# Setup

## 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` .

```python
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. &#x20;

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` . &#x20;

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

```python
# ... 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:<br>

```python
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.&#x20;
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 `TxParams`object 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`.&#x20;
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`&#x20;
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()` .


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://drift-2.gitbook.io/driftpy-for-dummies/setup.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
