Get PrepPositions for an User Account

Fetch PrepPosition details for an userAccount of a particular Authority

A perpetual position in a perpetual market refers to a trader's open position in a perpetual futures contract. This position can be either long (betting that the price of the underlying asset will increase) or short (betting that the price will decrease). We can query PerpPositions data for a particular marketIndex via SuperIndexer using the following steps:

  • We query the user account details for an authority (user wallet)

  • The user account details will contain perpPositions for the user. We need to filter positions where either the baseAssetAmount or quoteAssetAmount or the lpShares is not equal to zero(these are all perpPosition fields). Also, the openOrders field should not equal to zero.

  • Once done, finally we filter the final list of positions while matching marketIndex field.

You can directly copy paste this code on replit and see it in action.

Fetch perpPosition for a User Account by authority and market index

const BN = require("bn.js");
const SHYFT_API_KEY = "YOUR-API-KEY";
const ZERO = new BN(0);

async function getperpPositionDataByGraphQl(authorityAddress) {
  const operationsDoc = `
        query MyQuery {
            drift_User(
                where: {authority: {_eq: ${JSON.stringify(authorityAddress)}}}
            ) {
                perpPositions
                authority
            }
        }
      `; //graphQl query
  const result = await fetch(
    `https://programs.shyft.to/v0/graphql/accounts?api_key=${SHYFT_API_KEY}&network=mainnet-beta`, //SHYFT's GQL endpoint
    {
      method: "POST",
      body: JSON.stringify({
        query: operationsDoc,
        variables: {},
        operationName: "MyQuery",
      }),
    }
  );

  return await result.json();
}

async function main(authorityPubkey, marketIndex) {
  const { errors, data } = await getperpPositionDataByGraphQl(authorityPubkey);
  if (errors) {
    console.error(errors);
    console.log("Some Error Occured, please check your API key or try again");
  }
  let allMatchedMarkets = [];
  for (let index = 0; index < data.drift_User.length; index++) {
    const currentPerpPosition = data.drift_User[index];

    const matchedMarkets = currentPerpPosition.perpPositions.filter(
      (perpPosition) =>
        !new BN(perpPosition.baseAssetAmount).eq(ZERO) ||
        !new BN(perpPosition.quoteAssetAmount).eq(ZERO) ||
        !(perpPosition.openOrders == 0) ||
        !new BN(perpPosition.lpShares).eq(ZERO)
    );
    if (matchedMarkets) {
      matchedMarkets.forEach((mMar) => {
        allMatchedMarkets.push(mMar);
      });
    }
  }
  if(!allMatchedMarkets.length){
    console.log("No perpPostions found");
    return
  }
  console.log("PerpPositions found: ");
  console.dir(allMatchedMarkets.find(m => m.marketIndex == marketIndex),{depth: null});
  
}
main("BgGAVukE1j8JDsvXwcnneuoN8LTpDuiRUtYfQWociQjL", 2);

Last updated