### Build and Serve Drift v2 Docs Locally Source: https://github.com/drift-labs/v2-teacher/blob/main/README.md Installs project dependencies using Bundler and then starts a local development server to view the Drift v2 API documentation. The `bundle exec middleman server` command is the standard way to run Middleman applications. ```shell bundle install ``` ```shell bundle exec middleman server ``` ```shell ./start.sh ``` -------------------------------- ### Drift Vaults CLI: Clone and Install Dependencies Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md This snippet demonstrates how to clone the Drift Vaults repository from GitHub and install the necessary dependencies using Yarn. It then shows how to access the CLI help information. This is the initial setup step for using the Drift Vaults command-line interface. ```bash git clone git@github.com:drift-labs/drift-vaults.git cd ts/sdk yarn yarn cli --help ``` -------------------------------- ### Install Nokogiri Dependencies Source: https://github.com/drift-labs/v2-teacher/blob/main/README.md Installs the necessary system libraries (libxml2 and libxslt) required for the Nokogiri gem, which is often used for parsing HTML and XML in Ruby projects. ```shell brew install libxml2 libxslt ``` -------------------------------- ### Install Bundler Source: https://github.com/drift-labs/v2-teacher/blob/main/README.md Installs the Bundler gem, a dependency manager for Ruby projects. This command sets the GEM_HOME environment variable to ensure gems are installed in the user's home directory. ```shell export GEM_HOME="$HOME/.gem" gem install bundler ``` -------------------------------- ### Install Ruby and Update Gems (macOS) Source: https://github.com/drift-labs/v2-teacher/blob/main/README.md Installs the latest Ruby version using Homebrew and updates the Ruby system gems. Ensures the system's PATH is configured correctly to avoid using the default system Ruby. ```shell brew update brew install ruby ``` ```shell gem update --system ``` -------------------------------- ### Listening to Perp Market Fills (Python) Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md Example of how to listen for perp market fill events using the Python SDK. ```APIDOC ## Listening to Perp Market Fills (Python) This example demonstrates how to filter and react to specific 'Fill' events on perp markets using the Python SDK. ### Request Example ```python from drift_sdk.types import WrappedEvent market_index = 0 def fill_callback(event: WrappedEvent): if event.event_type != "OrderActionRecord": return if event.data.market_index != market_index: return if not is_variant(event.data.market_type, "Perp"): return if not is_variant(event.data.action, "Fill"): return print(event) # Assuming event_subscriber is an instance of EventSubscriber event_subscriber.event_emitter.new_event += fill_callback ``` ``` -------------------------------- ### Builder Initialization and Order Placement Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md Guides for initializing builder clients, setting up user revenue share accounts, and approving builders. Includes details on placing orders with builder codes. ```APIDOC ## Builder Codes ### Builder Initialization Initialize the builder client to manage revenue share. ```ts await builderClient.initializeRevenueShare(builderAuthority) ``` ### User Initialization #### RevenueShareEscrow Account Initialize a RevenueShareEscrow account for the user before they can pay builder fees. ```ts await userClient.initializeRevenueShareEscrow(takerAuthority, numOrders) ``` - **takerAuthority** (string) - The public key of the taker. - **numOrders** (number) - The recommended number of orders to hold for the taker. #### Builder Approval Approve a builder with their maximum payable fee. ```ts // 200 = 20 bps max fee await userClient.changeApprovedBuilder(builderAuthority, 200, true) ``` - **builderAuthority** (string) - The public key of the builder. - **maxFeeTenthBps** (number) - The maximum fee in tenth of a basis point (e.g., 100 = 10 bps). - **approve** (boolean) - Whether to approve the builder. ### Order Placement with Builder Codes Construct a place_order transaction that includes `builderIdx` and `builderFeeTenthBps` in the signed message. ```typescript const orderMessage: SignedMsgOrderParamsMessage = { signedMsgOrderParams: marketOrderParams as OrderParams, subAccountId: takerClient.activeSubAccountId, slot: new BN(slot + 100), uuid: generateSignedMsgUuid(), stopLossOrderParams: null, takeProfitOrderParams: null, /// The builder's UI must include these 2 fields /// in order to append a builder fee. builderIdx: 0, // the builder is idx 0 on the taker's RevenueShareEscrow.approved_builders list builderFeeTenthBps: 50, // builder fee on this order: 5 bps }; ``` Builder codes are enabled by Swift by setting `builderIdx` and `builderFee` in the signed message. The builder's app constructs this transaction and sends it to the Swift server. ``` -------------------------------- ### DriftClient Initialization Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md Provides instructions and code examples for initializing the DriftClient, which is used to interact with the Drift protocol. Covers initialization parameters for both TypeScript and Python. ```APIDOC ## Client Initialization ### Description Initializes the `DriftClient` for interacting with the Drift protocol. This client requires a connection object, a wallet for signing transactions, and environment configuration. It can be initialized with a dummy wallet for read-only operations. ### Code Examples #### TypeScript ```typescript import {Connection} from "@solana/web3.js"; import {Wallet, loadKeypair, DriftClient} from "@drift-labs/sdk"; const connection = new Connection('https://api.mainnet-beta.solana.com', 'confirmed'); const keyPairFile = `${process.env.HOME}/.config/solana/my-keypair.json`; const wallet = new Wallet(loadKeypair(keyPairFile)) const driftClient = new DriftClient({ connection, wallet, env: 'mainnet-beta', }); await driftClient.subscribe(); ``` #### Python ```python from anchorpy import Wallet from driftpy.drift_client import DriftClient from solana.rpc.async_api import AsyncClient # set connection and wallet # ... drift_client = DriftClient(connection, wallet, "mainnet") await drift_client.add_user(0) # Assuming a Drift account has already been created await drift_client.subscribe() ``` ### TypeScript Initialization Parameters | Parameter | Description | Optional | Default | | ----------- | ----------- | -------- | ------- | | connection | Connection object specifying solana rpc url | No | | | wallet | The wallet used to sign transactions sent to solana blockchain | No | | | programId | Drift program id | Yes | dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH | | env | `devnet` or `mainnet-beta`. Used to automatically derive market accounts to subscribe to if they're not explicitly set | Yes | | | perpMarketIndexes | Which perp markets accounts to subscribe to. | Yes | Derived based on env| | spotMarketIndexes | Which spot markets accounts to subscribe to. | Yes | Derived based on env| | oracleInfos | Which oracles accounts to subscribe to. | Yes | Derived based on env| | accountSubscription | Whether to use websocket or polling to subscribe to on-chain accounts e.g. markets, users, oracle.| Yes | Websockets | | opts | Transaction confirmation status options | Yes | {preflightCommitment: "processed", commitment: "processed"} | | activeSubAccountId | Which sub account to use initially | Yes | 0 | | subAccountIds | All the sub account ids to subscribe to. If this and authoritySubAccountMap are empty, subscribes to all sub account ids. | Yes | [] | | authority | Which user account authority you're signing for. Only set if you're signing for delegated account. | Yes | wallet.publicKey | | authoritySubAccountMap | Map of authority to sub account ids to subscribe to. Only necessary if using multiple delegate accounts. If this and subAccountIds are empty, subscribes to all sub account ids. | Yes | {} | | includeDelegates | Whether or not to subscribe to delegates when subAccountIds and authoritySubAccountMap are empty | Yes | false | | userStats | Whether or not to listen subscribe to user stats account. | Yes | false | ``` -------------------------------- ### Place Spot Order (TypeScript) Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md Provides a TypeScript example for placing a limit spot order. It demonstrates setting the market index, direction, base asset amount, and price, utilizing precision conversion functions. ```typescript const orderParams = { orderType: OrderType.LIMIT, marketIndex: 1, direction: PositionDirection.LONG, baseAssetAmount: driftClient.convertToSpotPrecision(1, 100), price: driftClient.convertToPricePrecision(100), } await driftClient.placeSpotOrder(orderParams); ``` -------------------------------- ### Configure Bundler for M1 Macs Source: https://github.com/drift-labs/v2-teacher/blob/main/README.md Sets a configuration option for Bundler to force the use of a specific Ruby platform, which is often necessary for M1 Macs to resolve compatibility issues during gem installation. ```shell bundle config set force_ruby_platform true ``` -------------------------------- ### Listening to Perp Market Fills (TypeScript) Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md Example of how to listen for perp market fill events using the TypeScript SDK. ```APIDOC ## Listening to Perp Market Fills (TypeScript) This example demonstrates how to filter and react to specific 'Fill' events on perp markets. ### Request Example ```typescript const marketIndex = 0; const isPerpMarketFill = (event) => { if (event.eventType !== 'OrderActionRecord') { return false; } if (event.marketIndex !== marketIndex) { return false; } if (!isVariant(event.marketType, 'perp')) { return false; } if (!isVariant(event.action, 'fill')) { return false; } return true; }; const fillCallback = (event) => { console.log(event); } // Assuming eventSubscriber is an instance of EventSubscriber eventSubscriber.eventEmitter.on('newEvent', (event) => { if (isPerpMarketFill(event)) { fillCallback(event); } }); ``` ``` -------------------------------- ### Get Perp Market Account (TypeScript, Python) Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md This example shows how to fetch the account details for a perpetual futures market. It provides the equivalent code in both TypeScript and Python, both of which take the market index as a parameter. ```typescript const marketIndex = 0; const perpMarketAccount = driftClient.getPerpMarketAccount(marketIndex); ``` ```python market_index = 0 perp_market_account = drift_client.get_perp_market_account(market_index) ``` -------------------------------- ### GET /v2/orders Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md Retrieves all open orders for the user. ```APIDOC ## GET /v2/orders ### Description Retrieves all open orders for the user. ### Method GET ### Endpoint /v2/orders ### Parameters None ### Request Example ```shell curl localhost:8080/v2/orders ``` ### Response #### Success Response (200) - **orders** (Array) - A list of open order objects. #### Response Example ```json [ { "orderId": 123, "userOrderId": 456, "marketIndex": 0, "price": "1000000000000000000", "baseAssetAmount": "500000000000000000", "quoteAssetAmount": "500000000000000000", "side": "buy", "orderType": "limit", "status": "open", "timestamp": "1678886400" } ] ``` ``` -------------------------------- ### Connect using Drift Gateway CLI Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md Initiates a connection to a Solana RPC endpoint using the drift-gateway command-line interface. This command starts a gateway service, optionally specifying a port for communication. ```shell drift-gateway https://api.mainnet-beta.solana.com --port 8080 ``` -------------------------------- ### Place Spot Order (Shell) Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md An example using curl to submit a POST request to the Drift Protocol API for placing a limit spot order. The JSON payload includes market index, amount, price, and other relevant order details. ```shell curl -X POST -H 'content-type: application/json' \ -d '{ "orders": [{ "marketIndex": 0, "marketType": "spot", "amount": -1.23, "price": 80.0, "postOnly": true, "orderType": "limit", "immediateOrCancel": false, "reduceOnly": false }] }' \ localhost:8080/v2/orders ``` -------------------------------- ### Place Perpetual Order (Shell) Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md An example using curl to send a POST request to the Drift Protocol API to place a limit perpetual order. It specifies market index, amount, price, and order type within a JSON payload. ```shell curl -X POST -H 'content-type: application/json' \ -d '{ "orders": [{ "marketIndex": 0, "marketType": "perp", "amount": 1.23, "price": 80.0, "postOnly": true, "orderType": "limit", "immediateOrCancel": false, "reduceOnly": false }] }' \ localhost:8080/v2/orders ``` -------------------------------- ### Wallet Management Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md Details on how to set up and use a wallet for signing Solana transactions. Wallets can be loaded from keypair files or configured via environment variables. ```APIDOC ## Wallet ### Description Manages the wallet used for signing Solana transactions. The wallet can be created from a private key or a keypair file. Ensure the wallet has sufficient SOL to cover transaction fees and account initialization rent. ### Code Examples #### TypeScript ```typescript import {Wallet, loadKeypair} from "@drift-labs/sdk"; const keyPairFile = `${process.env.HOME}/.config/solana/my-keypair.json`; const wallet = new Wallet(loadKeypair(keyPairFile)); ``` #### Python ```python import os from anchorpy import Wallet from driftpy.keypair import load_keypair keypair_file = os.path.expanduser('~/.config/solana/my-keypair.json') keypair = load_keypair(keypair_file) wallet = Wallet(keypair) ``` #### Shell ```shell # Use the `DRIFT_GATEWAY_KEY` environment variable to configure the gateway wallet # Provide either a path to a .json keypair or a base58 seed string export DRIFT_GATEWAY_KEY="" ``` ``` -------------------------------- ### Get Open Orders (TypeScript, Python, Shell) Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md Retrieves a list of all currently open orders for the user. Examples are provided for TypeScript, Python, and a cURL command for direct API requests. This function does not require any parameters. ```typescript const orders = user.getOpenOrders(); ``` ```python orders = user.get_open_orders() ``` ```shell curl localhost:8080/v2/orders ``` -------------------------------- ### Client Initialization Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md Configuration options for initializing the Drift client, particularly for delegate accounts. ```APIDOC ## Client Initialization for Delegate Accounts When subscribing to the client for delegate accounts, you have to be explicit about the following parameters: ``` subAccountIds: [SUBACCOUNT_ID], activeSubAccountId: SUBACCOUNT_ID, authority: TARGET_AUTHORITY, ``` ### Parameters #### Query Parameters - **connection** (AsyncClient) - Required - AsyncClient connection to the Solana cluster - **wallet** (Wallet) - Required - Wallet object, can be Keypair or Wallet type - **env** (string) - Optional - Drift environment, 'devnet' or 'mainnet' (Default: "mainnet") - **program_id** (PublicKey) - Optional - Drift program identifier (Default: DRIFT_PROGRAM_ID) - **opts** (TxConfirmationConfig) - Optional - Options for transaction confirmation status (Default: DEFAULT_TX_OPTIONS) - **authority** (PublicKey) - Optional - Public key of the user account authority (Default: None) - **account_subscription** (AccountSubscriptionConfig) - Optional - Configuration for account subscriptions (websockets/polling) (Default: AccountSubscriptionConfig.default()) - **perp_market_indexes** (list[int]) - Optional - List of perpetual market indexes to interact with (Default: None) - **spot_market_indexes** (list[int]) - Optional - List of spot market indexes to interact with (Default: None) - **oracle_infos** (list[OracleInfo]) - Optional - List of OracleInfo objects for market data (Default: None) - **tx_params** (TxParams) - Optional - Additional parameters for transactions (Default: None) - **tx_version** (int) - Optional - Version of the transaction (Default: None) - **tx_sender** (TxSender) - Optional - Object handling the sending of transactions (Default: None) - **active_sub_account_id** (int) - Optional - ID of the initially active sub-account (Default: None) - **sub_account_ids** (list[int]) - Optional - List of sub-account IDs to subscribe to (Default: None) - **market_lookup_table** (PublicKey) - Optional - Public key for the market lookup table (Default: None) ``` -------------------------------- ### Initialize User Revenue Share Escrow (TypeScript) Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md Initializes a `RevenueShareEscrow` account for a user, which is necessary before they can pay builder fees. This is typically an onboarding step provided by the builder. It requires the taker's authority and the number of orders the escrow account should accommodate. ```typescript await userClient.initializeRevenueShareEscrow(takerAuthority, numOrders) ``` -------------------------------- ### Get Perp Position (TypeScript, Python, Shell) Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md Fetches the base asset amount for a perpetual futures position given a market index. This information is used to determine if the position is long or short. Code examples are provided in TypeScript, Python, and as a cURL command for API access. ```typescript const marketIndex = 0; const baseAssetAmount = user.getPerpPosition( marketIndex, )?.baseAssetAmount; const isLong = baseAssetAmount.gte(new BN(0)); const isShort = baseAssetAmount.lt(new BN(0)); ``` ```python market_index = 0 perp_position = user.get_perp_position(market_index) base_asset_amount = perp_position.base_asset_amount if perp_position is not None else 0 is_long = base_asset_amount > 0 is_short = base_asset_amount < 0 ``` ```shell curl -X GET \ -H 'content-type: application/json' \ -d '{"marketIndex":0,"marketType":"perp"}' \ localhost:8080/v2/positions ``` -------------------------------- ### Place Spot Order (Python) Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md Illustrates how to place a limit spot order using the Drift Protocol SDK in Python. This snippet shows the configuration of OrderParams for spot markets, including precision conversion. ```python market_index = 1 order_params = OrderParams( order_type=OrderType.Limit(), base_asset_amount=drift_client.convert_to_spot_precision(100, market_index), market_index=market_index, direction=PositionDirection.Long(), price=drift_client.convert_to_price_precision(100), ) await drift_client.place_spot_order(order_params) ``` -------------------------------- ### Get Deposit/Borrow Amounts (TypeScript, Python, Shell) Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md Retrieves the token amount for a given market index to determine if it represents a deposit or borrow. Supports TypeScript, Python, and includes a cURL example for API interaction. The logic differentiates based on whether the token amount is positive (deposit) or negative (borrow). ```typescript const marketIndex = 0; const tokenAmount = user.getTokenAmount( marketIndex, ); const isDeposit = tokenAmount.gte(new BN(0)); const isBorrow = tokenAmount.lt(new BN(0)); ``` ```python market_index = 0 token_amount = user.get_token_amount(marketIndex) is_deposit = token_amount > 0 is_borrow = token_amount < 0 ``` ```shell curl -X GET \ -H 'content-type: application/json' \ -d '{"marketIndex":0,"marketType":"spot"}' \ localhost:8080/v2/positions ``` -------------------------------- ### Get Funding Rates - Python Source: https://github.com/drift-labs/v2-teacher/blob/main/source/includes/_data_api.md Retrieves the last 30 days of funding rates for a specified market using the Drift Data API. The funding rate is returned as a string and requires division by 1e9 to get the actual rate, and further calculation to convert to a percentage of the oracle price. ```python import requests def get_funding_rates(market_symbol='SOL-PERP'): url = f'https://data.api.drift.trade/fundingRates' params = {'marketName': market_symbol} response = requests.get(url, params=params) return response.json()['fundingRates'] # Example usage, print the funding rates for SOL-PERP market_symbol = 'SOL-PERP' rates = get_funding_rates(market_symbol) print(f"Funding Rates for {market_symbol}:") for rate in rates: funding_rate_pct = (float(rate['fundingRate']) / 1e9) / (float(rate['oraclePriceTwap']) / 1e6) funding_rate_pct_apr = funding_rate_pct * 24 * 365 * 100 # ... any logic here, for example... print(f"Slot: {rate['slot']}, Funding Rate: {funding_rate_pct:.9f}%/hour ({funding_rate_pct_apr:.2f}% APR)") ``` -------------------------------- ### Initialize UserMap with Python Source: https://github.com/drift-labs/v2-teacher/blob/main/source/includes/_orderbook_blockchain.md Initializes a UserMap to track all user accounts using Python. It requires an AsyncClient, Wallet, and DriftClient instance. Users can subscribe via websockets. ```python from solana.rpc.async_api import AsyncClient from solders.keypair import Keypair from anchorpy import Wallet from driftpy.drift_client import DriftClient from driftpy.keypair import load_keypair from driftpy.user_map.user_map import UserMap from driftpy.user_map.user_map_config import UserMapConfig, WebsocketConfig connection = AsyncClient("https://api.mainnet-beta.solana.com") # switch for your own rpc keypair_file = "" # path to keypair file wallet = Wallet(load_keypair(keypair_file)) drift_client = DriftClient( connection, wallet, "mainnet" ) await drift_client.subscribe() user_map_config = UserMapConfig(drift_client, WebsocketConfig()) user_map = UserMap(user_map_config) await user_map.subscribe() ``` -------------------------------- ### Place and Take Perp Order Example (Python) Source: https://context7.com/drift-labs/v2-teacher/llms.txt Demonstrates how to place and take a perpetual futures order using the Drift client. This function requires the Drift client, market index, position direction, and base asset amount as input. It returns the transaction signature upon successful execution or raises an exception if an error occurs. ```python tx_sig = await place_and_take_perp_order( drift_client, 0, # SOL-PERP market index PositionDirection.Long(), 1 # 1 SOL ) ``` -------------------------------- ### User Initialization Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md Initializes a new Drift user account or uses an existing one programmatically. ```APIDOC ## User Initialization Initializing a new drift user account requires some rent (~.035 SOL), which can be reclaimed upon deletion. Alternatively, you can export the private key of an existing user initialized via the UI to use the same user account programmatically. Sub account ids are monotonic. The first user account created will have sub account id 0, the second will have sub account id 1, etc. The next sub account id can be found by calling `driftClient.getNextSubAccountId()` in TypeScript. ### TypeScript #### Request Example ```typescript const [txSig, userPublickKey] = await driftClient.initializeUserAccount( 0, "toly" ); ``` ### Parameters (TypeScript) #### Query Parameters - **subAccountId** (number) - Optional - The sub account id for the new user account. (Default: 0) - **name** (string) - Optional - Display name for the user account (Default: "Main Account") - **referrerInfo** (ReferrerInfo) - Optional - The address of the referrer and referrer stats accounts (Default: None) ### Python #### Request Example ```python tx_sig = await drift_client.initialize_user(sub_account_id=0, name="toly") ``` ### Parameters (Python) #### Query Parameters - **sub_account_id** (int) - Optional - The sub account id for the new user account. (Default: 0) - **name** (str) - Optional - Display name for the user account (Default: None) - **referrer_info** (ReferrerInfo) - Optional - The address of the referrer and referrer stats accounts (Default: None) ``` -------------------------------- ### Get Spot Market Account Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md Retrieves the account information for a specific spot market. ```APIDOC ## GET /spot_market_account ### Description Retrieves the account information for a specific spot market. ### Method GET ### Endpoint `/spot_market_account` ### Parameters #### Query Parameters - **marketIndex** (number) - Required - The market index for the spot market. ### Request Example ```typescript const marketIndex = 1; const spotMarketAccount = driftClient.getSpotMarketAccount(marketIndex); ``` ### Response #### Success Response (200) - **spotMarketAccount** (object) - The account details for the specified spot market. ``` -------------------------------- ### Get Perp Market Account Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md Retrieves the account information for a specific perpetual futures market. ```APIDOC ## GET /perp_market_account ### Description Retrieves the account information for a specific perpetual futures market. ### Method GET ### Endpoint `/perp_market_account` ### Parameters #### Query Parameters - **marketIndex** (number) - Required - The market index for the perpetual market. ### Request Example ```typescript const marketIndex = 0; const perpMarketAccount = driftClient.getPerpMarketAccount(marketIndex); ``` ### Response #### Success Response (200) - **perpMarketAccount** (object) - The account details for the specified perpetual market. ``` -------------------------------- ### GET /v2/unrealizedPNL Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md Retrieves the unrealized PNL for the user, with options to include funding payments and specify a market. ```APIDOC ## GET /v2/unrealizedPNL ### Description Retrieves the unrealized Profit and Loss (PNL) for the user. Allows for customization by including funding payments, specifying a market, and controlling calculation strictness. ### Method GET ### Endpoint /v2/unrealizedPNL ### Parameters #### Query Parameters - **withFunding** (boolean) - Optional - Whether to include unsettled funding payments in the PNL calculation. Defaults to false. - **marketIndex** (integer) - Optional - The index of a specific market for which to calculate PNL. If not provided, PNL for all markets is calculated. - **withWeightMarginCategory** (boolean) - Optional - To include margin category weighting in PNL calculation. - **strict** (boolean) - Optional - Whether the calculation should be strict. Defaults to false. ### Request Example ```shell curl "localhost:8080/v2/unrealizedPNL?withFunding=true&marketIndex=0" ``` ### Response #### Success Response (200) - **pnl** (BN) - The calculated unrealized PNL. #### Response Example ```json { "pnl": "100000000000000000" } ``` ``` -------------------------------- ### GET /user (User Management) Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md Retrieve user information, optionally specifying a sub-account ID or authority. ```APIDOC ## GET /user (User Management) ### Description Retrieve user information, optionally specifying a sub-account ID or authority. ### Method GET ### Endpoint /user ### Parameters #### Query Parameters - **subAccountId** (number) - Optional - The sub account id of user to get. Defaults to the active sub account. - **authority** (string) - Optional - The authority of user to get. Only necessary if using multiple delegate accounts. Defaults to the current authority. ### Response #### Success Response (200) - **user_data** (object) - Contains the user's account details. ``` -------------------------------- ### Get Auction Parameters for Market Orders (Python) Source: https://context7.com/drift-labs/v2-teacher/llms.txt Retrieves recommended auction parameters for market orders using Python. This function takes market index, type, direction, amount, asset type, and auction duration. It constructs a URL with query parameters and makes an HTTP GET request. The response is parsed as JSON, and relevant auction details are printed. Error handling for request exceptions is included. ```python import requests from urllib.parse import urlencode def get_auction_params( market_index, market_type='perp', direction='long', amount=100000000000, asset_type='base', auction_duration=45 ): base_url = 'https://dlob.drift.trade/auctionParams' params = { 'marketIndex': market_index, 'marketType': market_type, 'direction': direction, 'amount': amount, 'assetType': asset_type, 'auctionDuration': auction_duration, } try: url = f"{base_url}?{urlencode(params)}" response = requests.get(url) response.raise_for_status() auction_params = response.json() print('Auction Parameters:') print(f"Market: {market_type} {market_index}") print(f"Direction: {direction}") print(f"Entry Price: ${float(auction_params['entryPrice']):.4f}") print(f"Best Price: ${float(auction_params['bestPrice']):.4f}") print(f"Worst Price: ${float(auction_params['worstPrice']):.4f}") print(f"Price Impact: {auction_params['priceImpact'] * 100:.3f}%") print(f"Auction Duration: {auction_params['params']['auctionDuration']}s") print(f"Auction Start Price: ${float(auction_params['params']['auctionStartPrice']):.4f}") print(f"Auction End Price: ${float(auction_params['params']['auctionEndPrice']):.4f}") return auction_params except requests.RequestException as error: print(f'Error fetching auction params: {error}') raise # Example: Get auction params for buying 100 SOL-PERP params = get_auction_params( market_index=0, # SOL-PERP market_type='perp', direction='long', amount=100000000000, # 100 SOL in base precision (1e9) asset_type='base', auction_duration=45 ) ``` -------------------------------- ### GET /contracts Source: https://github.com/drift-labs/v2-teacher/blob/main/source/includes/_data_api.md Retrieves contract information for each market, including funding rates and open interest (oi). ```APIDOC ## GET /contracts ### Description Returns the contract information for each market. Contract information contains funding rate and open interest (oi). ### Method GET ### Endpoint /contracts ### Parameters #### Query Parameters None ### Request Example ```json { "example": "GET /contracts" } ``` ### Response #### Success Response (200) - **contracts** (array) - An array of contract objects, each containing market details. - **marketName** (string) - The name of the market. - **fundingRate** (string) - The current funding rate. - **openInterest** (string) - The open interest for the market. #### Response Example ```json { "contracts": [ { "marketName": "SOL-PERP", "fundingRate": "123456789", "openInterest": "987654321" } ] } ``` ``` -------------------------------- ### Drift Vaults CLI: Initialize a New Vault Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md This command initializes a new Drift Vault with specified parameters such as name, market index, redeem period, fees, and permission settings. It requires the vault name, market index, and optionally delegate address, RPC URL, and keypair path. This command sets up a new vault managed by the user. ```bash yarn cli init-vault \ --name "test vault" \ --market-index 1 \ --redeem-period 3600 \ --max-tokens 10000 \ --management-fee 2 \ --profit-share 20 \ --permissioned \ --min-deposit-amount 1 \ --url \ --keypair ~/.config/solana/keypair.json ``` -------------------------------- ### Get Auction Parameters for Market Orders (TypeScript) Source: https://context7.com/drift-labs/v2-teacher/llms.txt Retrieves recommended auction parameters for market orders. This function takes market details, order direction, amount, asset type, and auction duration as input. It makes an HTTP GET request to the Drift API and returns a detailed AuctionParams object, or throws an error if the request fails. The output includes various price points, price impact, and auction specifics. ```typescript interface AuctionParams { params: { orderType: string; marketType: string; userOrderId: number; direction: string; baseAssetAmount: string; marketIndex: number; reduceOnly: boolean; postOnly: string; auctionDuration: number; auctionStartPrice: string; auctionEndPrice: string; oraclePriceOffset: number; }; entryPrice: string; bestPrice: string; worstPrice: string; priceImpact: number; slippageTolerance: number; } async function getAuctionParams( marketIndex: number, marketType: 'perp' | 'spot', direction: 'long' | 'short', amount: number, assetType: 'base' | 'quote', auctionDuration: number = 45 ): Promise { const baseUrl = 'https://dlob.drift.trade/auctionParams'; const params = new URLSearchParams({ marketIndex: marketIndex.toString(), marketType, direction, amount: amount.toString(), assetType, auctionDuration: auctionDuration.toString(), }); try { const response = await fetch(`${baseUrl}?${params}`); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const auctionParams: AuctionParams = await response.json(); console.log('Auction Parameters:'); console.log(`Market: ${marketType} ${marketIndex}`); console.log(`Direction: ${direction}`); console.log(`Entry Price: $${parseFloat(auctionParams.entryPrice).toFixed(4)}`); console.log(`Best Price: $${parseFloat(auctionParams.bestPrice).toFixed(4)}`); console.log(`Worst Price: $${parseFloat(auctionParams.worstPrice).toFixed(4)}`); console.log(`Price Impact: ${(auctionParams.priceImpact * 100).toFixed(3)}%`); console.log(`Auction Duration: ${auctionParams.params.auctionDuration}s`); console.log(`Auction Start Price: $${parseFloat(auctionParams.params.auctionStartPrice).toFixed(4)}`); console.log(`Auction End Price: $${parseFloat(auctionParams.params.auctionEndPrice).toFixed(4)}`); return auctionParams; } catch (error) { console.error('Error fetching auction params:', error); throw error; } } // Example: Get auction params for buying 100 SOL-PERP (in base units: 100 * 1e9) const params = await getAuctionParams( 0, // SOL-PERP market index 'perp', 'long', 100000000000, // 100 SOL in base precision (1e9) 'base', 45 // 45 second auction ); ``` -------------------------------- ### Place Perpetual Order (TypeScript) Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md Demonstrates placing various types of perpetual orders (market, limit, bid, ask) using the driftClient in TypeScript. It shows how to configure order parameters like type, direction, amount, and price with precision conversion. ```typescript // market buy for 100 SOL-PERP @ $21.20->$21.30 over 60 slots (~30 seconds) // after 60 slots, market buy 100 SOL-PERP @ $21.35 until maxTs const orderParams = { orderType: OrderType.MARKET, marketIndex: 0, direction: PositionDirection.LONG, baseAssetAmount: driftClient.convertToPerpPrecision(100), auctionStartPrice: driftClient.convertToPricePrecision(21.20), auctionEndPrice: driftClient.convertToPricePrecision(21.30), price: driftClient.convertToPricePrecision(21.35), auctionDuration: 60, maxTs: now + 100, } await driftClient.placePerpOrder(orderParams); // bid for 100 SOL-PERP @ $21.23 const orderParams = { orderType: OrderType.LIMIT, marketIndex: 0, direction: PositionDirection.LONG, baseAssetAmount: driftClient.convertToPerpPrecision(100), price: driftClient.convertToPricePrecision(21.23), } await driftClient.placePerpOrder(orderParams); // ask for 100 SOL-PERP @ ${OraclePrice} + .05 const orderParams = { orderType: OrderType.LIMIT, marketIndex: 0, direction: PositionDirection.SHORT, baseAssetAmount: driftClient.convertToPerpPrecision(100), oraclePriceOffset: driftClient.convertToPricePrecision(.05).toNumber(), } await driftClient.placePerpOrder(orderParams); ``` -------------------------------- ### Initialize Drift Client (Python) Source: https://context7.com/drift-labs/v2-teacher/llms.txt Initializes a Drift client for interacting with the Drift Protocol on Solana using Python. It requires an AsyncClient for connection, a wallet loaded from a keypair file, and specification of environment and market indexes. The client is then subscribed to. ```python from anchorpy import Wallet from driftpy.drift_client import DriftClient from driftpy.keypair import load_keypair from solana.rpc.async_api import AsyncClient import os connection = AsyncClient('https://api.mainnet-beta.solana.com') keypair_file = os.path.expanduser('~/.config/solana/my-keypair.json') keypair = load_keypair(keypair_file) wallet = Wallet(keypair) drift_client = DriftClient( connection, wallet, "mainnet", perp_market_indexes=[0, 1, 2], spot_market_indexes=[0, 1], ) await drift_client.add_user(0) # Add user with sub account id 0 await drift_client.subscribe() print(f"Connected to Drift Protocol") print(f"User account: {wallet.public_key}") ``` -------------------------------- ### Get Unrealized Funding Pnl Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md Retrieves the unrealized funding profit and loss (PnL) for the user. Supports filtering by a specific market. ```APIDOC ## GET /user/unrealized_funding_pnl ### Description Retrieves the unrealized funding profit and loss (PnL) for the user. Supports filtering by a specific market. ### Method GET ### Endpoint /user/unrealized_funding_pnl ### Query Parameters - **marketIndex** (string) - Optional - Whether to only return pnl for a specific market. ### Response #### Success Response (200) - **pnl** (number) - The unrealized funding PnL. ### Response Example { "pnl": 123.45 } ``` -------------------------------- ### Get Free Collateral Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md Calculates and returns the free collateral available to the user. Free collateral is the difference between total collateral and the margin requirement. ```APIDOC ## GET /user/free_collateral ### Description Calculates and returns the free collateral available to the user. Free collateral is the difference between total collateral and the margin requirement. ### Method GET ### Endpoint /user/free_collateral ### Query Parameters - **marginCategory** (string) - Optional - Specifies whether to use 'Initial' or 'Maintenance' margin for calculation. Defaults to 'Initial'. ### Response #### Success Response (200) - **freeCollateral** (number) - The amount of free collateral. ### Response Example { "freeCollateral": 2500.25 } ``` -------------------------------- ### Initialize DriftClient (Python) Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md Initializes the DriftClient with a Solana connection and wallet in Python. This client facilitates interaction with the Drift protocol. It requires a pre-existing Drift account and subscribes to on-chain data. ```python from anchorpy import Wallet from driftpy.drift_client import DriftClient from solana.rpc.async_api import AsyncClient # set connection and wallet # ... drift_client = DriftClient(connection, wallet, "mainnet") await drift_client.add_user(0) # Assuming a Drift account has already been created await drift_client.subscribe() ``` -------------------------------- ### Initialize Drift Client (TypeScript) Source: https://context7.com/drift-labs/v2-teacher/llms.txt Initializes a Drift client for interacting with the Drift Protocol on Solana. Requires connection to the Solana RPC, a wallet, and specifying market indexes and subscription type. It establishes a connection and subscribes to real-time data. ```typescript import { Connection } from "@solana/web3.js"; import { Wallet, loadKeypair, DriftClient } from "@drift-labs/sdk"; const connection = new Connection('https://api.mainnet-beta.solana.com', 'confirmed'); const keyPairFile = `${process.env.HOME}/.config/solana/my-keypair.json`; const wallet = new Wallet(loadKeypair(keyPairFile)); const driftClient = new DriftClient({ connection, wallet, env: 'mainnet-beta', perpMarketIndexes: [0, 1, 2], // SOL-PERP, BTC-PERP, ETH-PERP spotMarketIndexes: [0, 1], // USDC, SOL accountSubscription: { type: 'websocket', resubTimeoutMs: 30_000, }, }); await driftClient.subscribe(); // Verify connection console.log('Connected to Drift Protocol'); console.log('User account:', driftClient.wallet.publicKey.toString()); ``` -------------------------------- ### Get Total Collateral Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md Calculates and returns the total collateral for the user's account. The calculation can be adjusted based on margin category and strictness. ```APIDOC ## GET /user/total_collateral ### Description Calculates and returns the total collateral for the user's account. The calculation can be adjusted based on margin category and strictness. ### Method GET ### Endpoint /user/total_collateral ### Query Parameters - **marginCategory** (string) - Optional - Specifies whether to use 'Initial' or 'Maintenance' margin for calculation. Defaults to 'Initial'. - **strict** (boolean) - Optional - Determines if the calculation should be strict. Defaults to false. ### Response #### Success Response (200) - **totalCollateral** (number) - The total collateral amount. ### Response Example { "totalCollateral": 5000.75 } ``` -------------------------------- ### Get User Information (Python) Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md Retrieves the current user's information using the `drift_client`. This is the Python equivalent of fetching user data. ```python user = drift_client.get_user() ``` -------------------------------- ### Initialize DriftClient (TypeScript) Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md Initializes the DriftClient with a Solana connection and a wallet. This client is used to interact with the Drift protocol. The client subscribes to necessary accounts after initialization. Ensure the connection and wallet are properly configured. ```typescript import {Connection} from "@solana/web3.js"; import {Wallet, loadKeypair, DriftClient} from "@drift-labs/sdk"; const connection = new Connection('https://api.mainnet-beta.solana.com', 'confirmed'); const keyPairFile = `${process.env.HOME}/.config/solana/my-keypair.json`; const wallet = new Wallet(loadKeypair(keyPairFile)) const driftClient = new DriftClient({ connection, wallet, env: 'mainnet-beta', }); await driftClient.subscribe(); ``` -------------------------------- ### Placing Oracle Market Orders Source: https://github.com/drift-labs/v2-teacher/blob/main/source/index.html.md Enables users to place oracle market orders by defining auction parameters relative to the oracle price. ```APIDOC ## Placing Oracle Market Orders ### Description Place an oracle market order with specified auction parameters. ### Method POST (Implicit, as part of a broader order placement functionality) ### Endpoint (Likely part of a general order placement endpoint, e.g., /v2/orders or /v2/perp/orders) ### Parameters #### Request Body (Example for `driftClient.placePerpOrder`) - **orderType** (OrderType.ORACLE) - Required - Specifies the order type as ORACLE. - **baseAssetAmount** (number) - Required - The amount of base asset for the order. - **direction** (PositionDirection) - Required - The direction of the position (LONG or SHORT). - **marketIndex** (number) - Required - The index of the market. - **auctionStartPrice** (number) - Required - The starting price for the auction. - **auctionEndPrice** (number) - Required - The ending price for the auction. - **oraclePriceOffset** (number) - Required - The offset from the oracle price for the limit price after the auction. - **auctionDuration** (number) - Required - The duration of the auction in slots. ### Request Example (TypeScript) ```typescript const orderParams = { orderType: OrderType.ORACLE, baseAssetAmount: driftClient.convertToPerpPrecision(10), direction: PositionDirection.LONG, marketIndex: 18, auctionStartPrice: auctionStartPrice, auctionEndPrice: auctionEndPrice, oraclePriceOffset: oraclePriceOffset, auctionDuration: auctionDuration, }; await driftClient.placePerpOrder(orderParams) ``` ### Response #### Success Response Confirmation of the oracle market order placement. ```