Setup

This page discusses how to set up DriftPy to work with your Drift account. The steps in this page are necessary before taking any other actions to interact with the Drift Protocol.

Creating a Drift Client

The first step to using DriftPy is setting up the Drift Client. The Drift Client serves as an entrypoint to the Drift Protocol, and can be used for many different functions, such as placing orders, settling PnL, and creating user accounts.

The Drift Client has multiple different types of Subscriptions. Subscriptions are the method by which you intend to receive data from the blockchain for use in your program. For example, if you want to receive data via WebSocket, you would specify AccountSubscriptionConfig("websocket") in your Drift Client constructor. The default configuration is websocket.

Here's an full example of how to create a Drift Client with a .env file holding your PRIVATE_KEY and your RPC_URL. Note: this example requires the python-dotenv library, which can be installed with pip install and poetry add .

import os
import asyncio

from dotenv import load_dotenv

from solders.keypair import Keypair

from solana.rpc.async_api import AsyncClient

from anchorpy import Wallet

from driftpy.drift_client import DriftClient
from driftpy.keypair import load_keypair

async def main():
    load_dotenv()
    secret = os.getenv("PRIVATE_KEY") # as a [u64]
    url = os.getenv("RPC_URL") # as a string
    
    keypair = load_keypair(secret)
    wallet = Wallet(kp)
    
    connection = AsyncClient(url)
    
    drift_client = DriftClient(
        connection,
        wallet,
        "mainnet", # or "devnet"
    )
    
    await drift_client.add_user(0)
    
    await drift_client.subscribe()

Note the await drift_client.subscribe() call on the last line of this excerpt. A common pitfall is for users to fail to subscribe to the Drift Client prior to requesting data, which will always cause an error. If you are seeing errors that look something like this: return self.cache["spot_markets"][market_index] IndexError: list index out of range You probably have not subscribed to the Drift Client yet.

Also note the await drift_client.add_user(0) call preceding the subscription. This says, "Register sub-account 0 (the default sub-account) as a usuable Drift User account for this instance of the Drift Client". This function call is necessary for loading the corresponding DriftUser object and its data. We'll go over the DriftUser more later, but for now, assume that that line should always be there.

Creating a Drift Account with DriftPy

That add_user(0) function call in the prior code block assumes that a Drift account has already been created for the Keypair with which you created your DriftClient, either through the UI, the TypeScript SDK, or previously through DriftPy. However, if that is not the case, you'll have to go through the steps of creating a Drift account for that Keypair .

Here's how you can do that in DriftPy. Note: This code does not require subscription to the Drift Client.

# ... assume DriftClient object is created, similar to prior step

try:
    tx_sig = await drift_client.initialize_user()
    print(f"Successfully initialized Drift User: {tx_sig}")
except Exception as e:
    print(f"Failed to initialize Drift User: {e}")

Once you've set up your Drift account, registered it with the Drift Client, and subscribed to the Drift Client, you're ready to start interacting with the Drift Protocol.

Drift Client Optional Parameters

There are several optional parameters for the Drift Client. Here's the whole constructor:

class DriftClient:
    def __init__(
        self,
        connection: AsyncClient,
        wallet: Union[Keypair, Wallet],
        env: DriftEnv = "mainnet",
        opts: TxOpts = DEFAULT_TX_OPTIONS,
        authority: Pubkey = None,
        account_subscription: Optional[
            AccountSubscriptionConfig
        ] = AccountSubscriptionConfig.default(),
        perp_market_indexes: list[int] = None,
        spot_market_indexes: list[int] = None,
        oracle_infos: list[OracleInfo] = None,
        tx_params: Optional[TxParams] = None,
        tx_version: Optional[TransactionVersion] = None,
        tx_sender: TxSender = None,
        active_sub_account_id: Optional[int] = None,
        sub_account_ids: Optional[list[int]] = None,
    )

For most use cases, you should be able to use the example code provided above for setting up your Drift Client. However, there may be times when you need some sort of customization. Here's what those optional parameters mean (starting at opts):

  1. opts - A TxOpts object used to specify some parameters for sending transactions from the Drift Client. Defaults to DEFAULT_TX_OPTIONS . This does not include priority fee parameters.

  2. authority - If you are trading under a delegate, this Pubkey corresponds to the actual authority of the Drift account. (i.e. the vault pubkey if you're trading as a vault delegate)

  3. account_subscription - The AccountSubscriptionConfig you intend to use to receive data from Drift. Defaults to AccountSubscriptionConfig.default() which is "websocket" .

  4. perp_market_indexes - A list of int s representing the perp markets you intend to subscribe to. Only provide this if you intend to listen to a subset of perp markets and not all perp markets.

  5. spot_market_indexes -A list of int s representing the spot markets you intend to subscribe to. Only provide this if you intend to listen to a subset of spot markets and not all spot markets. If you provide any perp_market_indexes , you must provide [0] here, as that is the quote (USDC) spot market index for all pairs on Drift.

  6. oracle_infos - A list of OracleInfos corresponding to the perp_market_indexes and spot_market_indexes provided. Do not provide this if you did not specify perp_market_indexes or spot_market_indexes .

  7. tx_params - A TxParamsobject used to specify priority fee values for sending transactions. Includes compute_units and compute_units_price.

  8. tx_version - Either Legacy or an int specifying the type of transaction you intend to send from the Drift Client.

  9. tx_sender - A StandardTxSender or FastTxSender object representing how you'd like to send transactions from the Drift Client. Defaults to StandardTxSender.

  10. active_sub_account_id - An int representing the sub_account_id that you intend to begin using the Drift Client under

  11. sub_account_ids - A list of int s representing all sub_account_id s that you intend to use under the DriftClient

  12. market_lookup_table - A Pubkey corresponding to a custom address lookup table, if you intend to use one. If you do not know what that means, you should not provide any value to this argument.

Note: the sub_account_id arguments do not need to be provided to use the Drift Client. You can follow the steps to adding a user described in the code examples above, but adding sub_account_id s will force the Drift Client to add those users on DriftClient.subscribe() .

Last updated