@d8x/perpetuals-sdk
Version:
Node TypeScript SDK for D8X Perpetual Futures
1,048 lines (859 loc) • 461 kB
Markdown
## Modules
<dl>
<dt><a href="#module_d8xMath">d8xMath</a></dt>
<dd></dd>
<dt><a href="#module_utils">utils</a></dt>
<dd></dd>
</dl>
## Classes
<dl>
<dt><a href="#AccountTrade">AccountTrade</a> ⇐ <code><a href="#WriteAccessHandler">WriteAccessHandler</a></code></dt>
<dd><p>Functions to create, submit and cancel orders on the exchange.
This class requires a private key and executes smart-contract interactions that
require gas-payments.</p></dd>
<dt><a href="#BrokerTool">BrokerTool</a> ⇐ <code><a href="#WriteAccessHandler">WriteAccessHandler</a></code></dt>
<dd><p>Functions for white-label partners to determine fees, deposit lots, and sign-up traders.
This class requires a private key and executes smart-contract interactions that
require gas-payments.</p></dd>
<dt><a href="#LiquidatorTool">LiquidatorTool</a> ⇐ <code><a href="#WriteAccessHandler">WriteAccessHandler</a></code></dt>
<dd><p>Functions to liquidate traders. This class requires a private key
and executes smart-contract interactions that require gas-payments.</p></dd>
<dt><a href="#LiquidityProviderTool">LiquidityProviderTool</a> ⇐ <code><a href="#WriteAccessHandler">WriteAccessHandler</a></code></dt>
<dd><p>Functions to provide liquidity. This class requires a private key and executes
smart-contract interactions that require gas-payments.</p></dd>
<dt><a href="#MarketData">MarketData</a> ⇐ <code><a href="#PerpetualDataHandler">PerpetualDataHandler</a></code></dt>
<dd><p>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.</p></dd>
<dt><a href="#OnChainPxFeed">OnChainPxFeed</a></dt>
<dd><p>OnChainPxFeed: get a price from a chainlink-style oracle</p></dd>
<dt><a href="#OnChainPxFeedAngle">OnChainPxFeedAngle</a></dt>
<dd><p>OnChainPxFeedAngle: get STUSD-USDC exchange rate</p></dd>
<dt><a href="#OnChainPxFeedRedStone">OnChainPxFeedRedStone</a></dt>
<dd><p>OnChainPxFeedRedStone: get a price from a chainlink-style oracle</p></dd>
<dt><a href="#OrderExecutorTool">OrderExecutorTool</a> ⇐ <code><a href="#WriteAccessHandler">WriteAccessHandler</a></code></dt>
<dd><p>Functions to execute existing conditional orders from the limit order book. This class
requires a private key and executes smart-contract interactions that require
gas-payments.</p></dd>
<dt><a href="#PerpetualDataHandler">PerpetualDataHandler</a></dt>
<dd><p>Parent class for MarketData and WriteAccessHandler that handles
common data and chain operations.</p></dd>
<dt><a href="#PerpetualEventHandler">PerpetualEventHandler</a></dt>
<dd><p>This class handles events and stores relevant variables
as member variables. The events change the state of the member variables:
mktData : MarketData relevant market data with current state (e.g. index price)
ordersInPerpetual: Map<number, OrderStruct> all open orders for the given trader
positionInPerpetual: Map<number, MarginAccount> all open positions for the given trader</p>
<p>Get data:</p>
<ul>
<li>getPerpetualData(perp id (string) or symbol) : PerpetualState. This is a reference!</li>
<li>getExchangeInfo() : ExchangeInfo. This is a reference!</li>
<li>getCurrentPositionRisk(perp id (string) or symbol) : MarginAccount. This is a reference!</li>
<li>getOrdersInPerpetualMap : Map<number, OrderStruct>. This is a reference!</li>
<li>getpositionInPerpetualMap : Map<number, MarginAccount>. This is a reference!</li>
</ul>
<p>Construct with a trader address and a marketData object
Initialize to gather all the relevant data.
Send event variables to event handler "on<EventName>" - this updates members</p>
<ul>
<li>[x] onUpdateMarkPrice : emitted on proxy; updates markprice and index price data</li>
<li>[x] onUpdateUpdateFundingRate : emitted on proxy; sets funding rate</li>
<li>[x] onExecutionFailed : emitted on order book; removes an open order</li>
<li>[x] onPerpetualLimitOrderCancelled : emitted on order book; removes an open order</li>
<li>[x] onPerpetualLimitOrderCreated : emitted on order book; adds an open order to the data</li>
<li>[x] async onUpdateMarginAccount : emitted on proxy; updates position data and open interest</li>
<li>[x] onTrade : emitted on proxy; returns TradeEvent to be displayed</li>
</ul></dd>
<dt><a href="#PolyMktsPxFeed">PolyMktsPxFeed</a></dt>
<dd><p>PolyMktsPxFeed gets prices from the official polymarket api
and applies the 1+px transformation</p></dd>
<dt><a href="#PriceFeeds">PriceFeeds</a></dt>
<dd><p>This class communicates with the REST API that provides price-data that is
to be submitted to the smart contracts for certain functions such as
trader liquidations, trade executions, change of trader margin amount.</p></dd>
<dt><a href="#ReferralCodeSigner">ReferralCodeSigner</a></dt>
<dd><p>This is a 'standalone' class that deals with signatures
required for referral codes:</p>
<ul>
<li>referrer creates a new referral code for trader (no agency involved)</li>
<li>agency creates a new referral code for a referrer and their trader</li>
<li>trader selects a referral code to trade with</li>
</ul>
<p>Note that since the back-end is chain specific, the referral code is typically bound to
one chain, unless the backend employs code transferrals</p></dd>
<dt><a href="#TraderInterface">TraderInterface</a> ⇐ <code><a href="#MarketData">MarketData</a></code></dt>
<dd><p>Interface that can be used by front-end that wraps all private functions
so that signatures can be handled in frontend via wallet</p></dd>
<dt><a href="#WriteAccessHandler">WriteAccessHandler</a> ⇐ <code><a href="#PerpetualDataHandler">PerpetualDataHandler</a></code></dt>
<dd><p>This is a parent class for the classes that require
write access to the contracts.
This class requires a private key and executes smart-contract interaction that
require gas-payments.</p></dd>
</dl>
## Members
<dl>
<dt><a href="#default">default</a> ⇒</dt>
<dd><p>Gets the price of one Angle stUSD in USDC from
on-chain</p></dd>
</dl>
## Constants
<dl>
<dt><a href="#referralDomain">referralDomain</a></dt>
<dd><p>LiquidityPoolData corresponding to the data in the smart contract</p></dd>
</dl>
## Typedefs
<dl>
<dt><a href="#ExchangeInfo">ExchangeInfo</a> : <code>Object</code></dt>
<dd></dd>
<dt><a href="#PoolState">PoolState</a> : <code>Object</code></dt>
<dd></dd>
<dt><a href="#SmartContractOrder">SmartContractOrder</a> : <code>Object</code></dt>
<dd></dd>
<dt><a href="#ClientOrder">ClientOrder</a> : <code>Object</code></dt>
<dd></dd>
</dl>
<a name="module_d8xMath"></a>
## d8xMath
* [d8xMath](#module_d8xMath)
* [~ABDK29ToFloat(x)](#module_d8xMath..ABDK29ToFloat) ⇒ <code>number</code>
* [~ABK64x64ToFloat(x)](#module_d8xMath..ABK64x64ToFloat) ⇒ <code>number</code>
* [~decNToFloat(x)](#module_d8xMath..decNToFloat) ⇒ <code>number</code>
* [~dec18ToFloat(x)](#module_d8xMath..dec18ToFloat) ⇒ <code>number</code>
* [~floatToABK64x64(x)](#module_d8xMath..floatToABK64x64) ⇒ <code>bigint</code>
* [~floatToDec18(x)](#module_d8xMath..floatToDec18) ⇒ <code>BigNumber</code>
* [~floatToDecN(x, decimals)](#module_d8xMath..floatToDecN) ⇒ <code>BigNumber</code>
* [~countDecimalsOf(x, precision)](#module_d8xMath..countDecimalsOf) ⇒
* [~roundToLotString(x, lot, precision)](#module_d8xMath..roundToLotString) ⇒
* [~mul64x64(x, y)](#module_d8xMath..mul64x64) ⇒ <code>bigint</code>
* [~div64x64(x, y)](#module_d8xMath..div64x64) ⇒ <code>bigint</code>
* [~calculateLiquidationPriceCollateralBase(LockedInValueQC, position, cash_cc, maintenance_margin_rate, S3)](#module_d8xMath..calculateLiquidationPriceCollateralBase) ⇒ <code>number</code>
* [~calculateLiquidationPriceCollateralQuantoConservative(LockedInValueQC, position, cash_cc, maintenance_margin_rate, S3, Sm)](#module_d8xMath..calculateLiquidationPriceCollateralQuantoConservative) ⇒ <code>number</code>
* [~calculateLiquidationPriceCollateralQuanto(LockedInValueQC, position, cash_cc, maintenance_margin_rate, S3, Sm)](#module_d8xMath..calculateLiquidationPriceCollateralQuanto) ⇒ <code>number</code>
* [~calculateLiquidationPriceCollateralQuote(LockedInValueQC, position, cash_cc, maintenance_margin_rate, S3)](#module_d8xMath..calculateLiquidationPriceCollateralQuote) ⇒ <code>number</code>
* [~getMarginRequiredForLeveragedTrade(targetLeverage, currentPosition, currentLockedInValue, tradeAmount, markPrice, indexPriceS2, indexPriceS3, tradePrice, feeRate)](#module_d8xMath..getMarginRequiredForLeveragedTrade) ⇒ <code>number</code>
* [~getNewPositionLeverage(tradeAmount, marginCollateral, currentPosition, currentLockedInValue, price, indexPriceS3, markPrice)](#module_d8xMath..getNewPositionLeverage) ⇒
* [~getDepositAmountForLvgTrade(pos0, b0, tradeAmnt, targetLvg, price, S3, S2Mark, cmin)](#module_d8xMath..getDepositAmountForLvgTrade) ⇒ <code>number</code>
* [~getDepositAmountForPredMktLvgTrade(pos0, b0, c0, tradeAmnt, targetLvg, prob, S3, markProb, imr)](#module_d8xMath..getDepositAmountForPredMktLvgTrade) ⇒ <code>number</code>
* [~newPos](#module_d8xMath..getDepositAmountForPredMktLvgTrade..newPos)
* [~priceToProb(px)](#module_d8xMath..priceToProb) ⇒
* [~probToPrice(prob)](#module_d8xMath..probToPrice) ⇒
* [~pmMarginThresh(pos, lockedInQC, s2, s3, m)](#module_d8xMath..pmMarginThresh) ⇒
* [~pmInitialMarginRate(posSign, s0, sm, cmin)](#module_d8xMath..pmInitialMarginRate) ⇒ <code>number</code>
* [~pmExchangeFee(prob, m, tradeAmt, tradeMgnRate)](#module_d8xMath..pmExchangeFee) ⇒
* [~pmMarginBalance(pos, s2, s3, ell, mc)](#module_d8xMath..pmMarginBalance) ⇒
* [~pmFindLiquidationPrice(pos, s3, ell, mc, baseMarginRate, sm)](#module_d8xMath..pmFindLiquidationPrice) ⇒ <code>number</code>
* [~excessMargin(tradeAmt, currentCashCC, currentPos, currentLockedInQC, limitPrice, Sm, S3)](#module_d8xMath..excessMargin) ⇒
* [~pmGetDepositAmtForLvgTrade(tradeAmt, targetLvg, price, S3, S2Mark)](#module_d8xMath..pmGetDepositAmtForLvgTrade) ⇒
* [~pmExcessCashAtLvg(tradeAmt, lvg, walletBalCC, currentCashCC, currentPosition, currentLockedInValue, slippage, S2, Sm, S3, totLong, totShort)](#module_d8xMath..pmExcessCashAtLvg) ⇒
* [~pmFindMaxPersonalTradeSizeAtLeverage(dir, lvg, walletBalCC, slippage, currentPosition, currentCashCC, currentLockedInValue, S2, Sm, S3, glblMaxTrade)](#module_d8xMath..pmFindMaxPersonalTradeSizeAtLeverage) ⇒
* [~pmMaxSignedOpenTradeSize(long, short, sm, isBuy, mr)](#module_d8xMath..pmMaxSignedOpenTradeSize)
<a name="module_d8xMath..ABDK29ToFloat"></a>
### d8xMath~ABDK29ToFloat(x) ⇒ <code>number</code>
<p>Convert ABK64x64/2^35 bigint-format to float.
Divide by 2^64 to get a float, but it's already "divided" by 2^35,
so there's only 2^29 left</p>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <code>number</code> - <p>x/2^64 in number-format (float)</p>
| Param | Type | Description |
| --- | --- | --- |
| x | <code>BigNumber</code> \| <code>number</code> | <p>number in ABDK-format/2^35</p> |
<a name="module_d8xMath..ABK64x64ToFloat"></a>
### d8xMath~ABK64x64ToFloat(x) ⇒ <code>number</code>
<p>Convert ABK64x64 bigint-format to float.
Result = x/2^64 if big number, x/2^29 if number</p>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <code>number</code> - <p>x/2^64 in number-format (float)</p>
| Param | Type | Description |
| --- | --- | --- |
| x | <code>BigNumberish</code> \| <code>number</code> | <p>number in ABDK-format or 2^29</p> |
<a name="module_d8xMath..decNToFloat"></a>
### d8xMath~decNToFloat(x) ⇒ <code>number</code>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <code>number</code> - <p>x as a float (number)</p>
| Param | Type | Description |
| --- | --- | --- |
| x | <code>BigNumberish</code> | <p>BigNumber in Dec-N format</p> |
<a name="module_d8xMath..dec18ToFloat"></a>
### d8xMath~dec18ToFloat(x) ⇒ <code>number</code>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <code>number</code> - <p>x as a float (number)</p>
| Param | Type | Description |
| --- | --- | --- |
| x | <code>BigNumberish</code> | <p>BigNumber in Dec18 format</p> |
<a name="module_d8xMath..floatToABK64x64"></a>
### d8xMath~floatToABK64x64(x) ⇒ <code>bigint</code>
<p>Converts x into ABDK64x64 format</p>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <code>bigint</code> - <p>x^64 in big number format</p>
| Param | Type | Description |
| --- | --- | --- |
| x | <code>number</code> | <p>number (float)</p> |
<a name="module_d8xMath..floatToDec18"></a>
### d8xMath~floatToDec18(x) ⇒ <code>BigNumber</code>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <code>BigNumber</code> - <p>x as a BigNumber in Dec18 format</p>
| Param | Type | Description |
| --- | --- | --- |
| x | <code>number</code> | <p>number (float)</p> |
<a name="module_d8xMath..floatToDecN"></a>
### d8xMath~floatToDecN(x, decimals) ⇒ <code>BigNumber</code>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <code>BigNumber</code> - <p>x as a BigNumber in Dec18 format</p>
| Param | Type | Description |
| --- | --- | --- |
| x | <code>number</code> | <p>number (float)</p> |
| decimals | <code>number</code> | <p>number of decimals</p> |
<a name="module_d8xMath..countDecimalsOf"></a>
### d8xMath~countDecimalsOf(x, precision) ⇒
<p>9 are rounded up regardless of precision, e.g, 0.1899000 at precision 6 results in 3</p>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <p>number of decimals</p>
| Param | Type |
| --- | --- |
| x | <code>number</code> |
| precision | <code>number</code> |
<a name="module_d8xMath..roundToLotString"></a>
### d8xMath~roundToLotString(x, lot, precision) ⇒
<p>Round a number to a given lot size and return a string formated
to for this lot-size</p>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <p>formated number string</p>
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| x | <code>number</code> | | <p>number to round</p> |
| lot | <code>number</code> | | <p>lot size (could be 'uneven' such as 0.019999999 instead of 0.02)</p> |
| precision | <code>number</code> | <code>7</code> | <p>optional lot size precision (e.g. if 0.01999 should be 0.02 then precision could be 5)</p> |
<a name="module_d8xMath..mul64x64"></a>
### d8xMath~mul64x64(x, y) ⇒ <code>bigint</code>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <code>bigint</code> - <p>x * y</p>
| Param | Type |
| --- | --- |
| x | <code>bigint</code> |
| y | <code>bigint</code> |
<a name="module_d8xMath..div64x64"></a>
### d8xMath~div64x64(x, y) ⇒ <code>bigint</code>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <code>bigint</code> - <p>x / y</p>
| Param | Type |
| --- | --- |
| x | <code>bigint</code> |
| y | <code>bigint</code> |
<a name="module_d8xMath..calculateLiquidationPriceCollateralBase"></a>
### d8xMath~calculateLiquidationPriceCollateralBase(LockedInValueQC, position, cash_cc, maintenance_margin_rate, S3) ⇒ <code>number</code>
<p>Determine the liquidation price</p>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <code>number</code> - <p>Amount to be deposited to have the given leverage when trading into position pos</p>
| Param | Type | Description |
| --- | --- | --- |
| LockedInValueQC | <code>number</code> | <p>trader locked in value in quote currency</p> |
| position | <code>number</code> | <p>trader position in base currency</p> |
| cash_cc | <code>number</code> | <p>trader available margin cash in collateral currency</p> |
| maintenance_margin_rate | <code>number</code> | <p>maintenance margin ratio</p> |
| S3 | <code>number</code> | <p>collateral to quote conversion (=S2 if base-collateral, =1 if quuote collateral, = index S3 if quanto)</p> |
<a name="module_d8xMath..calculateLiquidationPriceCollateralQuantoConservative"></a>
### d8xMath~calculateLiquidationPriceCollateralQuantoConservative(LockedInValueQC, position, cash_cc, maintenance_margin_rate, S3, Sm) ⇒ <code>number</code>
<p>Determine the liquidation price</p>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <code>number</code> - <p>Amount to be deposited to have the given leverage when trading into position pos</p>
| Param | Type | Description |
| --- | --- | --- |
| LockedInValueQC | <code>number</code> | <p>trader locked in value in quote currency</p> |
| position | <code>number</code> | <p>trader position in base currency</p> |
| cash_cc | <code>number</code> | <p>trader available margin cash in collateral currency</p> |
| maintenance_margin_rate | <code>number</code> | <p>maintenance margin ratio</p> |
| S3 | <code>number</code> | <p>collateral to quote conversion (=S2 if base-collateral, =1 if quuote collateral, = index S3 if quanto)</p> |
| Sm | <code>number</code> | <p>mark price</p> |
<a name="module_d8xMath..calculateLiquidationPriceCollateralQuanto"></a>
### d8xMath~calculateLiquidationPriceCollateralQuanto(LockedInValueQC, position, cash_cc, maintenance_margin_rate, S3, Sm) ⇒ <code>number</code>
<p>Determine the liquidation price for quanto -- assuming quanto currency value remains constant
See calculateLiquidationPriceCollateralQuantoConservative for a more conservative version</p>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <code>number</code> - <p>Amount to be deposited to have the given leverage when trading into position pos</p>
| Param | Type | Description |
| --- | --- | --- |
| LockedInValueQC | <code>number</code> | <p>trader locked in value in quote currency</p> |
| position | <code>number</code> | <p>trader position in base currency</p> |
| cash_cc | <code>number</code> | <p>trader available margin cash in collateral currency</p> |
| maintenance_margin_rate | <code>number</code> | <p>maintenance margin ratio</p> |
| S3 | <code>number</code> | <p>collateral to quote conversion (=S2 if base-collateral, =1 if quuote collateral, = index S3 if quanto)</p> |
| Sm | <code>number</code> | <p>mark price</p> |
<a name="module_d8xMath..calculateLiquidationPriceCollateralQuote"></a>
### d8xMath~calculateLiquidationPriceCollateralQuote(LockedInValueQC, position, cash_cc, maintenance_margin_rate, S3) ⇒ <code>number</code>
<p>Determine the liquidation price</p>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <code>number</code> - <p>Amount to be deposited to have the given leverage when trading into position pos</p>
| Param | Type | Description |
| --- | --- | --- |
| LockedInValueQC | <code>number</code> | <p>trader locked in value in quote currency</p> |
| position | <code>number</code> | <p>trader position in base currency</p> |
| cash_cc | <code>number</code> | <p>trader available margin cash in collateral currency</p> |
| maintenance_margin_rate | <code>number</code> | <p>maintenance margin ratio</p> |
| S3 | <code>number</code> | <p>collateral to quote conversion (=S2 if base-collateral, =1 if quuote collateral, = index S3 if quanto)</p> |
<a name="module_d8xMath..getMarginRequiredForLeveragedTrade"></a>
### d8xMath~getMarginRequiredForLeveragedTrade(targetLeverage, currentPosition, currentLockedInValue, tradeAmount, markPrice, indexPriceS2, indexPriceS3, tradePrice, feeRate) ⇒ <code>number</code>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <code>number</code> - <p>Total collateral amount needed for the new position to have he desired leverage.</p>
| Param | Description |
| --- | --- |
| targetLeverage | <p>Leverage of the resulting position. It must be positive unless the resulting position is closed.</p> |
| currentPosition | <p>Current position size, in base currency, signed.</p> |
| currentLockedInValue | <p>Current locked in value, average entry price times position size, in quote currency.</p> |
| tradeAmount | <p>Trade amount, in base currency, signed.</p> |
| markPrice | <p>Mark price, positive.</p> |
| indexPriceS2 | <p>Index price, positive.</p> |
| indexPriceS3 | <p>Collateral index price, positive.</p> |
| tradePrice | <p>Expected price to trade tradeAmount.</p> |
| feeRate | |
<a name="module_d8xMath..getNewPositionLeverage"></a>
### d8xMath~getNewPositionLeverage(tradeAmount, marginCollateral, currentPosition, currentLockedInValue, price, indexPriceS3, markPrice) ⇒
<p>Compute the leverage resulting from a trade</p>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <p>Leverage of the resulting position</p>
| Param | Description |
| --- | --- |
| tradeAmount | <p>Amount to trade, in base currency, signed</p> |
| marginCollateral | <p>Amount of cash in the margin account, in collateral currency</p> |
| currentPosition | <p>Position size before the trade</p> |
| currentLockedInValue | <p>Locked-in value before the trade</p> |
| price | <p>Price charged to trade tradeAmount</p> |
| indexPriceS3 | <p>Spot price of the collateral currency when the trade happens</p> |
| markPrice | <p>Mark price of the index when the trade happens</p> |
<a name="module_d8xMath..getDepositAmountForLvgTrade"></a>
### d8xMath~getDepositAmountForLvgTrade(pos0, b0, tradeAmnt, targetLvg, price, S3, S2Mark, cmin) ⇒ <code>number</code>
<p>Determine amount to be deposited into margin account so that the given leverage
is obtained when trading a position pos (trade amount = position)
Does NOT include fees
Smart contract equivalent: calcMarginForTargetLeverage(..., _ignorePosBalance = false & balance = b0)</p>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <code>number</code> - <p>Amount to be deposited to have the given leverage when trading into position pos before fees</p>
| Param | Type | Description |
| --- | --- | --- |
| pos0 | <code>number</code> | <p>current position</p> |
| b0 | <code>number</code> | <p>current balance</p> |
| tradeAmnt | <code>number</code> | <p>amount to trade</p> |
| targetLvg | <code>number</code> | <p>target leverage</p> |
| price | <code>number</code> | <p>price to trade amount 'tradeAmnt'</p> |
| S3 | <code>number</code> | <p>collateral to quote conversion (=S2 if base-collateral, =1 if quote collateral, = index S3 if quanto)</p> |
| S2Mark | <code>number</code> | <p>mark price</p> |
| cmin | <code>number</code> | <p>Absolute minimum margin per contract, only for pred markets</p> |
<a name="module_d8xMath..getDepositAmountForPredMktLvgTrade"></a>
### d8xMath~getDepositAmountForPredMktLvgTrade(pos0, b0, c0, tradeAmnt, targetLvg, prob, S3, markProb, imr) ⇒ <code>number</code>
<p>Determine amount to be deposited into margin account so that the given leverage
is obtained when opening a prediction market position
Does NOT include fees, but accounts for a possible non-zero current position
Smart contract equivalent: getDepositAmountForPredMktLvgPosition</p>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <code>number</code> - <p>Amount to be deposited to have the given leverage when trading into position pos before fees</p>
| Param | Type | Description |
| --- | --- | --- |
| pos0 | <code>number</code> | <p>current position</p> |
| b0 | <code>number</code> | <p>current balance</p> |
| c0 | <code>number</code> | <p>current available cash</p> |
| tradeAmnt | <code>number</code> | <p>amount to trade</p> |
| targetLvg | <code>number</code> | <p>target leverage</p> |
| prob | <code>number</code> | <p>prob to trade amount 'tradeAmnt'</p> |
| S3 | <code>number</code> | <p>collateral to quote conversion (=S2 if base-collateral, =1 if quote collateral, = index S3 if quanto)</p> |
| markProb | <code>number</code> | <p>mark prob</p> |
| imr | <code>number</code> | <p>minimum absolute margin per contract (fInitialMarginRate)</p> |
<a name="module_d8xMath..getDepositAmountForPredMktLvgTrade..newPos"></a>
#### getDepositAmountForPredMktLvgTrade~newPos
<p>Smart contract implementation:
// find smallest x such that:
// bal * s3 >= pos value / lvg
// where:
// pos value / lvg = |pos| * R(pm, sign(pos)) * margin rate
// pos = pos0 + k
// cash = cash0 + x
// ell = ell0 + px * k
// bal * s3 = cash * s3 + pos * sm - ell
// = bal0 * s3 + x * s3 + k * (sm - px)
// subject to:
// x >= 0
// cash * s3 >= |pos| * min(cmin, prob(sign(pos)))
// k * (sm - px) <= 0 a.s.
// (positive pnl does not contribute, i.e. ignore px better than mark)
// solution:
// bal0 * s3 + x * s3 >= pos value / lvg + (k * (px - sm))<em>+ = v * s3
// -->
// x >= v + (cash0 - bal0)</em>+ - cash0 = v - min(bal0, cash0)
// = pos value / lvg/ s3 + (k * (px - sm))_+ / s3 - min (bal0, cash0)
// = A + B - C
// x >= |pos| * min(cmin, prob(sign(pos))) / s3 - cash0
// x >= 0
// init x = A = pos value / lvg / s3
int128 fNewPos = _fPosition0.add(_fTradeAmount);
int128 v = (
fNewPos > 0 ? fNewPos.mul(_fMarkProb) : fNewPos.neg().mul(ONE_64x64.sub(_fMarkProb))
).mul(_fMarginRate).div(_fS3);
// + B = max(0,k * (px - sm)) / s3
{
int128 fPnL = _fTradeAmount.mul(_fMarkProb.sub(_fTradeProb));
if (fPnL < 0) {
v = v.sub(fPnL.div(_fS3)); // pnl < 0 -> increase v
}
}
// - C = - min(bal0, cash0) = - Equity
{
int128 equity = _fCash0CC < _fBalance0 ? _fCash0CC : _fBalance0;
v = v.sub(equity); // equity can be used / must be covered if negative
}
return v > 0 ? v : int128(0);</p>
**Kind**: inner constant of [<code>getDepositAmountForPredMktLvgTrade</code>](#module_d8xMath..getDepositAmountForPredMktLvgTrade)
<a name="module_d8xMath..priceToProb"></a>
### d8xMath~priceToProb(px) ⇒
<p>Convert a perpetual price to probability (predtictive markets)</p>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <p>Probability in [0,1]</p>
| Param | Description |
| --- | --- |
| px | <p>Perpetual price</p> |
<a name="module_d8xMath..probToPrice"></a>
### d8xMath~probToPrice(prob) ⇒
<p>Convert a probability to a predictive market price</p>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <p>Perpetual price</p>
| Param | Description |
| --- | --- |
| prob | <p>Probability in [0,1]</p> |
<a name="module_d8xMath..pmMarginThresh"></a>
### d8xMath~pmMarginThresh(pos, lockedInQC, s2, s3, m) ⇒
<p>Maintenance margin requirement for prediction markets</p>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <p>required margin balance</p>
| Param | Description |
| --- | --- |
| pos | <p>signed position</p> |
| lockedInQC | <p>locked in value</p> |
| s2 | <p>mark price</p> |
| s3 | <p>collateral to quote conversion</p> |
| m | <p>base margin rate</p> |
<a name="module_d8xMath..pmInitialMarginRate"></a>
### d8xMath~pmInitialMarginRate(posSign, s0, sm, cmin) ⇒ <code>number</code>
<p>Initial margin rate for prediction markets.</p>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <code>number</code> - <p>The margin rate to be applied: <code>(Math.abs(pos) * p * tau) / s3</code></p>
| Param | Description |
| --- | --- |
| posSign | <p>sign of position in base currency (can be signed position or -1, 1)</p> |
| s0 | <p>trade price</p> |
| sm | <p>mark-price (=1+p)</p> |
| cmin | <p>Absolute min margin saved as <code>fInitialMarginRate</code></p> |
<a name="module_d8xMath..pmExchangeFee"></a>
### d8xMath~pmExchangeFee(prob, m, tradeAmt, tradeMgnRate) ⇒
<p>Exchange fee as a rate for prediction markets
For opening trades only</p>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <p>dollar fee relative to tradeAmt</p>
| Param | Description |
| --- | --- |
| prob | <p>long probability</p> |
| m | <p>max maintenance margin rate (0.18)</p> |
| tradeAmt | <p>trade amount in base currency</p> |
| tradeMgnRate | <p>margin rate for this trade</p> |
<a name="module_d8xMath..pmMarginBalance"></a>
### d8xMath~pmMarginBalance(pos, s2, s3, ell, mc) ⇒
<p>Margin balance for prediction markets</p>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <p>current margin balance</p>
| Param | Description |
| --- | --- |
| pos | <p>signed position</p> |
| s2 | <p>mark price</p> |
| s3 | <p>collateral to quote conversion</p> |
| ell | <p>locked in value</p> |
| mc | <p>margin cash in collateral currency</p> |
<a name="module_d8xMath..pmFindLiquidationPrice"></a>
### d8xMath~pmFindLiquidationPrice(pos, s3, ell, mc, baseMarginRate, sm) ⇒ <code>number</code>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <code>number</code> - <p>Liquidation price as a probability in the range [0, 1]</p>
| Param | Description |
| --- | --- |
| pos | <p>Signed position size</p> |
| s3 | <p>Collateral to quote conversion at spot</p> |
| ell | <p>Locked-in value</p> |
| mc | <p>Margin collateral</p> |
| baseMarginRate | <p>Maintenance margin per contract (mu_m)</p> |
| sm | <p>Mark price at entry</p> |
<a name="module_d8xMath..excessMargin"></a>
### d8xMath~excessMargin(tradeAmt, currentCashCC, currentPos, currentLockedInQC, limitPrice, Sm, S3) ⇒
<p>Calculate the excess margin defined as
excess := margin balance - trading fee - initial margin threshold
for the given trade and position</p>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <p>excess margin as defined above</p>
| Param |
| --- |
| tradeAmt |
| currentCashCC |
| currentPos |
| currentLockedInQC |
| limitPrice |
| Sm |
| S3 |
<a name="module_d8xMath..pmGetDepositAmtForLvgTrade"></a>
### d8xMath~pmGetDepositAmtForLvgTrade(tradeAmt, targetLvg, price, S3, S2Mark) ⇒
<p>Internal function to find the deposit amount required
for a given trade amount and target leverage</p>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <p>deposit amount</p>
| Param |
| --- |
| tradeAmt |
| targetLvg |
| price |
| S3 |
| S2Mark |
<a name="module_d8xMath..pmExcessCashAtLvg"></a>
### d8xMath~pmExcessCashAtLvg(tradeAmt, lvg, walletBalCC, currentCashCC, currentPosition, currentLockedInValue, slippage, S2, Sm, S3, totLong, totShort) ⇒
<p>Internal function to calculate cash over initial margin rate
after a trade of size tradeAmt in prediction markets</p>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <p>excess cash</p>
| Param |
| --- |
| tradeAmt |
| lvg |
| walletBalCC |
| currentCashCC |
| currentPosition |
| currentLockedInValue |
| slippage |
| S2 |
| Sm |
| S3 |
| totLong |
| totShort |
<a name="module_d8xMath..pmFindMaxPersonalTradeSizeAtLeverage"></a>
### d8xMath~pmFindMaxPersonalTradeSizeAtLeverage(dir, lvg, walletBalCC, slippage, currentPosition, currentCashCC, currentLockedInValue, S2, Sm, S3, glblMaxTrade) ⇒
<p>Find maximal <em>affordable</em> trade size (short dir=-1 or long dir=1) for prediction
markets at provided leverage and incorporating the current position
and wallet balance.
Factors in lot size and global max short/long, factors in opening/closing position</p>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
**Returns**: <p>max <em>signed</em> trade size</p>
| Param | Description |
| --- | --- |
| dir | <p>direction of trade (-1 sell, 1 buy)</p> |
| lvg | <p>leverage of the trade</p> |
| walletBalCC | <p>wallet balance of the trader (collateral currency)</p> |
| slippage | <p>slippage percent used to estimate a traded price</p> |
| currentPosition | <p>position in base currency of the trader</p> |
| currentCashCC | <p>this is the cash available net of unpaid funding (often called available cash)</p> |
| currentLockedInValue | <p>average entry price * signed position size in base currency, in margin account</p> |
| S2 | <p>current index price of the form 1+p (regardless whether short or long)</p> |
| Sm | <p>current mark price (not just the mark price index but including the ema-premium from the contract)</p> |
| S3 | <p>current collateral to quote index price</p> |
| glblMaxTrade | <p>global max short or long order size that we retreive, e.g., from position risk (sign irrelevant) based on long: (<em>ℓ+n) * (1-p) - m (1-p) s = F → n = (F+m</em>(1-p)<em>s)/(1-p)-ℓ</em> short: (s+n)<em>p - m p <em>ℓ</em> = F →n = (F+m</em>p**ℓ*)/p-s</p> |
<a name="module_d8xMath..pmMaxSignedOpenTradeSize"></a>
### d8xMath~pmMaxSignedOpenTradeSize(long, short, sm, isBuy, mr)
<p>See PerpetualTradeLogic::_getMaxSignedOpenPredMktTradeSize</p>
**Kind**: inner method of [<code>d8xMath</code>](#module_d8xMath)
| Param | Description |
| --- | --- |
| long | <p>Long open OI</p> |
| short | <p>Short open OI</p> |
| sm | <p>Mark price (>1)</p> |
| isBuy | <p>True if trade is long</p> |
| mr | <p>Margin threshold per contract for liquidation (mu_m)</p> |
<a name="module_utils"></a>
## utils
* [utils](#module_utils)
* [~to4Chars(s)](#module_utils..to4Chars) ⇒ <code>string</code>
* [~toBytes4(s)](#module_utils..toBytes4) ⇒ <code>Buffer</code>
* [~fromBytes4(b)](#module_utils..fromBytes4) ⇒ <code>string</code>
* [~fromBytes4HexString(s)](#module_utils..fromBytes4HexString) ⇒ <code>string</code>
* [~contractSymbolToSymbol(s, mapping)](#module_utils..contractSymbolToSymbol) ⇒ <code>string</code>
* [~symbolToContractSymbol(s, mapping)](#module_utils..symbolToContractSymbol) ⇒ <code>Buffer</code>
* [~symbol4BToLongSymbol(s, mapping)](#module_utils..symbol4BToLongSymbol) ⇒ <code>string</code>
<a name="module_utils..to4Chars"></a>
### utils~to4Chars(s) ⇒ <code>string</code>
**Kind**: inner method of [<code>utils</code>](#module_utils)
**Returns**: <code>string</code> - <p>String with 4 characters (or characters + null chars)</p>
| Param | Type | Description |
| --- | --- | --- |
| s | <code>string</code> | <p>String to shorten/extend to 4 characters</p> |
<a name="module_utils..toBytes4"></a>
### utils~toBytes4(s) ⇒ <code>Buffer</code>
<p>Converts string into 4-character bytes4
uses to4Chars to first convert the string into
4 characters.
Resulting buffer can be used with smart contract to
identify tokens (BTC, USDC, MATIC etc.)</p>
**Kind**: inner method of [<code>utils</code>](#module_utils)
**Returns**: <code>Buffer</code> - <p>4-character bytes4.</p>
| Param | Type | Description |
| --- | --- | --- |
| s | <code>string</code> | <p>String to encode into bytes4</p> |
<a name="module_utils..fromBytes4"></a>
### utils~fromBytes4(b) ⇒ <code>string</code>
<p>Decodes a buffer encoded with toBytes4 into
a string. The string is the result of to4Chars of the
originally encoded string stripped from null-chars</p>
**Kind**: inner method of [<code>utils</code>](#module_utils)
**Returns**: <code>string</code> - <p>String decoded into to4Chars-type string without null characters</p>
| Param | Type | Description |
| --- | --- | --- |
| b | <code>Buffer</code> | <p>Correctly encoded bytes4 buffer using toBytes4</p> |
<a name="module_utils..fromBytes4HexString"></a>
### utils~fromBytes4HexString(s) ⇒ <code>string</code>
<p>Decodes the bytes4 encoded string received from the
smart contract as a hex-number in string-format</p>
**Kind**: inner method of [<code>utils</code>](#module_utils)
**Returns**: <code>string</code> - <p>x of to4Chars(x) stripped from null-chars,
where x was originally encoded and
returned by the smart contract as bytes4</p>
| Param | Type | Description |
| --- | --- | --- |
| s | <code>string</code> | <p>string representing a hex-number ("0x...")</p> |
<a name="module_utils..contractSymbolToSymbol"></a>
### utils~contractSymbolToSymbol(s, mapping) ⇒ <code>string</code>
**Kind**: inner method of [<code>utils</code>](#module_utils)
**Returns**: <code>string</code> - <p>User friendly currency symbol, e.g. "MATIC"</p>
| Param | Type | Description |
| --- | --- | --- |
| s | <code>string</code> | <p>String representing a hex-number ("0x...")</p> |
| mapping | <code>Object</code> | <p>List of symbol and clean symbol pairs, e.g. [{symbol: "MATIC", cleanSymbol: "MATC"}, ...]</p> |
<a name="module_utils..symbolToContractSymbol"></a>
### utils~symbolToContractSymbol(s, mapping) ⇒ <code>Buffer</code>
**Kind**: inner method of [<code>utils</code>](#module_utils)
**Returns**: <code>Buffer</code> - <p>Buffer that can be used with smart contract to identify tokens</p>
| Param | Type | Description |
| --- | --- | --- |
| s | <code>string</code> | <p>User friendly currency symbol, e.g. "MATIC"</p> |
| mapping | <code>Object</code> | <p>List of symbol and clean symbol pairs, e.g. [{symbol: "MATIC", cleanSymbol: "MATC"}, ...]</p> |
<a name="module_utils..symbol4BToLongSymbol"></a>
### utils~symbol4BToLongSymbol(s, mapping) ⇒ <code>string</code>
<p>Converts symbol or symbol combination into long format</p>
**Kind**: inner method of [<code>utils</code>](#module_utils)
**Returns**: <code>string</code> - <p>long format e.g. MATIC. if not found the element is ""</p>
| Param | Type | Description |
| --- | --- | --- |
| s | <code>string</code> | <p>symbol, e.g., USDC-MATC-USDC, MATC, USDC, ...</p> |
| mapping | <code>Object</code> | <p>list of symbol and clean symbol pairs, e.g. [{symbol: "MATIC", cleanSymbol: "MATC"}, ...]</p> |
<a name="AccountTrade"></a>
## AccountTrade ⇐ [<code>WriteAccessHandler</code>](#WriteAccessHandler)
<p>Functions to create, submit and cancel orders on the exchange.
This class requires a private key and executes smart-contract interactions that
require gas-payments.</p>
**Kind**: global class
**Extends**: [<code>WriteAccessHandler</code>](#WriteAccessHandler)
* [AccountTrade](#AccountTrade) ⇐ [<code>WriteAccessHandler</code>](#WriteAccessHandler)
* [new AccountTrade(config, signer)](#new_AccountTrade_new)
* [.cancelOrder(symbol, orderId)](#AccountTrade+cancelOrder) ⇒ <code>ContractTransaction</code>
* [.order(order)](#AccountTrade+order) ⇒ <code>ContractTransaction</code>
* [.queryExchangeFee(poolSymbolName, [brokerAddr])](#AccountTrade+queryExchangeFee) ⇒
* [.getCurrentTraderVolume(poolSymbolName)](#AccountTrade+getCurrentTraderVolume) ⇒ <code>number</code>
* [.getOrderIds(symbol)](#AccountTrade+getOrderIds) ⇒ <code>Array.<string></code>
* [.addCollateral(symbol, amount)](#AccountTrade+addCollateral)
* [.removeCollateral(symbol, amount)](#AccountTrade+removeCollateral)
* [.createProxyInstance(provider)](#WriteAccessHandler+createProxyInstance)
* [.setAllowance(symbol, amount)](#WriteAccessHandler+setAllowance) ⇒
* [.getAddress()](#WriteAccessHandler+getAddress) ⇒ <code>string</code>
* [.swapForMockToken(symbol, amountToPay)](#WriteAccessHandler+swapForMockToken) ⇒
* [.fetchSymbolList()](#PerpetualDataHandler+fetchSymbolList)
* [.getOrderBookContract(symbol)](#PerpetualDataHandler+getOrderBookContract) ⇒
* [.getOrderBookAddress(symbol)](#PerpetualDataHandler+getOrderBookAddress) ⇒
* [.getPerpetuals(ids, overrides)](#PerpetualDataHandler+getPerpetuals) ⇒
* [.getLiquidityPools(fromIdx, toIdx, overrides)](#PerpetualDataHandler+getLiquidityPools) ⇒
* [._fillSymbolMaps()](#PerpetualDataHandler+_fillSymbolMaps)
* [.initSettlementToken(perpStaticInfos)](#PerpetualDataHandler+initSettlementToken)
* [.getSymbolFromPoolId(poolId)](#PerpetualDataHandler+getSymbolFromPoolId) ⇒ <code>symbol</code>
* [.getPoolIdFromSymbol(symbol)](#PerpetualDataHandler+getPoolIdFromSymbol) ⇒ <code>number</code>
* [.getPerpIdFromSymbol(symbol)](#PerpetualDataHandler+getPerpIdFromSymbol) ⇒ <code>number</code>
* [.getSymbolFromPerpId(perpId)](#PerpetualDataHandler+getSymbolFromPerpId) ⇒ <code>string</code>
* [.symbol4BToLongSymbol(sym)](#PerpetualDataHandler+symbol4BToLongSymbol) ⇒ <code>string</code>
* [.fetchPriceSubmissionInfoForPerpetual(symbol)](#PerpetualDataHandler+fetchPriceSubmissionInfoForPerpetual) ⇒
* [.getIndexSymbols(symbol)](#PerpetualDataHandler+getIndexSymbols) ⇒
* [.fetchLatestFeedPriceInfo(symbol)](#PerpetualDataHandler+fetchLatestFeedPriceInfo) ⇒
* [.fetchCollateralToSettlementConversion(symbol)](#PerpetualDataHandler+fetchCollateralToSettlementConversion)
* [.getPriceIds(symbol)](#PerpetualDataHandler+getPriceIds) ⇒
* [.getPerpetualSymbolsInPool(poolSymbol)](#PerpetualDataHandler+getPerpetualSymbolsInPool) ⇒
* [.getAllOpenOrders(symbol)](#PerpetualDataHandler+getAllOpenOrders) ⇒
* [.numberOfOpenOrders(symbol)](#PerpetualDataHandler+numberOfOpenOrders) ⇒ <code>number</code>
* [.pollLimitOrders(symbol, numElements, [startAfter])](#PerpetualDataHandler+pollLimitOrders) ⇒
* [.getPoolStaticInfoIndexFromSymbol(symbol)](#PerpetualDataHandler+getPoolStaticInfoIndexFromSymbol) ⇒
* [.getMarginTokenFromSymbol(symbol)](#PerpetualDataHandler+getMarginTokenFromSymbol) ⇒
* [.getSettlementTokenFromSymbol(symbol)](#PerpetualDataHandler+getSettlementTokenFromSymbol) ⇒
* [.getMarginTokenDecimalsFromSymbol(symbol)](#PerpetualDataHandler+getMarginTokenDecimalsFromSymbol) ⇒
* [.getSettlementTokenDecimalsFromSymbol(symbol)](#PerpetualDataHandler+getSettlementTokenDecimalsFromSymbol) ⇒
* [.getABI(contract)](#PerpetualDataHandler+getABI) ⇒
* [.isPredictionMarket(symbol)](#PerpetualDataHandler+isPredictionMarket) ⇒
* [.isLowLiquidityMarket(symbol)](#PerpetualDataHandler+isLowLiquidityMarket) ⇒
* [.isTradFiMarket(symbol)](#PerpetualDataHandler+isTradFiMarket) ⇒
* [.getMarketDayTradingOpenCloseSec(symbol)](#PerpetualDataHandler+getMarketDayTradingOpenCloseSec) ⇒
* [.getInitialMarginRate(symbol)](#PerpetualDataHandler+getInitialMarginRate) ⇒
* [.getMaintenanceMarginRate(symbol)](#PerpetualDataHandler+getMaintenanceMarginRate) ⇒
* [.getShortSymbol(symbol)](#PerpetualDataHandler+getShortSymbol) ⇒
* [.refreshSymbols()](#PerpetualDataHandler+refreshSymbols)
* [.getLocalPerpetualStates()](#PerpetualDataHandler+getLocalPerpetualStates) ⇒
* [.fetchOnChainPerpetualStates()](#PerpetualDataHandler+fetchOnChainPerpetualStates) ⇒
* [.checkHeartbeat()](#PerpetualDataHandler+checkHeartbeat) ⇒
<a name="new_AccountTrade_new"></a>
### new AccountTrade(config, signer)
<p>Constructor</p>
| Param | Type | Description |
| --- | --- | --- |
| config | <code>NodeSDKConfig</code> | <p>Configuration object, see PerpetualDataHandler. readSDKConfig.</p> |
| signer | <code>string</code> \| <code>Signer</code> | <p>Private key or ethers Signer of the account</p> |
**Example**
```js
import { AccountTrade, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
async function main() {
console.log(AccountTrade);
// load configuration for Polygon zkEVM Tesnet
const config = PerpetualDataHandler.readSDKConfig("cardona");
// AccountTrade (authentication required, PK is an environment variable with a private key)
const pk: string = <string>process.env.PK;
let accTrade = new AccountTrade(config, pk);
// Create a proxy instance to access the blockchain
await accTrade.createProxyInstance();
}
main();
```
<a name="AccountTrade+cancelOrder"></a>
### accountTrade.cancelOrder(symbol, orderId) ⇒ <code>ContractTransaction</code>
<p>Cancels an existing order on the exchange.</p>
**Kind**: instance method of [<code>AccountTrade</code>](#AccountTrade)
**Returns**: <code>ContractTransaction</code> - <p>Contract Transaction (containing events).</p>
| Param | Type | Description |
| --- | --- | --- |
| symbol | <code>string</code> | <p>Symbol of the form ETH-USD-MATIC.</p> |
| orderId | <code>string</code> | <p>ID of the order to be cancelled.</p> |
**Example**
```js
import { AccountTrade, PerpetualDataHandler, Order } from '@d8x/perpetuals-sdk';
async function main() {
console.log(AccountTrade);
// setup (authentication required, PK is an environment variable with a private key)
const config = PerpetualDataHandler.readSDKConfig("cardona");
const pk: string = <string>process.env.PK;
let accTrade = new AccountTrade(config, pk);
await accTrade.createProxyInstance();
// cancel order
let cancelTransaction = accTrade.cancelOrder("MATIC-USD-MATIC",
"0x4639061a58dcf34f4c9c703f49f1cb00d6a4fba490d62c0eb4a4fb06e1c76c19")
console.log(cancelTransaction);
}
main();
```
<a name="AccountTrade+order"></a>
### accountTrade.order(order) ⇒ <code>ContractTransaction</code>
<p>Submits an order to the exchange.</p>
**Kind**: instance method of [<code>AccountTrade</code>](#AccountTrade)
**Returns**: <code>ContractTransaction</code> - <p>Contract Transaction (containing events).</p>
| Param | Type | Description |
| --- | --- | --- |
| order | <code>Order</code> | <p>Order structure. As a minimum the structure needs to specify symbol, side, type and quantity.</p> |
**Example**
```js
import { AccountTrade, PerpetualDataHandler, Order } from '@d8x/perpetuals-sdk';
async function main() {
console.log(AccountTrade);
// setup (authentication required, PK is an environment variable with a private key)
const config = PerpetualDataHandler.readSDKConfig("cardona");
const pk: string = <string>process.env.PK;
const accTrade = new AccountTrade(config, pk);
await accTrade.createProxyInstance();
// set allowance
await accTrade.setAllowance("MATIC");
// set an order
const order: Order = {
symbol: "MATIC-USD-MATIC",
side: "BUY",
type: "MARKET",
quantity: 100,
leverage: 2,
executionTimestamp: Date.now()/1000,
};
const orderTransaction = await accTrade.order(order);
console.log(orderTransaction);
}
main();
```
<a name="AccountTrade+queryExchangeFee"></a>
### accountTrade.queryExchangeFee(poolSymbolName, [brokerAddr]) ⇒
<p>Fee charged by the exchange for trading any perpetual on a given pool.
It accounts for the current trader's fee tier (based on the trader's D8X balance and trading volume).
If trading with a broker, it also accounts for the selected broker's fee tier.
Note that this result only includes exchange fees, additional broker fees are not included.</p>
**Kind**: instance method of [<code>AccountTrade</code>](#AccountTrade)
**Returns**: <p>Exchange fee, in decimals (i.e. 0.1% is 0.001).</p>
| Param | Type | Description |
| --- | --- | --- |
| poolSymbolName | <code>string</code> | <p>Pool symbol name (e.g. MATIC, USDC, etc).</p> |
| [brokerAddr] | <code>string</code> | <p>Optional address of a broker this trader may use to trade under.</p> |
**Example**
```js
import { AccountTrade, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
async function main() {
console.log(AccountTrade);
// setup (authentication required, PK is an environment variable with a private key)
const config = PerpetualDataHandler.readSDKConfig("cardona");
const pk: string = <string>process.env.PK;
let accTrade = new AccountTrade(config, pk);
await accTrade.createProxyInstance();
// query exchange fee
let fees = await accTrade.queryExchangeFee("MATIC");
console.log(fees);
}
main();
```
<a name="AccountTrade+getCurrentTraderVolume"></a>
### accountTrade.getCurrentTraderVolume(poolSymbolName) ⇒ <code>number</code>
<p>Exponentially weighted EMA of the total USD trading volume of all trades performed by this trader.
The weights are chosen so that in average this coincides with the 30 day volume.</p>
**Kind**: instance method of [<code>AccountTrade</code>](#AccountTrade)
**Returns**: <code>number</code> - <p>Current trading volume for this trader, in USD.</p>
| Param | Type | Description |
| --- | --- | --- |
| poolSymbolName | <code>string</code> | <p>Pool symbol name (e.g. MATIC, USDC, etc).</p> |
**Example**
```js
import { AccountTrade, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
async function main() {
console.log(AccountTrade);
// setup (authentication required, PK is an environment variable with a private key)
const config = PerpetualDataHandler.readSDKConfig("cardona");
const pk: string = <string>process.env.PK;
let accTrade = new AccountTrade(config, pk);
await accTrade.createProxyInstance();
// query 30 day volume
let vol = await accTrade.getCurrentTraderVolume("MATIC");
console.log(vol);
}
main();
```
<a name="AccountTrade+getOrderIds"></a>
### accountTrade.getOrderIds(symbol) ⇒ <code>Array.<string></code>
**Kind**: instance method of [<code>AccountTrade</code>](#AccountTrade)
**Returns**: <code>Array.<string></code> - <p>Array of Ids for all the orders currently open by this trader.</p>
| Param | Description |
| --- | --- |
| symbol | <p>Symbol of the form ETH-USD-MATIC.</p> |
**Example**
```js
import { AccountTrade, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
async function main() {
console.log(AccountTrade);
// setup (authentication required, PK is an environment variable with a private key)
const config = PerpetualDataHandler.readSDKConfig("cardona");
const pk: string = <string>process.env.PK;
let accTrade = new AccountTrade(config, pk);
await accTrade.createProxyInstance();
// get order IDs
let orderIds = await accTrade.getOrderIds("MATIC-USD-MATIC");
console.log(orderIds);
}
main();
```
<a name="AccountTrade+addCollateral"></a>
### accountTrade.addCollateral(symbol, amount)
**Kind**: instance method of [<code>AccountTrade</code>](#AccountTrade)
| Param | Type | Description |
| --- | --- | --- |
| symbol | <code>string</code> | <p>Symbol of the form ETH-USD-MATIC.</p> |
| amount | <code>number</code> | <p>How much collateral to add, in units of collateral currency, e.g. MATIC</p> |
**Example**
```js
import { AccountTrade, Perpe