This guide shows how to re-margin with specific leverage (EX: 3). In order to set target leverage, calculate current leverage first, then execute deposit or withdraw function
Can reference Get Account to know how to get account object & Get Perpetual Info to know how to get perpetual object


  1. 1.
    deposit: can reference Adding Margin to know more.
  2. 2.
    withdraw: can reference Removing Margin to know more.


Calculate the current leverage first.
const markPrice = perpetual.markPrice
const keeperGasReward = perpetual.keeperGasReward
const position = fromWei(account.accountStorage.position)
const margin = fromWei(account.accountStorage.margin)
const oi = markPrice * Math.abs(Number(position))
const leverage = oi / (Number(margin) - keeperGasReward)
console.log("now leverage: " + leverage)
In order to set leverage to 3, execute the difference amount, then calling deposit or withdraw.
const targetMargin = oi / 3 + keeperGasReward
console.log("targetMargin: " + targetMargin)
if (targetMargin > Number(margin)) {
const amount = targetMargin - Number(margin)
console.log("deposit amount: " + amount)
await liquidityPool.deposit(0, trader.address, toWei(amount.toString()))
} else if (targetMargin < Number(margin)) {
const amount = Number(margin) - targetMargin
console.log("withdraw amount: " + amount)
await liquidityPool.withdraw(0, trader.address, toWei(amount.toString()))

Sample Code

Last modified 10mo ago
Copy link
On this page
Sample Code