@d8x/perpetuals-sdk
Version:
Node TypeScript SDK for D8X Perpetual Futures
795 lines (794 loc) • 36.3 kB
TypeScript
import { Contract, Overrides, Provider } from "ethers";
import { OrderStatus } from "./constants";
import { type LimitOrderBook, type Multicall3 } from "./contracts";
import { IPerpetualOrder, type PerpStorage } from "./contracts/IPerpetualManager";
import { type IClientOrder } from "./contracts/LimitOrderBook";
import { type ExchangeInfo, type MarginAccount, type NodeSDKConfig, type Order, type PerpetualState, type PerpetualStaticInfo, type PoolState, type PoolStaticInfo, type SmartContractOrder, type IdxPriceInfo, PythMetadata } from "./nodeSDKTypes";
import PerpetualDataHandler from "./perpetualDataHandler";
import PriceFeeds from "./priceFeeds";
/**
* Functions to access market data (e.g., information on open orders, information on products that can be traded).
* This class requires no private key and is blockchain read-only.
* No gas required for the queries here.
* @extends PerpetualDataHandler
*/
export default class MarketData extends PerpetualDataHandler {
/**
* Constructor
* @param {NodeSDKConfig} config Configuration object, see
* PerpetualDataHandler.readSDKConfig.
* @example
* import { MarketData, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
* async function main() {
* console.log(MarketData);
* // load configuration for Polygon zkEVM (testnet)
* const config = PerpetualDataHandler.readSDKConfig("cardona");
* // MarketData (read only, no authentication needed)
* let mktData = new MarketData(config);
* // Create a proxy instance to access the blockchain
* await mktData.createProxyInstance();
* }
* main();
*
*/
constructor(config: NodeSDKConfig);
/**
* Initialize the marketData-Class with this function
* to create instance of D8X perpetual contract and gather information
* about perpetual currencies
* @param provider optional provider to perform blockchain calls
*/
createProxyInstance(provider?: Provider, overrides?: Overrides): Promise<void>;
/**
* Initialize the marketData-Class with this function
* to create instance of D8X perpetual contract and gather information
* about perpetual currencies
* @param marketData Initialized market data object to save on blokchain calls
*/
createProxyInstance(marketData: MarketData): Promise<void>;
/**
* Get the proxy address
* @returns {string} Address of the perpetual proxy contract
*/
getProxyAddress(): string;
/**
* Get the pre-computed triangulations
* @returns Triangulations
*/
getTriangulations(): Map<string, [string[], boolean[]]>;
/**
* Convert the smart contract output of an order into a convenient format of type "Order"
* @param {SmartContractOrder} smOrder SmartContractOrder, as obtained e.g., by PerpetualLimitOrderCreated event
* @returns {Order} more convenient format of order, type "Order"
*/
smartContractOrderToOrder(smOrder: SmartContractOrder | IPerpetualOrder.OrderStruct | IPerpetualOrder.OrderStructOutput | IClientOrder.ClientOrderStruct | IClientOrder.ClientOrderStructOutput): Order;
/**
* Get contract instance. Useful for event listening.
* @example
* import { MarketData, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
* async function main() {
* console.log(MarketData);
* // setup
* const config = PerpetualDataHandler.readSDKConfig("cardona");
* let mktData = new MarketData(config);
* await mktData.createProxyInstance();
* // Get contract instance
* let proxy = await mktData.getReadOnlyProxyInstance();
* console.log(proxy);
* }
* main();
*
* @returns read-only proxy instance
*/
getReadOnlyProxyInstance(): import("./contracts").IPerpetualManager;
/**
* Information about the products traded in the exchange.
* @example
* import { MarketData, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
* async function main() {
* console.log(MarketData);
* // setup
* const config = PerpetualDataHandler.readSDKConfig("cardona");
* let mktData = new MarketData(config);
* await mktData.createProxyInstance();
* // Get exchange info
* let info = await mktData.exchangeInfo();
* console.log(info);
* }
* main();
*
* @returns {ExchangeInfo} Array of static data for all the pools and perpetuals in the system.
*/
exchangeInfo(overrides?: Overrides & {
rpcURL?: string;
}): Promise<ExchangeInfo>;
/**
* All open orders for a trader-address and a symbol.
* @param {string} traderAddr Address of the trader for which we get the open orders.
* @param {string} symbol Symbol of the form ETH-USD-MATIC or a pool symbol, or undefined.
* If a poolSymbol is provided, the response includes orders in all perpetuals of the given pool.
* If no symbol is provided, the response includes orders from all perpetuals in all pools.
* @example
* import { MarketData, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
* async function main() {
* console.log(MarketData);
* // setup
* const config = PerpetualDataHandler.readSDKConfig("cardona");
* let mktData = new MarketData(config);
* await mktData.createProxyInstance();
* // Get all open orders for a trader/symbol
* let opOrder = await mktData.openOrders("0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B",
* "ETH-USD-MATIC");
* console.log(opOrder);
* }
* main();
*
* @returns For each perpetual an array of open orders and corresponding order-ids.
*/
openOrders(traderAddr: string, symbol?: string, overrides?: Overrides & {
rpcURL?: string;
}): Promise<{
orders: Order[];
orderIds: string[];
}[]>;
/**
* All open orders for a trader-address and a given perpetual symbol.
* @param {string} traderAddr Address of the trader for which we get the open orders.
* @param {string} symbol perpetual-symbol of the form ETH-USD-MATIC
* @returns open orders and order ids
* @ignore
*/
private _openOrdersOfPerpetual;
/**
* All open orders for a trader-address and a given perpetual symbol.
* @param {string} traderAddr Address of the trader for which we get the open orders.
* @param {string} symbol perpetual-symbol of the form ETH-USD-MATIC
* @returns open orders and order ids
* @ignore
*/
private _openOrdersOfPerpetuals;
/**
* Information about the position open by a given trader in a given perpetual contract, or
* for all perpetuals in a pool
* @param {string} traderAddr Address of the trader for which we get the position risk.
* @param {string} symbol Symbol of the form ETH-USD-MATIC,
* or pool symbol ("MATIC") to get all positions in a given pool,
* or no symbol to get all positions in all pools.
* @example
* import { MarketData, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
* async function main() {
* console.log(MarketData);
* // setup
* const config = PerpetualDataHandler.readSDKConfig("cardona");
* let mktData = new MarketData(config);
* await mktData.createProxyInstance();
* // Get position risk info
* let posRisk = await mktData.positionRisk("0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B",
* "ETH-USD-MATIC");
* console.log(posRisk);
* }
* main();
*
* @returns {Array<MarginAccount>} Array of position risks of trader.
*/
positionRisk(traderAddr: string, symbol?: string, overrides?: Overrides & {
rpcURL?: string;
}): Promise<MarginAccount[]>;
/**
* Information about the position open by a given trader in a given perpetual contract.
* @param {string} traderAddr Address of the trader for which we get the position risk.
* @param {string} symbol perpetual symbol of the form ETH-USD-MATIC
* @returns MarginAccount struct for the trader
* @ignore
*/
protected _positionRiskForTraderInPerpetual(traderAddr: string, symbol: string, provider: Provider, overrides?: Overrides): Promise<MarginAccount>;
/**
* Information about the position open by a given trader in a given perpetual contract.
* @param {string} traderAddr Address of the trader for which we get the position risk.
* @param {string} symbol perpetual symbol of the form ETH-USD-MATIC
* @returns MarginAccount struct for the trader
* @ignore
*/
protected _positionRiskForTraderInPerpetuals(traderAddr: string, symbols: string[], provider: Provider, overrides?: Overrides): Promise<MarginAccount[]>;
private dataForPositionRiskOnTrade;
/**
* Estimates what the position risk will be if a given order is executed.
* @param traderAddr Address of trader
* @param order Order to be submitted
* @param signedPositionNotionalBaseCCY signed position notional of current position (before trade)
* @param tradingFeeTbps trading fee in tenth of basis points (exchange fee and broker fee)
* @param indexPriceInfo Index prices and market status (open/closed). Defaults to current market status if not given.
* @returns Position risk after trade, including order cost and maximal trade sizes for position
* @example
* import { MarketData, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
* async function main() {
* console.log(MarketData);
* // setup
* const config = PerpetualDataHandler.readSDKConfig("cardona");
* const mktData = new MarketData(config);
* await mktData.createProxyInstance();
* const order: Order = {
* symbol: "MATIC-USD-MATIC",
* side: "BUY",
* type: "MARKET",
* quantity: 100,
* leverage: 2,
* executionTimestamp: Date.now()/1000,
* };
* // Get position risk conditional on this order being executed
* const posRisk = await mktData.positionRiskOnTrade("0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B", order, 0, 60);
* console.log(posRisk);
* }
* main();
*/
positionRiskOnTrade(traderAddr: string, order: Order, signedPositionNotionalBaseCCY: number, tradingFeeTbps: number, indexPriceInfo?: IdxPriceInfo, overrides?: Overrides): Promise<{
newPositionRisk: MarginAccount;
orderCost: number;
maxLongTrade: number;
maxShortTrade: number;
ammPrice: number;
}>;
/**
* Fee is relative to base-currency amount (=trade amount)
* @param maxMaintMgnRate maintenance margin rate param for pred mkts
* @param Sm Mark price
* @param tradeAmtBC signed trade amount
* @param tradeMgnRate margin rate param from perpetual
* @returns relative exchange fee in decimals
*/
static exchangeFeePrdMkts(maxMaintMgnRate: number, Sm: number, tradeAmtBC: number, traderPosBC: number, tradeMgnRate: number): number;
/**
* Estimates what the position risk will be if given amount of collateral is added/removed from the account.
* @param {number} deltaCollateral Amount of collateral to add or remove (signed)
* @param {MarginAccount} account Position risk before collateral is added or removed
* @returns {MarginAccount} Position risk after collateral has been added/removed
* @example
* import { MarketData, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
* async function main() {
* console.log(MarketData);
* // setup
* const config = PerpetualDataHandler.readSDKConfig("cardona");
* const mktData = new MarketData(config);
* await mktData.createProxyInstance();
* // Get position risk conditional on removing 3.14 MATIC
* const traderAddr = "0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B";
* const curPos = await mktData.positionRisk("traderAddr", "BTC-USD-MATIC");
* const posRisk = await mktData.positionRiskOnCollateralAction(-3.14, curPos);
* console.log(posRisk);
* }
* main();
*/
positionRiskOnCollateralAction(deltaCollateral: number, account: MarginAccount, indexPriceInfo?: IdxPriceInfo, overrides?: Overrides): Promise<MarginAccount>;
/**
* Calculates liquidation prices for a position
* constructed in positionRiskOnTrade/positionRiskOnCollateralAction
* @param symbol Perpetual symbol
* @param lockedInQC Locked in value
* @param signedPositionBC Signed position size
* @param marginCashCC Available cash in margin account (includes unpaid funding)
* @param markPrice Mark price
* @param collToQuoteConversion Collateral index price (S3)
* @param S2 index price
* @param symbolToPerpStaticInfo Symbol-to-perp static info mapping
* @returns [Base index price, Collateral index price, Maintenance margin rate]
* @ignore
*/
protected static _getLiquidationParams(symbol: string, lockedInQC: number, signedPositionBC: number, marginCashCC: number, markPrice: number, collToQuoteConversion: number, S2: number, symbolToPerpStaticInfo: Map<string, PerpetualStaticInfo>): [number, number | undefined, number];
/**
* Gets the wallet balance in the settlement currency corresponding to a given perpetual symbol.
* The settlement currency is usually the same as the collateral currency.
* @param address Address to check
* @param symbol Symbol of the form ETH-USD-MATIC.
* @returns Perpetual's collateral token balance of the given address.
* @example
* import { MarketData, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
* async function main() {
* console.log(MarketData);
* // setup (authentication required, PK is an environment variable with a private key)
* const config = PerpetualDataHandler.readSDKConfig("cardona");
* let md = new MarketData(config);
* await md.createProxyInstance();
* // get MATIC balance of address
* let marginTokenBalance = await md.getWalletBalance(myaddress, "BTC-USD-MATIC");
* console.log(marginTokenBalance);
* }
* main();
*/
getWalletBalance(address: string, symbol: string, overrides?: Overrides): Promise<number>;
/**
* Get the address' balance of the pool share token
* @param {string} address address of the liquidity provider
* @param {string | number} symbolOrId Symbol of the form ETH-USD-MATIC, or MATIC (collateral only), or Pool-Id
* @returns {number} Pool share token balance of the given address (e.g. dMATIC balance)
* @example
* import { MarketData, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
* async function main() {
* console.log(MarketData);
* // setup (authentication required, PK is an environment variable with a private key)
* const config = PerpetualDataHandler.readSDKConfig("cardona");
* let md = new MarketData(config);
* await md.createProxyInstance();
* // get dMATIC balance of address
* let shareTokenBalance = await md.getPoolShareTokenBalance(myaddress, "MATIC");
* console.log(shareTokenBalance);
* }
* main();
*/
getPoolShareTokenBalance(address: string, symbolOrId: string | number, overrides?: Overrides): Promise<number>;
/**
* Query the pool share token holdings of address
* @param address address of token holder
* @param poolId pool id
* @returns pool share token balance of address
* @ignore
*/
private _getPoolShareTokenBalanceFromId;
/**
* Value of pool token in collateral currency
* @param {string | number} symbolOrId symbol of the form ETH-USD-MATIC, MATIC (collateral), or poolId
* @returns {number} current pool share token price in collateral currency
* @example
* import { MarketData, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
* async function main() {
* console.log(MarketData);
* // setup (authentication required, PK is an environment variable with a private key)
* const config = PerpetualDataHandler.readSDKConfig("cardona");
* let md = new MarketData(config);
* await md.createProxyInstance();
* // get price of 1 dMATIC in MATIC
* let shareTokenPrice = await md.getShareTokenPrice(myaddress, "MATIC");
* console.log(shareTokenPrice);
* }
* main();
*/
getShareTokenPrice(symbolOrId: string | number, overrides?: Overrides): Promise<number>;
/**
* Value of the pool share tokens for this liquidity provider
* in poolSymbol-currency (e.g. MATIC, USDC).
* @param {string} address address of liquidity provider
* @param {string | number} symbolOrId symbol of the form ETH-USD-MATIC, MATIC (collateral), or poolId
* @returns the value (in collateral tokens) of the pool share, #share tokens, shareTokenAddress
* @example
* import { MarketData, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
* async function main() {
* console.log(MarketData);
* // setup (authentication required, PK is an environment variable with a private key)
* const config = PerpetualDataHandler.readSDKConfig("cardona");
* let md = new MarketData(config);
* await md.createProxyInstance();
* // get value of pool share token
* let shareToken = await md.getParticipationValue(myaddress, "MATIC");
* console.log(shareToken);
* }
* main();
*/
getParticipationValue(address: string, symbolOrId: string | number, overrides?: Overrides): Promise<{
value: number;
shareTokenBalance: number;
poolShareToken: string;
}>;
/**
* Get pool id from symbol
* @param poolSymbolOrId Pool symbol or pool Id
* @returns Pool Id
* @ignore
*/
private _poolSymbolOrIdToPoolId;
/**
* Gets the maximal order sizes to open/close/flip positions, both long and short,
* considering the existing position, state of the perpetual
* Accounts for user's wallet balance only in rmMaxOrderSizeForTrader case.
* @param {string} traderAddr Address of trader
* @param {symbol} symbol Symbol of the form ETH-USD-MATIC
* @returns Maximal buy and sell trade sizes (positive)
* @example
* import { MarketData, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
* async function main() {
* console.log(MarketData);
* // setup (authentication required, PK is an environment variable with a private key)
* const config = PerpetualDataHandler.readSDKConfig("cardona");
* let md = new MarketData(config);
* await md.createProxyInstance();
* // max order sizes
* let shareToken = await md.maxOrderSizeForTrader(myaddress, "BTC-USD-MATIC");
* console.log(shareToken); // {buy: 314, sell: 415}
* }
* main();
*/
maxOrderSizeForTrader(traderAddr: string, symbol: string, overrides?: Overrides): Promise<{
buy: number;
sell: number;
}>;
/**
* pmMaxOrderSizeForTrader returns the max order size for the
* trader that is possible from AMM perspective (agnostic about wallet
* balance and leverage, also correct if trader is shrinking their position)
* @param traderAddr address of trader
* @param symbol perp symbol
* @param overrides optional
* @returns buy: number; sell: number absolute
*/
private pmMaxOrderSizeForTrader;
/**
* Returns the maximal allowed short trade and long trade (signed) for a trader
* that has a given notional (in ABDK format) in the perpetual, ignoring the traders wallet balance
* @param perpId
* @param currentTraderPos ABDK64x64 signed notional position of trader
* @param overrides
* @returns [maxShortPos, maxLongPos] signed maximal trade sizes
*/
getMaxShortLongTrade(perpId: number, currentTraderPos: bigint, overrides?: Overrides): Promise<[number, number]>;
/**
* Returns the maximal order size. Also applies to closing positions.
* @param traderAddr trader addr to get their position
* @param symbol symbol we are trading
* @param overrides
* @returns max buy and sell order size in absolute terms
*/
private rmMaxOrderSizeForTrader;
/**
* Perpetual-wide maximal signed position size in perpetual.
* @param side BUY_SIDE or SELL_SIDE
* @param {string} symbol of the form ETH-USD-MATIC.
* @returns {number} signed maximal position size in base currency
* @example
* import { MarketData, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
* async function main() {
* console.log(MarketData);
* // setup
* const config = PerpetualDataHandler.readSDKConfig("cardona");
* let mktData = new MarketData(config);
* await mktData.createProxyInstance();
* // get oracle price
* let maxLongPos = await mktData.maxSignedPosition(BUY_SIDE, "BTC-USD-MATIC");
* console.log(maxLongPos);
* }
* main();
*/
maxSignedPosition(side: string, symbol: string, overrides?: Overrides): Promise<number>;
/**
* Uses the Oracle(s) in the exchange to get the latest price of a given index in a given currency, if a route exists.
* @param {string} base Index name, e.g. ETH.
* @param {string} quote Quote currency, e.g. USD.
* @example
* import { MarketData, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
* async function main() {
* console.log(MarketData);
* // setup
* const config = PerpetualDataHandler.readSDKConfig("cardona");
* let mktData = new MarketData(config);
* await mktData.createProxyInstance();
* // get oracle price
* let price = await mktData.getOraclePrice("ETH", "USD");
* console.log(price);
* }
* main();
*
* @returns {number} Price of index in given currency.
*/
getOraclePrice(base: string, quote: string, overrides?: Overrides): Promise<[bigint, bigint]>;
/**
* Get the status of an order given a symbol and order Id
* @param symbol Symbol of the form ETH-USD-MATIC
* @param orderId Order Id
* @param overrides
* @returns Order status (cancelled = 0, executed = 1, open = 2, unkown = 3)
* @example
* import { MarketData, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
* async function main() {
* console.log(MarketData);
* // setup
* const config = PerpetualDataHandler.readSDKConfig("cardona");
* let mktData = new MarketData(config);
* await mktData.createProxyInstance();
* // get order stauts
* let status = await mktData.getOrderStatus("ETH-USD-MATIC", "0xmyOrderId");
* console.log(status);
* }
* main();
*
*/
getOrderStatus(symbol: string, orderId: string, overrides?: Overrides): Promise<OrderStatus>;
/**
* Get the status of an array of orders given a symbol and their Ids
* @param symbol Symbol of the form ETH-USD-MATIC
* @param orderId Array of order Ids
* @returns Array of order status
* @example
* import { MarketData, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
* async function main() {
* console.log(MarketData);
* // setup
* const config = PerpetualDataHandler.readSDKConfig("cardona");
* let mktData = new MarketData(config);
* await mktData.createProxyInstance();
* // get order stauts
* let status = await mktData.getOrdersStatus("ETH-USD-MATIC", ["0xmyOrderId1", "0xmyOrderId2"]);
* console.log(status);
* }
* main();
*
*/
getOrdersStatus(symbol: string, orderId: string[], overrides?: Overrides): Promise<OrderStatus[]>;
/**
* Get the current mark price
* @param symbol symbol of the form ETH-USD-MATIC
* @param indexPrices optional. IdxPriceInfo
* @example
* import { MarketData, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
* async function main() {
* console.log(MarketData);
* // setup
* const config = PerpetualDataHandler.readSDKConfig("cardona");
* let mktData = new MarketData(config);
* await mktData.createProxyInstance();
* // get mark price
* let price = await mktData.getMarkPrice("ETH-USD-MATIC");
* console.log(price);
* }
* main();
*
* @returns {number} mark price
*/
getMarkPrice(symbol: string, indexPrices?: IdxPriceInfo): Promise<number>;
/**
* get the current price for a given quantity
* @param symbol symbol of the form ETH-USD-MATIC
* @param quantity quantity to be traded, negative if short
* @param priceInfo [s2, s3, conf, params]; for non-prediction markets conf/params can be 0
* @example
* import { MarketData, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
* async function main() {
* console.log(MarketData);
* // setup
* const config = PerpetualDataHandler.readSDKConfig("cardona");
* let mktData = new MarketData(config);
* await mktData.createProxyInstance();
* // get perpetual price
* let price = await mktData.getPerpetualPrice("ETH-USD-MATIC", 1);
* console.log(price);
* }
* main();
*
* @returns {number} price
*/
getPerpetualPrice(symbol: string, quantity: number, priceInfo?: IdxPriceInfo, overrides?: Overrides): Promise<number>;
/**
* Query recent perpetual state from blockchain
* @param {string} symbol symbol of the form ETH-USD-MATIC
* @returns {PerpetualState} PerpetualState copy
*/
getPerpetualState(symbol: string, indexPriceInfo?: IdxPriceInfo, overrides?: Overrides): Promise<PerpetualState>;
/**
* Query recent pool state from blockchain, not including perpetual states
* @param {string} poolSymbol symbol of the form USDC
* @returns {PoolState} PoolState copy
*/
getPoolState(poolSymbol: string, overrides?: Overrides): Promise<PoolState>;
/**
* Query perpetual static info.
* This information is queried once at createProxyInstance-time, and remains static after that.
* @param {string} symbol Perpetual symbol
*
* @returns {PerpetualStaticInfo} Perpetual static info copy.
*/
getPerpetualStaticInfo(symbol: string): PerpetualStaticInfo;
/**
* get the current mid-price for a perpetual
* @param symbol symbol of the form ETH-USD-MATIC
* @example
* import { MarketData, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
* async function main() {
* console.log(MarketData);
* // setup
* const config = PerpetualDataHandler.readSDKConfig("cardona");
* let mktData = new MarketData(config);
* await mktData.createProxyInstance();
* // get perpetual mid price
* let midPrice = await mktData.getPerpetualMidPrice("ETH-USD-MATIC");
* console.log(midPrice);
* }
* main();
*
* @returns {number} price
*/
getPerpetualMidPrice(symbol: string): Promise<number>;
/**
* Query smart contract to get user orders and convert to user friendly order format.
* @param {string} traderAddr Address of trader.
* @param {ethers.Contract} orderBookContract Instance of order book.
* @returns {Order[]} Array of user friendly order struct.
* @ignore
*/
protected static openOrdersOnOrderBook(traderAddr: string, orderBookContract: LimitOrderBook, symbolToPerpStaticInfo: Map<string, PerpetualStaticInfo>, overrides?: Overrides): Promise<Order[]>;
/**
* Query smart contract to get user orders and convert to user friendly order format.
* @param {string} traderAddr Address of trader.
* @param {ethers.Contract} orderBookContract Instance of order book.
* @returns {Order[]} Array of user friendly order struct.
* @ignore
*/
protected static _openOrdersOnOrderBooks(traderAddr: string, orderBookContracts: LimitOrderBook[], multicall: Multicall3, symbolToPerpStaticInfo: Map<string, PerpetualStaticInfo>, overrides?: Overrides): Promise<{
orders: Order[][];
digests: string[][];
}>;
/**
*
* @param {string} traderAddr Address of the trader
* @param {LimitOrderBook} orderBookContract Instance of order book contract
* @returns Array of order-id's
* @ignore
*/
static orderIdsOfTrader(traderAddr: string, orderBookContract: LimitOrderBook, overrides?: Overrides): Promise<string[]>;
/**
* Query the available margin conditional on the given (or current) index prices
* Result is in collateral currency
* @param {string} traderAddr address of the trader
* @param {string} symbol perpetual symbol of the form BTC-USD-MATIC
* @param indexPrices optional indexPriceInfo
* @returns available margin in collateral currency
* @example
* import { MarketData, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
* async function main() {
* console.log(MarketData);
* // setup
* const config = PerpetualDataHandler.readSDKConfig("cardona");
* let mktData = new MarketData(config);
* await mktData.createProxyInstance();
* // get available margin
* let mgn = await mktData.getAvailableMargin("0xmyAddress", "ETH-USD-MATIC");
* console.log(mgn);
* }
* main();
*/
getAvailableMargin(traderAddr: string, symbol: string, indexPrices?: IdxPriceInfo, overrides?: Overrides): Promise<number>;
/**
* Calculate a type of exchange loyality score based on trader volume
* @param {string} traderAddr address of the trader
* @returns {number} a loyality score (4 worst, 1 best)
* @example
* import { MarketData, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
* async function main() {
* console.log(MarketData);
* // setup
* const config = PerpetualDataHandler.readSDKConfig("cardona");
* let mktData = new MarketData(config);
* await mktData.createProxyInstance();
* // get scpre
* let s = await mktData.getTraderLoyalityScore("0xmyAddress");
* console.log(s);
* }
* main();
*/
getTraderLoyalityScore(traderAddr: string, overrides?: Overrides): Promise<number>;
/**
* Get all off-chain prices for normal perps
* @param _symbolToPerpStaticInfo mapping: PerpetualStaticInfo for each perpetual
* @param _priceFeedGetter priceFeed class from which we can get offchain price data
* @returns mapping of symbol-pair (e.g. BTC-USD) to price/isMarketClosed
* @ignore
*/
private static _getAllActivePerpIndexPrices;
/**
* Get market open/closed status
* @param {string} symbol Perpetual symbol of the form ETH-USD-MATIC
* @returns {boolean} True if the market is closed
* @example
* import { MarketData, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
* async function main() {
* console.log(MarketData);
* // setup
* const config = PerpetualDataHandler.readSDKConfig("cardona");
* let mktData = new MarketData(config);
* await mktData.createProxyInstance();
* // is market closed?
* let s = await mktData.isMarketClosed("ETH-USD-MATIC");
* console.log(s);
* }
* main();
*/
isMarketClosed(symbol: string): Promise<boolean>;
/**
* Market status based on off-chain info
* @param symbol Perp symbol
* @param _symbolToPerpStaticInfo Static info mapping
* @param _priceFeedGetter Price getter instance
* @ignore
*/
private static _isMarketClosed;
/**
* Collect all mid-prices
* @param _proxyContract contract instance
* @param _poolStaticInfos static info to get whether pool is active or not
* @param _nestedPerpetualIDs contains all perpetual ids for each pool
* @param _symbolToPerpStaticInfo maps symbol to static info
* @param _perpetualIdToSymbol maps perpetual id to symbol of the form BTC-USD-MATIC
* @param _idxPriceMap symbol to price/market closed
* @returns perpetual symbol to mid-prices mapping
* @ignore
*/
private static _queryMidPrices;
/**
* Query the on-chain state of all pools and perpeetuals
* @param _proxyContract Proxy contract
* @param _multicall Multicall contract
* @param _poolStaticInfos Static info array
* @param _symbolList Symbol to on-chain symbol mapping
* @param _nestedPerpetualIDs All perpetual Ids
* @ignore
*/
private static _queryPoolAndPerpetualStates;
protected static _marginAccountsToPosBC(ms: PerpStorage.MarginAccountStructOutput[], p: PerpStorage.PerpetualDataStructOutput[]): Array<[bigint, bigint]>;
/**
* Parse liquidity pool state obtained on-chain
* @param _liquidityPools
* @param _poolStaticInfos
* @ignore
*/
protected static _poolDataToPoolState(_liquidityPools: Partial<PerpStorage.LiquidityPoolDataStructOutput>[], _poolStaticInfos: PoolStaticInfo[]): PoolState[];
/**
* Parse perpetual states obtained on-chain
* @param _perpetuals
* @param _symbolList
* @ignore
*/
protected static _perpetualDataToPerpetualState(_perpetuals: any[], _longShortBC: [bigint, bigint][], _symbolList: Map<string, string>): PerpetualState[];
/**
* Fetch on-chain exchange info
* @param _proxyContract
* @param _multicall
* @param _poolStaticInfos
* @param _symbolToPerpStaticInfo
* @param _perpetualIdToSymbol
* @param _nestedPerpetualIDs
* @param _symbolList
* @param _priceFeedGetter
* @param _oracleFactoryAddr
* @param overrides
* @ignore
*/
static _exchangeInfo(_proxyContract: Contract, _multicall: Multicall3, _poolStaticInfos: Array<PoolStaticInfo>, _symbolToPerpStaticInfo: Map<string, PerpetualStaticInfo>, _perpetualIdToSymbol: Map<number, string>, _nestedPerpetualIDs: Array<Array<number>>, _symbolList: Map<string, string>, _priceFeedGetter: PriceFeeds, _oracleFactoryAddr: string, overrides?: Overrides): Promise<ExchangeInfo>;
/**
* Get the latest on-chain price of a perpetual base index in USD.
* @param {string} symbol Symbol of the form ETH-USDC-MATIC.
* If a pool symbol is used, it returns an array of all the USD prices of the indices in the pool.
* If no argument is provided, it returns all prices of all the indices in the pools of the exchange.
* @return {Map<string, number>} Price of the base index in USD, e.g. for ETH-USDC-MATIC, it returns the value of ETH-USD.
* @example
* import { MarketData, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
* async function main() {
* console.log(MarketData);
* // setup
* const config = PerpetualDataHandler.readSDKConfig("cardona");
* let mktData = new MarketData(config);
* await mktData.createProxyInstance();
* // is market closed?
* let px = await mktData.getPriceInUSD("ETH-USDC-USDC");
* console.log(px); // {'ETH-USD' -> 1800}
* }
* main();
*
*/
getPriceInUSD(symbol?: string): Promise<Map<string, number>>;
/**
* Fetch latest off-chain index and collateral prices
* @param symbol Perpetual symbol of the form BTC-USDc-USDC
* @returns Prices and market-closed information
*/
fetchPricesForPerpetual(symbol: string): Promise<IdxPriceInfo>;
/**
* fetch prediction markets meta data
* @param symbol symbol of the form "TRUMP24-USD"
* @returns question for given symbol
*/
fetchPrdMktMetaData(symbol: string): Promise<string>;
/**
* Fetch Pyth metadata of a given symbol.
* The priority is:
* 1. Full match: first feed with exact symbol BERA-USD
* 2. Partial match: if no full match is found, search for first feed with symbol BERA-XYZ
* @param symbol symbol of the form "BERA-USD"
* @returns description of feed underlying given symbol
*/
fetchPythMetaData(symbol: string): Promise<PythMetadata>;
}