Get OpenOrders for a User Account

Fetch openOrder details for an user Authority

Open orders are pending buy or sell orders that a trader has placed on the platform's perpetual futures market but haven't been filled. We can get openOrders for a particular user Account, by querying the orders field, and checking orders with status "open".

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

Fetch openOrders associated to a user account

const SHYFT_API_KEY = "YOUR-API-KEY";

async function getOpenOrdersByGraphQl(authorityAddress) {
    const operationsDoc = `
          query MyQuery {
            drift_User(
                where: {authority: {_eq: ${JSON.stringify(authorityAddress)}}}
            ) {
                authority
                orders
                hasOpenOrder
                pubkey
            }
          }
        `; //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) {
    const { errors, data } = await getOpenOrdersByGraphQl(authorityPubkey);
    if (errors) {
      console.error(errors);
      console.log("Some Error Occured, please check your API key or try again");
    }
    
    let allOpenOrder = [];
    for (let index = 0; index < data.drift_User.length; index++) {
        const currentUserDetails = data.drift_User[index];
        
        const openOrder = currentUserDetails.orders.find(
            (order) => Object.keys(order.status)[0] == 'open'
        );
        
        if (!openOrder) {
            // console.log("Order not found");
            continue;
        }
        allOpenOrder.push(openOrder);
    }
    console.log("Open Orders found: ");
    console.dir(allOpenOrder, { depth: null });
}
main("BgGAVukE1j8JDsvXwcnneuoN8LTpDuiRUtYfQWociQjL")

Last updated