# Table of Contents - [Contributing to Drift Protocol – Drift Protocol ](#contributing-to-drift-protocol-drift-protocol-) - [Optimizations – Drift Protocol ](#optimizations-drift-protocol-) - [Decentralized Orderbook – Drift Protocol ](#decentralized-orderbook-drift-protocol-) - [Keepers – Drift Protocol ](#keepers-drift-protocol-) - [Keepers & Decentralized Orderbook (DLOB) FAQ – Drift Protocol ](#keepers-decentralized-orderbook-dlob-faq-drift-protocol-) - [Drift AMM – Drift Protocol ](#drift-amm-drift-protocol-) - [Program Vault Addresses – Drift Protocol ](#program-vault-addresses-drift-protocol-) - [Keeper Incentives – Drift Protocol ](#keeper-incentives-drift-protocol-) - [Revenue Pool – Drift Protocol ](#revenue-pool-drift-protocol-) - [Matching Engine – Drift Protocol ](#matching-engine-drift-protocol-) - [Phantom Setup – Drift Protocol ](#phantom-setup-drift-protocol-) - [Understanding Drift Protocol – Drift Protocol ](#understanding-drift-protocol-drift-protocol-) - [Introduction – Drift Protocol ](#introduction-drift-protocol-) - [Just-in-Time (JIT) Maker FAQ – Drift Protocol ](#just-in-time-jit-maker-faq-drift-protocol-) - [Prelaunch Market – Drift Protocol ](#prelaunch-market-drift-protocol-) - [How to trade Perpetual Swaps? – Drift Protocol ](#how-to-trade-perpetual-swaps-drift-protocol-) - [What are Perpetual Futures – Drift Protocol ](#what-are-perpetual-futures-drift-protocol-) - [Funding Rates – Drift Protocol ](#funding-rates-drift-protocol-) - [What is Spot Margin Trading? – Drift Protocol ](#what-is-spot-margin-trading-drift-protocol-) - [Spot FAQ – Drift Protocol ](#spot-faq-drift-protocol-) - [Order Types – Drift Protocol ](#order-types-drift-protocol-) - [All Order Types – Drift Protocol ](#all-order-types-drift-protocol-) - [Margin Requirements – Drift Protocol ](#margin-requirements-drift-protocol-) - [Advanced Orders FAQ – Drift Protocol ](#advanced-orders-faq-drift-protocol-) - [Account Health Breakdown – Drift Protocol ](#account-health-breakdown-drift-protocol-) - [Auction Parameters – Drift Protocol ](#auction-parameters-drift-protocol-) - [Metamask Setup – Drift Protocol ](#metamask-setup-drift-protocol-) - [Bot Wallet Setup – Drift Protocol ](#bot-wallet-setup-drift-protocol-) - [Passwordless login – Drift Protocol ](#passwordless-login-drift-protocol-) - [Creating and Managing Subaccount – Drift Protocol ](#creating-and-managing-subaccount-drift-protocol-) - [Wallet Faq – Drift Protocol ](#wallet-faq-drift-protocol-) - [Other Trading Fees – Drift Protocol ](#other-trading-fees-drift-protocol-) - [Cross-collateral deposits – Drift Protocol ](#cross-collateral-deposits-drift-protocol-) - [Delegated Accounts – Drift Protocol ](#delegated-accounts-drift-protocol-) - [Versioned Transactions – Drift Protocol ](#versioned-transactions-drift-protocol-) - [Withdraw and Close Account – Drift Protocol ](#withdraw-and-close-account-drift-protocol-) - [Perpetual Markets Specs – Drift Protocol ](#perpetual-markets-specs-drift-protocol-) - [Trading Fees – Drift Protocol ](#trading-fees-drift-protocol-) - [Fee Pool – Drift Protocol ](#fee-pool-drift-protocol-) - [Block Conditions – Drift Protocol ](#block-conditions-drift-protocol-) - [Versioned Transactions – Drift Protocol ](#versioned-transactions-drift-protocol-) - [Oracles – Drift Protocol ](#oracles-drift-protocol-) - [Introduction to Profit & Loss – Drift Protocol ](#introduction-to-profit-loss-drift-protocol-) - [Accounting & Settlement – Drift Protocol ](#accounting-settlement-drift-protocol-) - [What is unsettled P&L? – Drift Protocol ](#what-is-unsettled-p-l-drift-protocol-) - [P&L Pool – Drift Protocol ](#p-l-pool-drift-protocol-) - [What is lending and borrowing? – Drift Protocol ](#what-is-lending-and-borrowing-drift-protocol-) - [Liquidators – Drift Protocol ](#liquidators-drift-protocol-) - [Supply and Borrow APY – Drift Protocol ](#supply-and-borrow-apy-drift-protocol-) - [Liquidations – Drift Protocol ](#liquidations-drift-protocol-) - [Lend Borrow FAQ – Drift Protocol ](#lend-borrow-faq-drift-protocol-) - [Borrow Interest Rate – Drift Protocol ](#borrow-interest-rate-drift-protocol-) - [Isolated Pools – Drift Protocol ](#isolated-pools-drift-protocol-) - [Drift Collateral Rewards – Drift Protocol ](#drift-collateral-rewards-drift-protocol-) - [How it works – Drift Protocol ](#how-it-works-drift-protocol-) - [Closing a Position – Drift Protocol ](#closing-a-position-drift-protocol-) - [Risk – Drift Protocol ](#risk-drift-protocol-) - [Opening a Position – Drift Protocol ](#opening-a-position-drift-protocol-) - [Monitoring existing position – Drift Protocol ](#monitoring-existing-position-drift-protocol-) - [Maker Rebate Fees – Drift Protocol ](#maker-rebate-fees-drift-protocol-) - [Market Maker Participation – Drift Protocol ](#market-maker-participation-drift-protocol-) - [Insurance Fund Staking – Drift Protocol ](#insurance-fund-staking-drift-protocol-) - [Backstop AMM Liquidity (BAL) – Drift Protocol ](#backstop-amm-liquidity-bal-drift-protocol-) - [Drift Builder Codes – Drift Protocol ](#drift-builder-codes-drift-protocol-) - [Bal Provision Faq – Drift Protocol ](#bal-provision-faq-drift-protocol-) - [Insurance Fund Introduction – Drift Protocol ](#insurance-fund-introduction-drift-protocol-) - [SDK Documentation – Drift Protocol ](#sdk-documentation-drift-protocol-) - [BAL Providers – Drift Protocol ](#bal-providers-drift-protocol-) - [Referral Links – Drift Protocol ](#referral-links-drift-protocol-) - [Preparing Environment – Drift Protocol ](#preparing-environment-drift-protocol-) - [Tutorial: Bots – Drift Protocol ](#tutorial-bots-drift-protocol-) - [Tutorial: Order Trigger Bot – Drift Protocol ](#tutorial-order-trigger-bot-drift-protocol-) - [Tutorial: Order Matching Bot – Drift Protocol ](#tutorial-order-matching-bot-drift-protocol-) - [RPC Providers – Drift Protocol ](#rpc-providers-drift-protocol-) - [Tutorial: Liquidation Bot – Drift Protocol ](#tutorial-liquidation-bot-drift-protocol-) - [Troubleshooting – Drift Protocol ](#troubleshooting-drift-protocol-) - [Historical Data V1 – Drift Protocol ](#historical-data-v1-drift-protocol-) - [JIT Maker Bot – Drift Protocol ](#jit-maker-bot-drift-protocol-) - [Historical Data V2 – Drift Protocol ](#historical-data-v2-drift-protocol-) - [Risk Parameters – Drift Protocol ](#risk-parameters-drift-protocol-) - [Introduction to Prediction Markets – Drift Protocol ](#introduction-to-prediction-markets-drift-protocol-) - [Delisting Process – Drift Protocol ](#delisting-process-drift-protocol-) - [Introduction – Drift Protocol ](#introduction-drift-protocol-) - [Audits – Drift Protocol ](#audits-drift-protocol-) - [Protocol Guard Rails – Drift Protocol ](#protocol-guard-rails-drift-protocol-) - [Bug Bounty – Drift Protocol ](#bug-bounty-drift-protocol-) - [Risks – Drift Protocol ](#risks-drift-protocol-) - [Historical Data Glossary – Drift Protocol ](#historical-data-glossary-drift-protocol-) - [Additional Resources and Data – Drift Protocol ](#additional-resources-and-data-drift-protocol-) - [Glossary – Drift Protocol ](#glossary-drift-protocol-) - [Overview – Drift Protocol ](#overview-drift-protocol-) - [Terms of Use – Drift Protocol ](#terms-of-use-drift-protocol-) - [Privacy Policy – Drift Protocol ](#privacy-policy-drift-protocol-) - [Disclaimer – Drift Protocol ](#disclaimer-drift-protocol-) - [Competition Terms – Drift Protocol ](#competition-terms-drift-protocol-) --- # Contributing to Drift Protocol – Drift Protocol Contributing to Drift Protocol ============================== Interested in contributing to the Drift Protocol? There are multiple ways to make valuable contributions, from documentation to code and more. Below are some of the primary avenues you can explore: Table of Contents[](https://docs.drift.trade/contributing-to-drift#table-of-contents) -------------------------------------------------------------------------------------- * [Documentation](https://docs.drift.trade/contributing-to-drift#documentation) * [Bot Code](https://docs.drift.trade/contributing-to-drift#bot-code) * [TypeScript SDK](https://docs.drift.trade/contributing-to-drift#typescript-sdk) * [Composing Programs on Top of Drift](https://docs.drift.trade/contributing-to-drift#composing-programs-on-top-of-drift) * [Main Program Contributions](https://docs.drift.trade/contributing-to-drift#main-program-contributions) Documentation[](https://docs.drift.trade/contributing-to-drift#documentation) ------------------------------------------------------------------------------ Raise issues or submit Pull Requests at the [Drift Documentation Repository (opens in a new tab)](https://github.com/drift-labs/v2-teacher) . Bot Code[](https://docs.drift.trade/contributing-to-drift#bot-code) -------------------------------------------------------------------- ### Keeper Bots[](https://docs.drift.trade/contributing-to-drift#keeper-bots) * Repository: [keeper bots (opens in a new tab)](https://github.com/drift-labs/keeper-bots-v2) * Example: `filler-lite` is a recent effort to make running a keeper bot more accessible for lower-performing RPCs. [Learn More (opens in a new tab)](https://github.com/drift-labs/keeper-bots-v2/blob/master/src/bots/fillerLite.ts) ### Trading Bots[](https://docs.drift.trade/contributing-to-drift#trading-bots) * JIT Proxy Program: [Repository (opens in a new tab)](https://github.com/drift-labs/jit-proxy) * JIT Maker: [Source Code (opens in a new tab)](https://github.com/drift-labs/keeper-bots-v2/blob/master/src/bots/jitMaker.ts) TypeScript SDK[](https://docs.drift.trade/contributing-to-drift#typescript-sdk) -------------------------------------------------------------------------------- Add new features or improve code quality and maintainability at the [TypeScript SDK Repository (opens in a new tab)](https://github.com/drift-labs/protocol-v2/tree/master/sdk) . Expanding SDK Language Support[](https://docs.drift.trade/contributing-to-drift#expanding-sdk-language-support) ---------------------------------------------------------------------------------------------------------------- Use TypeScript SDK as a reference to add more language support for broader access. ### Rust SDK[](https://docs.drift.trade/contributing-to-drift#rust-sdk) * Repository: [driftrs (opens in a new tab)](https://github.com/drift-labs/drift-rs) . ### Python SDK[](https://docs.drift.trade/contributing-to-drift#python-sdk) * Repository: [driftpy (opens in a new tab)](https://github.com/drift-labs/driftpy) Composing Programs on Top of Drift[](https://docs.drift.trade/contributing-to-drift#composing-programs-on-top-of-drift) ------------------------------------------------------------------------------------------------------------------------ * Example: [Drift Vaults (opens in a new tab)](https://github.com/drift-labs/drift-vaults) * Feature Requests: Tokenization of the insurance fund stake has been requested. Main Program Contributions[](https://docs.drift.trade/contributing-to-drift#main-program-contributions) -------------------------------------------------------------------------------------------------------- * Expanding the test suite (both TypeScript and Cargo tests) at the [Main Program Repository (opens in a new tab)](https://github.com/drift-labs/protocol-v2/tree/master/programs/drift) . * Security: There is an Immunefi bug bounty program for identifying and sharing proof of concepts of smart contract bugs that could lead to a loss of funds. Feel free to pick a project or issue that interests you and start contributing! --- # Optimizations – Drift Protocol 🏎 About Drift v2 Optimizations Optimizations ============= Drift Protocol's AMM (AMM) acts as the designated market maker to provide a guaranteed liquidity source for traders. To overcome latency arbitrage, adverse selection and toxic flow, a number of optimisations were made within the protocol while following particular constraints such as maximum allowable spread and minimum liquidity depth. > Drift's AMM essentially bootstraps liquidity in a perpetuals market and offers a competitive lower bound as opposed to relying fully on external liquidity providers which can freely come and go. Auction Process[](https://docs.drift.trade/about-v2/optimizations#auction-process) ----------------------------------------------------------------------------------- The auction process itself acts as a speedbump against latency arbitrage of the oracle and the AMM. This helps to reduce the adverse selection faced on-chain. Concentration Factor[](https://docs.drift.trade/about-v2/optimizations#concentration-factor) --------------------------------------------------------------------------------------------- The size of k (the constant product invariant) determines the depth of liquidity. By increasing k by a factor of but making the max/min base reserves tighter, the AMM can provide the same amount of bid and ask liquidity but it is now concentrated with a tighter price range. Formulaic K[](https://docs.drift.trade/about-v2/optimizations#formulaic-k) --------------------------------------------------------------------------- After every funding rate update, if the net revenue (in terminal) increased over the hour, the AMM will utilize the funding received to increase k (hence the depth of liquidity provided). Otherwise, if the AMM had to pay funding over the previous hour, a portion of the payment will be utilized to reduce k (decrease liquidity offering). These updates have maximum update amounts of .1% but are used to converge toward an optimal k over time. Participation in the JIT Auction[](https://docs.drift.trade/about-v2/optimizations#participation-in-the-jit-auction) --------------------------------------------------------------------------------------------------------------------- Just as market makers provide active liquidity through the JIT auction process, the AMM may also opt to participate as well in order to reduce inventory. P&L Settlement[](https://docs.drift.trade/about-v2/optimizations#pl-settlement) -------------------------------------------------------------------------------- Due to: * Potential market imbalances; * Live-oracle based pricing; and * Maximum allowable spread set by the AMM, The way unrealised P&L users can lock in from entering and exiting a trade against the AMM is technically unbounded (e.g. if BTC goes toward infinity). However, whilst a user can achieve this unrealised gain, it is important to note that an offsetting loss (or sufficient fees collected) is necessary before the unrealised gain can be settled in full and withdrawable as collateral. Until the P&L pool is replenished by offsetting losses, winners may\* be offered discounted margin on unrealised gains. Winners will have the ability to withdraw their portion from the P&L settlement pool as it increases. Read more about the settlement mechanism in [P&L](https://docs.drift.trade/profit-loss/profit-loss-intro) . **\***: If the unrealised P&L imbalance exceeds its per-market threshold, those unrealised gains may be discounted by the margining system (initial, not maintenance) to prevent large borrows against it. This initial margin discounting would only impact new positions being opened and would not affect a user's liquidation threshold. These rules are systemitised and can be read more under the Margin subheading in [Cross-Collateral Deposits](https://docs.drift.trade/getting-started/cross-collateral-deposits) . Terminal State Consideration[](https://docs.drift.trade/about-v2/optimizations#terminal-state-consideration) ------------------------------------------------------------------------------------------------------------- If the inventory on the AMM is 0, all the repeg and k change operations have no terminal state costs. Even so, the AMM is still fully aware of the remaining position imbalance within the market and makes decisions on its spread size and liquidity depth based on that awareness (while following its constraints as a designated market maker). [Revenue Pool](https://docs.drift.trade/about-v2/revenue-pool "Revenue Pool") [Program/Vault Addresses](https://docs.drift.trade/about-v2/program-vault-addresses "Program/Vault Addresses") --- # Decentralized Orderbook – Drift Protocol 🏎 About Drift v2 Decentralized Orderbook Decentralized Orderbook ======================= Overview[](https://docs.drift.trade/about-v2/decentralized-orderbook#overview) ------------------------------------------------------------------------------- Drift's decentralised orderbook is powered by our network of [Keeper Bots](https://docs.drift.trade/about-v2/keepers) . The Keeper Bots match open orders with various on-chain liquidity mechanisms once they cross or their trigger condition is met. These scenarios include: * Taker auction against Taker auction; * Taker/Maker limit orders against Taker auction; * Maker limit orders against Taker limit orders; * Taker/Maker orders against the Drift's AMM. _Note: (1) two post only maker orders cannot be crossed; (2) maker orders that fill against the AMM are not eligible for rebate reward; and (3) limit orders can be filled by market orders that go through the JIT auction._ Keepers earn rewards that incentivise: 1. providing the best execution for takers (relative to the oracle price) and; 2. following First-Come-First-Serve execution ordering While a robust Keepers network improves throughput/usability, the protocol's core functionality is not crunched upon it. Existing trading bots (JIT makers and resting order takers) implicitly fulfil the role of Keepers. ### Build Philosophy[](https://docs.drift.trade/about-v2/decentralized-orderbook#build-philosophy) The decentralised orderbook is designed with two core values in mind: 1. decentralisation;  and 2. computational efficiency. _Decentralisation_ is achieved through our network of hybrid off-chain Keepers that anyone can build and run — similar to liquidator bots. _Computational efficiency_ is achieved by leaving the order-filling logic — the part that requires the most computational power — off-chain, and filling them on-chain upon a trigger. Hence, Drift’s unique limit order system is a _hybrid_ system that uses a combination off-chain Keepers and on-chain settlement. [Drift AMM](https://docs.drift.trade/about-v2/drift-amm "Drift AMM") [Keepers](https://docs.drift.trade/about-v2/keepers "Keepers") --- # Keepers – Drift Protocol 🏎 About Drift v2 Keepers Keepers ======= Keeper Bots[](https://docs.drift.trade/about-v2/keepers#keeper-bots) --------------------------------------------------------------------- Keeper Bots listen, store, sort and fill valid limit orders. Keepers do this by compiling all valid open orders found on-chain and organising them into an off-chain orderbook. These orders are sorted by price and age, and if two orders have the same age, they’re then sorted by position size. Each Keeper holds its own orderbook (hence '_decentralised_ orderbook'). Keepers then listen to trigger conditions and match crossing orders and limit orders against the AMM when the users’ trigger or limit price is met. For performing this critical duty, the Keepers earn a fee for every trade they execute. Similar to liquidation bots, Keepers will compete for fees in a decentralised system; with the most profitable Keepers being: 1. the fastest; 2. the best price improvement for takers; and 3. the ones that fulfil orders in the protocol’s desired sequence — oldest and largest first. Reference implementations for the filler and trigger Keepers are provided: [Keeper Bots](https://docs.drift.trade/tutorial-bots) . ![](https://docs.drift.trade/_next/image?url=%2F_next%2Fstatic%2Fmedia%2F_7EXFtBAy_tQDOSdL_VIL_image.6fbf0bea.png&w=3840&q=75) [Decentralized Orderbook](https://docs.drift.trade/about-v2/decentralized-orderbook "Decentralized Orderbook") [Keepers & Decentralized Orderbook FAQ](https://docs.drift.trade/about-v2/keepers-decentralized-orderbook-faq "Keepers & Decentralized Orderbook FAQ") --- # Keepers & Decentralized Orderbook (DLOB) FAQ – Drift Protocol 🏎 About Drift v2 Keepers & Decentralized Orderbook FAQ Keepers & Decentralized Orderbook (DLOB) FAQ ============================================ ### Is this the same as a traditional orderbook? How are the limit orders filled?[](https://docs.drift.trade/about-v2/keepers-decentralized-orderbook-faq#is-this-the-same-as-a-traditional-orderbook-how-are-the-limit-orders-filled) Drift's decentralised orderbook (DLOB) is different to a traditional orderbook. Limit orders placed on Drift's decentralised orderbook are filled either: * against each other (buys and sells at the same price); * against the AMM if the trigger conditions are met. The orders are stored and settled on-chain. The queue is constructed by a network of off-chain Keepers that are incentivised to fill orders against the AMM or each other based on age. ### Is the Keeper network guaranteed to execute my order?[](https://docs.drift.trade/about-v2/keepers-decentralized-orderbook-faq#is-the-keeper-network-guaranteed-to-execute-my-order) Orders are executed 'best effort' by the network and are powered by special economic incentives designed to mimic the typical execution order seen in a Centralised Limit Order Book (CLOB). ### How is an orderbook constructed off-chain?[](https://docs.drift.trade/about-v2/keepers-decentralized-orderbook-faq#how-is-an-orderbook-constructed-off-chain) When a user submits a limit order, it is submitted onto the Solana blockchain. This is known as an on-chain order. Keeper Bots monitor all open limit orders placed on-chain. Similar to the way liquidator bots track all user positions to monitor liquidation eligibility; Keeper Bots monitor the eligibility of limit orders to be filled. To accomplish this, Keeper Bots construct an orderbook structure off-chain categorising all the open limit orders by price, age, and then position size. Once the particular requisite trigger condition is met, the Keeper Bot will fill the oldest valid order against the AMM for a financial incentive. If two orders have the same age, the Keeper Bot will most likely fill the order that is larger in size (up to the incentive cap). ### Why is the orderbook constructed off-chain?[](https://docs.drift.trade/about-v2/keepers-decentralized-orderbook-faq#why-is-the-orderbook-constructed-off-chain) Drift doesn't construct a central limit orderbook on-chain and instead opts for a flat structure to achieve cost-effective scalability. The network of Keepers monitor on-chain orders and constructs their own orderbooks off-chain. This achieves (1) decentralisation (as each Keeper stores its own copy of the orderbook); and (2) computational efficiency (as the high throughput and intensive computations are calculated off-chain). This should translate to better performance during periods of high network congestion. ### What are Keeper bots? How can I participate?[](https://docs.drift.trade/about-v2/keepers-decentralized-orderbook-faq#what-are-keeper-bots-how-can-i-participate) A Keeper will track and fill orders and earn a reward. The guide to run is listed in [Keeper Bots](https://docs.drift.trade/tutorial-bots/keeper-bots) . Incentive structures are listed in [Keeper Incentives](https://docs.drift.trade/about-v2/keeper-incentives) . [Keepers](https://docs.drift.trade/about-v2/keepers "Keepers") [Keeper Incentives](https://docs.drift.trade/about-v2/keeper-incentives "Keeper Incentives") --- # Drift AMM – Drift Protocol 🏎 About Drift v2 Drift AMM Drift AMM ========= Introduction[](https://docs.drift.trade/about-v2/drift-amm#introduction) ------------------------------------------------------------------------- Drift uses a backstop AMM as a source of guaranteed constant liquidity for the exchange, providing constant liquidity to be taken against asynchronously. Drift's v1 featured a Dynamic AMM which was an iteration on top of Perpetual Protocol's innovation - the [virtual AMM (vAMM) (opens in a new tab)](https://blog.perp.fi/a-deep-dive-into-our-virtual-amm-vamm-40345c522eeb) , except with configurable parameters, namely: * **Peg:** a price multiplier * **K:** liquidity depth * **Fee Pool:** comprised of taker fee amounts (multiple methods for fee discounts to be implemented in the future) * **Fee Tranches:** percentage allocations from the fee pool to be distributed amongst the following operations: * Adjusting Peg (alternatively, "repeg") * `k` adjustments * (Capped) funding payments You can read more about Drift's v1 AMM design [here (opens in a new tab)](https://www.notion.so/driftprotocol/Drift-AMM-deep-dive-ff154003aedb4efa83d6e7f4440cd4ab#861bdbceda8a45a38600a0d9d762ee25) . Drift v2 AMM[](https://docs.drift.trade/about-v2/drift-amm#drift-v2-amm) ------------------------------------------------------------------------- Drift’s v2 AMM is still a AMM using a constant product curve but now includes external [Backstop AMM Liquidity (BAL)](https://docs.drift.trade/backstop-amm-liquidity/bal-provider-overview) a concentration factor, and dynamic spread/peg that programmatically update prior to filling trades. The mechanics behind the dynamic spread and peg are: 1. Inventory adjusted spreads 2. Oracle live pricing/volatility ### Inventory Adjusted Spreads[](https://docs.drift.trade/about-v2/drift-amm#inventory-adjusted-spreads) In a typical constant product AMM, the AMM quotes the same price for buys/sells and charges a flat fee. To implicitly utilise a dynamic fee, Drift v2's AMM quotes different prices for buys and sells. The offset from the mid-price is dynamic based on the current inventory. To do so, there will be 3 points tracked on the constant product curve: the bid price and ask price, and a point between the reservation price. ![](https://docs.drift.trade/_next/image?url=%2F_next%2Fstatic%2Fmedia%2FK7PAJRkd_-P-t8v6RQ_nI_drift-amm-bid-ask-spreads.b8fb4828.png&w=3840&q=75) Base long spread and short spread are currently set as: `bid/ask price = reservation price ± base_spread + f(inventory, balance, ...)` The long and short spread can be asymmetric due to changes in the underlying inventory skew and market buy/sell pressure. Ultimately, the ask - bid can never exceed the max spread (percentage calculated using the current valid oracle price). The bid/ask points on the curve are calculated as follows (exact efficient integer math method calculated on contract): `bid_quote_reserve = quote_reserve - (quote_reserve / (100%/short_spread))` `ask_quote_reserve = quote_reserve + (quote_reserve / (100%/long_spread))` The `quote_reserve` is defined as the total AMM reserves of the quote asset. Then using the same k to back out the base\_reserve for the bid/ask curves as well. ### Oracle Live Pricing[](https://docs.drift.trade/about-v2/drift-amm#oracle-live-pricing) The AMM's reservation price gets updated regularly through Drift's live oracle-based pricing. This pricing mechanism updates an asset's mark price towards its oracle price, achieving: * more accurate pricing; and * better entries and exits closer to oracle price. The mark price is updated each time the oracle updates its price and when the contract is interacted with. Oracle Live Pricing Sequence Every time a trader wants to fill against the AMM, the AMM will be updated in the same slot with a valid oracle price (see [Oracles](https://docs.drift.trade/trading/oracles) ). The sequence is: 1. The AMM checks the oracle price 2. The AMM move its peg toward the oracle price 3. The AMM sets its bid/ask spread versus its reservation price 4. The order will fill according to the bid/ask price if the order has lived longer than the minimum duration for AMM fills (10 slots) The overall spread will increase if the AMM is heavily levered or in debt. The oracle price and reservation price are always within this spread. Effective leverage is a function of many market stats, including Inventory P&L and collateral within the fee pool in the terminal state. The reservation (AMM) price is the `quote/base reserves * peg`. [Understanding Drift Protocol](https://docs.drift.trade/about-v2/understanding-drift "Understanding Drift Protocol") [Decentralized Orderbook](https://docs.drift.trade/about-v2/decentralized-orderbook "Decentralized Orderbook") --- # Program Vault Addresses – Drift Protocol 🏎 About Drift v2 Program/Vault Addresses Program / Vault Addresses[](https://docs.drift.trade/about-v2/program-vault-addresses#program--vault-addresses) ---------------------------------------------------------------------------------------------------------------- Below is mainnet instance of Drift Protocol: * Program Address: dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH * Vault Address: JCNCMFXo5M5qwUPg2Utu1u6YWp3MbygxqBsBeXXJfrw [Optimizations](https://docs.drift.trade/about-v2/optimizations "Optimizations") [Phantom](https://docs.drift.trade/getting-started/wallet-setup/phantom-setup " Phantom") --- # Keeper Incentives – Drift Protocol 🏎 About Drift v2 Keeper Incentives Keeper Incentives ================= Keepers **keep** the Drift network healthy. Keeper Rewards[](https://docs.drift.trade/about-v2/keeper-incentives#keeper-rewards) ------------------------------------------------------------------------------------- For matching orders, Keepers receive a portion of the taker fee. For cancelling orders (that can be cancelled see [Advanced Orders FAQ](https://docs.drift.trade/trading/advanced-orders-faq) ), Keepers will receive the `cancel_order_fee` on the state. Liquidation rewards for keepers are different for every market and range from 0.75% to 3% of the amount liquidated. See [Fee schedule (opens in a new tab)](https://analytics.drift.trade/?tab=Fee-Schedule) . Currently, the USDC reward function for keepers (_f\_keeper_) is designed as: fkeeper\=min(0.01∗max(1,torder)1/4,0.1∗fuser)f\_{\\text{keeper}} = \\textit{min}(0.01 \\ast \\textit{max}\\left(1, t\_{\\text{order}}\\right)^ {1/4}, 0.1 \\ast f\_{\\text{user}})fkeeper​\=min(0.01∗max(1,torder​)1/4,0.1∗fuser​) where: tordert\_{\\text{order}}torder​ is seconds since the order was placed fuserf\_{\\text{user}}fuser​ is the taker fee paid by the user who placed the order This reward is subject to evolve to incentivise CLOB-like execution ordering. See [source code (opens in a new tab)](https://github.com/drift-labs/protocol-v1/blob/c748c64fcfa6d7fd5aba72f7021218dd6aaa02f0/programs/clearing_house/src/math/fees.rs#L257) for the on-chain calculation. ![plot of filler rewards (given user fee)](https://docs.drift.trade/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fplot-fillet-rewards.842ac692.png&w=3840&q=75) A Keeper reward multiplier (for taker price improvement) is applied to the keeper's minimum time-based reward component in the function above. Any percent improvement versus the baseline `oracle +/- 10bps`, increases this multiplier. ### Future Work[](https://docs.drift.trade/about-v2/keeper-incentives#future-work) 30d fill volume for keepers is tracked on-chain via `UserStats`, allowing for logic to reward consistent keepers with a larger multiplier on rewards. [Keepers & Decentralized Orderbook FAQ](https://docs.drift.trade/about-v2/keepers-decentralized-orderbook-faq "Keepers & Decentralized Orderbook FAQ") [Matching Engine](https://docs.drift.trade/about-v2/matching-engine "Matching Engine") --- # Revenue Pool – Drift Protocol 🏎 About Drift v2 Revenue Pool Revenue Pool ============ A portion of the fees collected within the protocol (denominated in a particular token: USDC, SOL, etc) go into that spot market's revenue pool. The revenue pool increases from various portions of the protocol: 1. borrow fees 2. spot market exchange fees 3. perpetual market exchange fees 4. liquidations and ultimately goes to fund: 1. insurance vault 2. perpetual market amm (conditionally) Insurance Fund[](https://docs.drift.trade/about-v2/revenue-pool#insurance-fund) -------------------------------------------------------------------------------- Every hour (on the hour), a portion of the revenue pool can be settled to the insurance fund using the permissionless `settle_revenue_to_insurance_fund` instruction: If the insurance fund has users staked, each individual hourly settlement is capped to what would amount to 1000% APR * thus an astronomically large inflow into the revenue pool (relatively to user insurance staked amounts) would result in revenue that slowly reaches the insurance over a longer period of time rather than immediately * this encourages more insurance fund stakers (who require a medium horizon of insurance offering) to join during the high annualised cap inflow Insurance Fund Stakers must adhere to the cooldown period for withdrawals (see [Insurance Fund Staking](https://docs.drift.trade/insurance-fund/insurance-fund-staking) ). Spot Markets[](https://docs.drift.trade/about-v2/revenue-pool#spot-markets) ---------------------------------------------------------------------------- Spot Markets allow for swaps between tokens and interest payments between depositors and borrowers. These token swaps and flow of interest are parameterised to allow fee collection for the revenue pool and thus ultimately insurance. Within the program, its parameterised by the following **in bold**: | Field | Description | | --- | --- | | `total_if_factor` | percentage of the borrow interest reserved for revenue pool | | `user_if_factor` | this proportion of `total_if_factor` is reserved for staked users (the other piece is reserved for the protocol itself) | | `liquidation_if_factor` | the proportion of liability transfer in `liquidate_borrow` that is sent to the revenue pool | Thus the following must be true: `user_if_factor <= total_if_factor`. For example, if the `total_if_factor` is 100%, depositors would receive no interest from borrows. The following instructions interact w/ the insurance fund: * `resolve_borrow_bankruptcy` Perpetual Markets[](https://docs.drift.trade/about-v2/revenue-pool#perpetual-markets) -------------------------------------------------------------------------------------- Perpetual Markets are bootstrapped by the [Drift AMM](https://docs.drift.trade/about-v2/drift-amm) which depending on market-making performance conditions can add and remove funds from the revenue pool. Within the program, its parameterized by the following **in bold**: | Field | Description | | --- | --- | | `max_revenue_withdraw_per_period` | the amm's max revenue pool draw per period(note this doesn't include bankruptcy resolution) | | `revenue_withdraw_since_last_settle` | revenue pool draws on behalf of user pnl since the last settle(note this doesn't include bankruptcy resolution) | | `last_revenue_withdraw_ts` | the last timestamp of a revenue withdraw (track in order to reset the period) | A perpetual market's amm may draw up to `max_revenue_withdraw_per_period` from the revenue pool every period. Additionally, for direct draws from the insurance fund, it parameterized by the following **in bold**: | Field | Description | | --- | --- | | `quote_settled_insurance` | settled funds from the insurance fund since inception | | `quote_max_insurance` | max funds it can settle from insurance fund since inception | | `unrealized_max_imbalance` | max amount of pnl the net users can be owed within a market before:1. draws from insurance are allowed2. initial asset weights for this pnl gets discounted | Unlike spot markets, perp markets are capped by the max draw from insurance via `quote_max_insurance` `quote_settled_insurance` tracks the insurance fund draw amount since inception. Once this threshold is reached or the insurance fund is depleted, the market will then resort to the AMM [Fee Pool](https://docs.drift.trade/trading/fee-pool) . For any remaining losses not covered, the market will perform socialized losses in bankruptcy events. The following instructions interact w/ the insurance fund: * `resolve_perp_pnl_deficit` * `resolve_perp_bankruptcy` notes: `resolve_perp_pnl_deficit` can only be resolved by insurance fund deposits (within the market's constraints), not by social loss with other users [Just-in-Time (JIT) Auctions FAQ](https://docs.drift.trade/about-v2/jit-maker-faq "Just-in-Time (JIT) Auctions FAQ") [Optimizations](https://docs.drift.trade/about-v2/optimizations "Optimizations") --- # Matching Engine – Drift Protocol 🏎 About Drift v2 Matching Engine Matching Engine =============== Drift is a decentralized auction-based trading protocol. Every taker order has the following auction parameters: * **Auction duration:** the number of slots the auction lasts * **Auction start price:** the price the auction begins at * **Auction end price:** the price the auction ends at * **Limit Price:** the price of the order after the completion of the auction * **Max timestamp:** the time the order expires The auction duration, start price, and end price define a linear function that specifies an order’s price over a set of slots. At the end of the auction, the limit price specifies an order’s price. Price parameters can be defined as fixed prices as well as relative oracle offsets to account for the oracle price changing during the duration of the auction. The max timestamp specifies when an order expires. Drift supports market and limit orders. Market orders must have an auction and max timestamp. An auction and max timestamp are optional for a limit order. During a limit order’s auction, it can only take liquidity. At the end of the auction, it is considered “resting” and can also provide liquidity for orders (i.e., it transitions from being a taker to being a taker or maker). If a user only wishes to provide liquidity, they can set their limit order to post-only, in which case it can only be a maker. A taker order can be filled against three sources of liquidity: * **Backstop liquidity:** liquidity provided by the protocol-owned AMM * **Resting liquidity:** limit orders that have been previously placed and are not undergoing an auction * **Just-in-time liquidity:** limit orders placed after the taker order with the specific purpose of only filling the taker order There are three ways a user can have their taker order filled: * **A keeper creates a transaction filling their order with resting liquidity** * **The user creates a transaction filling their order with resting liquidity** * **A maker creates a transaction filling the user’s order with the maker’s JIT liquidity** To place an order, users sign a transaction containing their order params. The transaction is sent to the Solana network and, once it is included in a block, it is propagated to keepers and market makers via RPCs. The keepers and market makers then race to fill user orders with liquidity that satisfies their auction prices. Backstop liquidity is compared against resting and JIT liquidity before each fill. If the backstop liquidity offers a superior price, Drift will fill users against the backstop liquidity prior to filling against the resting or JIT liquidity specified by the keeper or market maker. ![](https://docs.drift.trade/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fkeeper_arch.40dd8f19.png&w=1920&q=75) [Keeper Incentives](https://docs.drift.trade/about-v2/keeper-incentives "Keeper Incentives") [Just-in-Time (JIT) Auctions FAQ](https://docs.drift.trade/about-v2/jit-maker-faq "Just-in-Time (JIT) Auctions FAQ") --- # Phantom Setup – Drift Protocol 👋🏻 Getting Started Wallet Setup Phantom Phantom Setup[](https://docs.drift.trade/getting-started/wallet-setup/phantom-setup#phantom-setup) --------------------------------------------------------------------------------------------------- ### 1\. [Install Phantom wallet (opens in a new tab)](https://phantom.app/) on your preferred browser (Chrome, Brave, Firefox, Edge).[](https://docs.drift.trade/getting-started/wallet-setup/phantom-setup#1-install-phantom-wallet-on-your-preferred-browser-chrome-brave-firefox-edge) ![](https://docs.drift.trade/assets/3Ms0a5cuUqfXG93pIRDkK_image.png) ### 2\. Ensure your Phantom Wallet has SOL and USDC or other assets to trade on Drift[](https://docs.drift.trade/getting-started/wallet-setup/phantom-setup#2-ensure-your-phantom-wallet-has-sol-and-usdc-or-other-assets-to-trade-on-drift) You can deposit SOL to cover trading fees on your Phantom wallet. If you don't have SOL yet, you can purchase SOL on an exchange and withdraw SOL to your Phantom wallet. You can then swap any asset in your wallet for USDC or other assets that are accepted as margin for cross collateral (SOL, BTC and ETH) within the Phantom interface itself, or on [Jupiter (opens in a new tab)](https://jup.ag/swap/SOL-USDC) . Check out [Cross-Collateral Deposits](https://docs.drift.trade/getting-started/cross-collateral-deposits) to see which assets are accepted as deposits on Drift. ![](https://docs.drift.trade/assets/jcnLW71e4_JwiOR7pEIwB_image.png) ### 3\. Connect your Wallet[](https://docs.drift.trade/getting-started/wallet-setup/phantom-setup#3-connect-your-wallet) Navigate to our trading page. On the top right side of the page, select "Connect Wallet." ![](https://docs.drift.trade/assets/9d2fRiDEH7N0kJ4zdeNeO_image.png) ![](https://docs.drift.trade/assets/XMNnV520NZJxMwclE2sVF_image.png) ### 4\. Deposit USDC on Drift[](https://docs.drift.trade/getting-started/wallet-setup/phantom-setup#4-deposit-usdc-on-drift) Click on the "Deposit" button located next to the button you connected your wallet with and choose the amount you want to deposit. You can change which asset you'd like to deposit by choosing your desired asset from the drop-down. ![](https://docs.drift.trade/assets/VAhaqFxb0ZO9Dzz3G4sr9_image.png) ### 5\. Withdraw USDC from Drift[](https://docs.drift.trade/getting-started/wallet-setup/phantom-setup#5-withdraw-usdc-from-drift) If you want to withdraw from Drift, select "Withdraw" inside the same window you used to deposit and choose the amount you want to withdraw. Select the amount you want to withdraw and confirm the transaction. ![](https://docs.drift.trade/assets/5pY_6vDUJ0V1cNv8HBGTi_image.png) Auto-confirm with Phantom Wallet[](https://docs.drift.trade/getting-started/wallet-setup/phantom-setup#auto-confirm-with-phantom-wallet) ----------------------------------------------------------------------------------------------------------------------------------------- With Auto-Confirm, you can now deposit, trade, borrow and execute any transaction on Drift with just one click! Here’s how you can enable it: 1. Navigate to Phantom settings 2. Click “Connected Apps” 3. Select Drift 4. Toggle “Auto-Confirm” to "Active" [Program/Vault Addresses](https://docs.drift.trade/about-v2/program-vault-addresses "Program/Vault Addresses") [MetaMask](https://docs.drift.trade/getting-started/wallet-setup/metamask-setup "MetaMask") --- # Understanding Drift Protocol – Drift Protocol 🏎 About Drift v2 Understanding Drift Protocol Understanding Drift Protocol ============================ At the application level, Drift Protocol is a decentralized exchange that supports low slippage, low fees, and minimal price impact on all trades. Drift offers four primary products: 1. Spot Trading - [What is Spot Margin Trading?](https://docs.drift.trade/trading/spot-margin-trading) 2. Perpetuals Trading - [What are Perpetual Futures?](https://docs.drift.trade/trading/what-are-perpetual-futures) 3. Borrow & Lend - [What is Borrow & Lend?](https://docs.drift.trade/lend-borrow/what-is-lend-borrow) 4. Passive Liquidity Provision - [Backstop AMM Liquidity (BAL)](https://docs.drift.trade/backstop-amm-liquidity/bal-provider-overview) The Problem[](https://docs.drift.trade/about-v2/understanding-drift#the-problem) --------------------------------------------------------------------------------- On-chain exchanges suffer from limitations associated with blockchains—namely, speed and limited computational capacity on-chain. Porting over existing off-chain centralised exchange infrastructure onto the blockchain results in an inefficient use of blockchains and disincentivises market-maker participation with unfavourable conditions. As a result, most on-chain orderbooks suffer from: * slow fills; * high spreads; and * low liquidity. Our Solution[](https://docs.drift.trade/about-v2/understanding-drift#our-solution) ----------------------------------------------------------------------------------- Drift has designed & developed an exchange that is robust, computationally efficient, and incentivises market maker participation, as well as liquidity provision. Trades on Drift are supported by three liquidity mechanisms: 1. Just-in-Time (JIT) Auction Liquidity: provided by market makers prior to each transaction; 2. Limit Orderbook Liquidity: provided by our decentralised orderbook (DLOB) made up of limit orders placed by makers that can be filled by takers; and 3. AMM Liquidity: provided by Drift's AMM if no makers step in to provide liquidity. ### Just-in-Time Liquidity[](https://docs.drift.trade/about-v2/understanding-drift#just-in-time-liquidity) All market trades (spot and perpetual) that are placed on Drift are routed through a short-term auction (default is ~ 5 seconds). During this period, market-makers can bid to fill the order at or better than the auction price, providing '_Just-in-Time Liquidity_' as the fulfilment is provided for the market order submitted. Auctions are run via a Dutch Auction (where the auction price starts at the better price and linearly moves toward a set worse end price) and market makers compete amongst themselves in speed to fulfil user orders. _For a more technical breakdown, check out:_[Matching Engine](https://docs.drift.trade/about-v2/matching-engine) ### Constant Liquidity[](https://docs.drift.trade/about-v2/understanding-drift#constant-liquidity) Drift's virtual AMM (AMM) is the backstop designated liquidity provider for trades on the exchange if: 1. market orders aren't filled by the JIT and 2. resting orders hit a trigger price that can be filled by the AMM. The AMM provides a source of constant liquidity for all traders to **take** from. The AMM is considered constant as liquidity is available based on a constant product formula `(x*y=k)` balancing the reserves. Drift's AMM features an inbuilt bid-ask spread that adjusts based on inventory held by the AMM. Users can also LP into the AMM to further collateralize. This also means that, even without external makers, Drift Protocol can support new markets without dependence on external market makers to bootstrap liquidity (albeit with additional risks on the immediate availability of unsettled PnL). Many prudent measures in the protocol's design are in place (capped exposure, effective market making, revenue pool utilization, insurance fund rules, etc) to mitigate and isolate the risks of a single market. The AMM needs a reliable oracle of the perpetual market's spot reference asset. For instance, Drift's SOL-PERP market would refer to a SOL/USD spot oracle for a spot reference. Drift currently uses [Pyth (opens in a new tab)](https://pyth.network/) for its oracles and can arbitrarily support other sources per market. _For a more technical breakdown, check out:_ [Drift AMM](https://docs.drift.trade/about-v2/drift-amm) ### Limit Orderbook Liquidity[](https://docs.drift.trade/about-v2/understanding-drift#limit-orderbook-liquidity) Drift's decentralised orderbook (DLOB) acts as its third source of liquidity. Limit orders are orders that trigger and execute on a particular condition. For a full breakdown of what limit orders are, visit: [Order Types](https://docs.drift.trade/trading/order-types) ; Limit orders are placed by users on-chain. A network of Keeper Bots ([Keeper Bots](https://docs.drift.trade/about-v2/keepers) ) then sorts the on-chain limit orders into an off-chain orderbook and categorises limit orders from oldest to newest, and largest to smallest. Each Keeper maintains its own view of the orderbook (hence the 'decentralised' aspect) and tracks new orders, AMM availability, and the oracle price. If the trigger condition of a limit order is met, the Keeper will submit the limit order and fill it against the AMM. Keepers will also match taker orders with resting limit orders if the conditions are the same. Keepers are also incentivised to fill the oldest and largest order first. For their work, they are paid a portion of the taker fee to their Drift User Account. The decentralised orderbook acts as a source of 'resting' liquidity as it rests on the orderbook until either a taker takes it, or the requisite market conditions are met and it's filled against the AMM. _For a more technical breakdown, check out:_ [Decentralised Orderbook FAQ](https://docs.drift.trade/about-v2/decentralized-orderbook) . Our core value[](https://docs.drift.trade/about-v2/understanding-drift#our-core-value) --------------------------------------------------------------------------------------- ### Decentralisation[](https://docs.drift.trade/about-v2/understanding-drift#decentralisation) Drift Protocol is a **decentralised** exchange, meaning: * all deposits, withdraws, and trades are executed on-chain and are completely transparent; * trading requires a connection to a self-custodial Solana wallet; and * execution of all trades is facilitated by smart contract technology with no human or third-party input to execute or fill trades. Decentralisation offers many benefits, including: * anonymity; * transparency; * fairness; and * trustlessness. However, decentralisation also means that Drift is susceptible to the same limitations and shortcomings that arise from running on a blockchain, including: * underlying blockchain risk; * transaction fees; * smart contract risk; and * network congestion. [👾 Welcome to Drift Protocol](https://docs.drift.trade/ "👾 Welcome to Drift Protocol") [Drift AMM](https://docs.drift.trade/about-v2/drift-amm "Drift AMM") --- # Introduction – Drift Protocol 👾 Welcome to Drift Protocol Introduction ============ Drift Protocol is a decentralised exchange, open-sourced and built on the [**Solana blockchain** (opens in a new tab)](https://solana.com/) . 📈 Trade[](https://docs.drift.trade/#-trade) --------------------------------------------- Focus on the strategy, and let Drift take care of your position: * [**Perpetual Futures / Swaps**](https://docs.drift.trade/trading/perpetuals-trading) - Trade the hottest perp markets with up to 101x leverage. * [**Spot Trading**](https://docs.drift.trade/trading/spot-margin-trading) - Trade assets with up to 5x leverage. * [**Swap Tokens** (opens in a new tab)](https://app.drift.trade/swap) - Swap any pair with up to 5x leverage. Drift was designed with a goal to be **capital efficient but also protective of your assets.** We achieved that by setting up sophisticated **cross-margined risk engine** - a system of tools with an extensive protection from over-extending risk. For instance: * In the lend/borrow markets, you can also use collateral for perpetual futures and trade more efficiently with spot assets. * Every token you deposit can earn you more through borrowing and also act as a collateral for perpetual swaps. * Borrowers can only borrow if they have more collateral than needed, following multiple safety measures for extra protection. [**Place an order.** (opens in a new tab)](https://app.drift.trade/) 💸 Earn[](https://docs.drift.trade/#-earn) ------------------------------------------- * [**Lend/Borrow**](https://docs.drift.trade/lend-borrow/what-is-lend-borrow) - Earn yield on your deposits through lending. * [**Insurance Fund Staking**](https://docs.drift.trade/insurance-fund/insurance-fund-intro) - Stake your assets into a vault and earn yield from exchange fees. * [**Market Maker Rewards**](https://docs.drift.trade/market-makers/market-maker-participation) - Opt-in only market-making Alpha Program. * [**(Advanced) Backstop AMM Liquidity (BAL)**](https://docs.drift.trade/backstop-amm-liquidity/bal-provider-overview) - Provide liquidity with leverage and earn yield. [**Earn yield.** (opens in a new tab)](https://app.drift.trade/) 🤖 Build[](https://docs.drift.trade/#-build) --------------------------------------------- * [**API Documentation** (opens in a new tab)](https://drift-labs.github.io/v2-teacher/#terms-of-use) - Interact with the protocol programatically. * [**SDKs**](https://docs.drift.trade/sdk-documentation) - Language bindings in [**Typescript** (opens in a new tab)](https://github.com/drift-labs/protocol-v2/tree/master/sdk) and [**Python** (opens in a new tab)](https://github.com/drift-labs/driftpy) . * [**Tutorials**](https://docs.drift.trade/tutorial-bots/keeper-bots) - Build a [**Keeper bot**](https://docs.drift.trade/tutorial-bots/keeper-bots) or [**JIT Trading bot**](https://docs.drift.trade/tutorial-bots/trading-bots/tutorial-jit-trading-bot) . * [**Drift Gateway** (opens in a new tab)](https://github.com/drift-labs/gateway) - Self hosted API gateway to easily interact with Drift V2 Protocol Drift Protocol is [**open-source** (opens in a new tab)](https://github.com/drift-labs/protocol-v2) and contributions are welcome. Our support is available at all times on [**Discord** (opens in a new tab)](https://discord.com/invite/95kByNnDy5) . [**Build a bot.**](https://docs.drift.trade/tutorial-bots/keeper-bots) 🛡 Contracts are audited by Trail of Bits, read [**report** (opens in a new tab)](https://www.drift.trade/audit) . [Understanding Drift Protocol](https://docs.drift.trade/about-v2/understanding-drift "Understanding Drift Protocol") --- # Just-in-Time (JIT) Maker FAQ – Drift Protocol 🏎 About Drift v2 Just-in-Time (JIT) Auctions FAQ Just-in-Time (JIT) Maker FAQ ============================ ### What are liquidity sources Drift use?[](https://docs.drift.trade/about-v2/jit-maker-faq#what-are-liquidity-sources-drift-use) * JIT makers: Encapsulates filler/maker order into one, but requires high-frequency trading infrastructure. * Resting orderbook maker: You can define as absolute price or from oracle offset. Orders can be placed and canceled dynamically, or set once and left in the orderbook. The work of order management is then deferred to the user placing the order. * AMM(LP vs. protocol-owned split). Increased assurance of backstop indiscriminate liquidity per market, ultimately covered by the revenue pool/insurance in cases of failure. ### JIT Links[](https://docs.drift.trade/about-v2/jit-maker-faq#jit-links) * [Tutorial on how to run JIT trading bot](https://docs.drift.trade/about-v2/pages/tutorial-bots/trading-bots/tutorial-jit-trading-bot) * [Drift Developer Docs (opens in a new tab)](https://drift-labs.github.io/v2-teacher/#orderbook-trades-dlob-server) * [Dune Dashboard (opens in a new tab)](https://dune.com/bigz/drift-jit) * [Typescript (opens in a new tab)](https://github.com/drift-labs/jit-proxy/blob/master/ts/sdk/Readme.md) * [Python (opens in a new tab)](https://github.com/drift-labs/keepyrs/) JIT Proxy Address: J1TnP8zvVxbtF5KFp5xRmWuvG9McnhzmBd9XGfCyuxFP Benefits[](https://docs.drift.trade/about-v2/jit-maker-faq#benefits) --------------------------------------------------------------------- ### What are the benefits for Takers?[](https://docs.drift.trade/about-v2/jit-maker-faq#what-are-the-benefits-for-takers) For Takers, the main benefit of the JIT auction is that liquidity can be much deeper compared to an AMM. Liquidity on the JIT isn't constrained by how much virtual liquidity is available for a user; it is determined by the liquidity provided by external Makers in each auction. Users have the opportunity for much better price improvement compared to a liquidity-constrained AMM. ### What are the benefits for Makers?[](https://docs.drift.trade/about-v2/jit-maker-faq#what-are-the-benefits-for-makers) For Makers, the JIT auction provides an easy way to access on-chain taker flow for market making operations. Unlike an on-chain CLOB where the set-up cost, ongoing infrastructural costs, and the possibility for latency arbitrage are high, market making on the JIT is a simple, competitive auction fill mechanism, reducing the barrier for entry for making on-chain. Makers will also earn a rebate for filling taker orders. For Takers[](https://docs.drift.trade/about-v2/jit-maker-faq#for-takers) ------------------------------------------------------------------------- ### How many auctions can there be at once?[](https://docs.drift.trade/about-v2/jit-maker-faq#how-many-auctions-can-there-be-at-once) The auction mechanism is highly parallelized for maximum exchange throughput. * Takers can initiate multiple auctions, up to the number of order slots (currently 32). * Makers can participate in as many auctions as they like (since their order is completed atomically). * Additionally, on a per-exchange level, there is no limit to the total amount of ongoing auctions happening at once. ### Can auctions be partially filled?[](https://docs.drift.trade/about-v2/jit-maker-faq#can-auctions-be-partially-filled) Yes, auctions can be partially filled up to a user's slippage tolerance. There are no Fill-or-Kill (FOK) auctions. ### Can auctions be cancelled once initiated?[](https://docs.drift.trade/about-v2/jit-maker-faq#can-auctions-be-cancelled-once-initiated) Yes, users can cancel the unfilled portion of their order in the auction once they've been initiated. Users will need to pay a network fee in SOL to cancel their ongoing auction, as well as a nominal fee to keepers of $0.01 USDC. ### Can Makers pull out of an auction once they have filled on the auction?[](https://docs.drift.trade/about-v2/jit-maker-faq#can-makers-pull-out-of-an-auction-once-they-have-filled-on-the-auction) Once an order is partially filled, Makers are unable able to pull out of an auction. Fills are confirmed when the Maker submits a fill on a first-come-first-serve basis. ### Is there a limit to how many auctions a Maker can participate in at once?[](https://docs.drift.trade/about-v2/jit-maker-faq#is-there-a-limit-to-how-many-auctions-a-maker-can-participate-in-at-once) No, there is no limit. Makers can enter multiple auctions at once to cancel out their exposure. ### Is there a way for users to enter market orders without entering the auction?[](https://docs.drift.trade/about-v2/jit-maker-faq#is-there-a-way-for-users-to-enter-market-orders-without-entering-the-auction) Not at the moment. Market orders all go through the JIT auction. Users can opt to place a limit order instead if the user wishes to be matched with another order via the DLOB. ### Can limit orders trigger an auction?[](https://docs.drift.trade/about-v2/jit-maker-faq#can-limit-orders-trigger-an-auction) Yes, limit orders can have an auction. To avoid having an auction, users can set the post-only flag. ### Are there individual JIT pools for each Taker order placed?[](https://docs.drift.trade/about-v2/jit-maker-faq#are-there-individual-jit-pools-for-each-taker-order-placed) Yes. Each user will have a different account and each taker order placed will go through its own auction. ### Will I know the exact price I'll be filled at?[](https://docs.drift.trade/about-v2/jit-maker-faq#will-i-know-the-exact-price-ill-be-filled-at) Exclusive of slippage and fees, the UI will display the price that the Taker will be filled at if they were to be filled against the AMM. This is the worst possible price the Taker can receive. Any Maker that steps in via the JIT auction can only provide the Taker with a better price. * * * For Makers[](https://docs.drift.trade/about-v2/jit-maker-faq#for-makers) ------------------------------------------------------------------------- ### How do I participate as a Maker in the auction?[](https://docs.drift.trade/about-v2/jit-maker-faq#how-do-i-participate-as-a-maker-in-the-auction) You can read docs here ([Matching Engine](https://docs.drift.trade/about-v2/matching-engine) ) as well as read through an example trading bot (). ### Is the same JIT auction mechanism used for liquidations as well?[](https://docs.drift.trade/about-v2/jit-maker-faq#is-the-same-jit-auction-mechanism-used-for-liquidations-as-well) No, liquidations do not use autions. Liquidators either take over user positions directly or fill liquidated users against resting liquidity. ### Are there example maker bots?[](https://docs.drift.trade/about-v2/jit-maker-faq#are-there-example-maker-bots) Yes. We've developed an open-source maker bot that can be accessed [here](https://docs.drift.trade/tutorial-bots/trading-bots/tutorial-jit-trading-bot) . ### How will Makers be notified of JIT auctions?[](https://docs.drift.trade/about-v2/jit-maker-faq#how-will-makers-be-notified-of-jit-auctions) We built an event emitter on Solana. Makers can listen to the event emitter for whenever there's a taker order. Makers can then bid to fill the order. ### Will I see what my maker bid is relative to all the other maker bids?[](https://docs.drift.trade/about-v2/jit-maker-faq#will-i-see-what-my-maker-bid-is-relative-to-all-the-other-maker-bids) Yes. ### Does the JIT auction happen in a set of rounds?[](https://docs.drift.trade/about-v2/jit-maker-faq#does-the-jit-auction-happen-in-a-set-of-rounds) Each new Taker order commences a new dutch auction. Dutch auctions are on a first-come-first-serve basis. ### Can I fill a subset of one order?[](https://docs.drift.trade/about-v2/jit-maker-faq#can-i-fill-a-subset-of-one-order) Yes. Makers can fill a subset of Taker orders by specifying the base asset amount they wish to fill. ### How does the DLOB work in conjunction with JIT liquidity?[](https://docs.drift.trade/about-v2/jit-maker-faq#how-does-the-dlob-work-in-conjunction-with-jit-liquidity) DLOB liquidity and JIT liquidity aren't mutually exclusive. The DLOB setup is designed with two separate actors: fillers and makers. Makers post orders and fillers will match orders. JIT mechanism enables the Maker to be their own filler. The Maker will submit the match with someone going through an auction (e.g. user who submitted a market order).[](https://docs.drift.trade/about-v2/jit-maker-faq#jit-mechanism-enables-the-maker-to-be-their-own-filler-the-maker-will-submit-the-match-with-someone-going-through-an-auction-eg-user-who-submitted-a-market-order) --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### Do JIT makers use the DLOB?[](https://docs.drift.trade/about-v2/jit-maker-faq#do-jit-makers-use-the-dlob) When filling a taker order with JIT liquidity, JIT makers do not use the DLOB. They place, fill and cancel an order atomically. ### I got "TakerOrderNotFound" or "AskNotCrossed" errors. What do they mean?[](https://docs.drift.trade/about-v2/jit-maker-faq#i-got-takerordernotfound-or-asknotcrossed-errors-what-do-they-mean) * **'TakerOrderNotFound'**: the auction order you tried to take was either already filled by another user or removed due to slowness in your request. * **'AskNotCrossed'**: the auction order's price doesn't reach your minimum selling price specified in the JIT parameters. It's common practice to simulate transactions before submitting them, but this can carry a higher risk of being too slow to compete in real-time situations. ### Why do some transactions appear on Drift but not on-chain?[](https://docs.drift.trade/about-v2/jit-maker-faq#why-do-some-transactions-appear-on-drift-but-not-on-chain) This might be a temporary display issue related to Solana forks. Transactions shown on Drift might be unconfirmed or failed due to these forks, even though they appear successful initially. Refreshing the page usually resolves the issue. ### Does Drift have stats on market orders? Is there any option to track the history of any specific JIT auction?[](https://docs.drift.trade/about-v2/jit-maker-faq#does-drift-have-stats-on-market-orders-is-there-any-option-to-track-the-history-of-any-specific-jit-auction) Yes, you can access data on hourly, daily usage, and placeAndMake by market here: [Dune Dashboard (opens in a new tab)](https://dune.com/bigz/drift-jit) . ### I'm not getting any orders filled. What can I do to get more fills?[](https://docs.drift.trade/about-v2/jit-maker-faq#im-not-getting-any-orders-filled-what-can-i-do-to-get-more-fills) The solution is two-fold: * Auctions need to be properly configured considering the current JIT supply. This is an ongoing challenge, as calibration can be difficult. Auctions that are too passive or slow can be frustrating for users. Fortunately, end users can configure some auction parameters within their UI settings under "Trader Profile." * JITs need the best possible "sniping" capabilities to ensure transactions land in the desired time slot. This makes RPC infrastructure an essential factor. ### I saw an auction message with a negative "slots\_left" value after the supposed duration. Is this a bug?[](https://docs.drift.trade/about-v2/jit-maker-faq#i-saw-an-auction-message-with-a-negative-slots_left-value-after-the-supposed-duration-is-this-a-bug) No, this indicates a limit order auction that has concluded. Limit order auctions have a predefined duration, and the negative \`slots\_left value signifies the auction has surpassed its intended timeframe. ### I'm encountering errors that say "cannot read .data and .DataAndSlot" when I try to run my bot. How can I fix this?[](https://docs.drift.trade/about-v2/jit-maker-faq#im-encountering-errors-that-say-cannot-read-data-and-dataandslot-when-i-try-to-run-my-bot-how-can-i-fix-this) These errors (cannot read .data or .dataAndSlot) typically occur when the free RPC keys run out of credits or reach their limits. This happens because maker/keeper bot functions require a lot of RPC calls. To address this, consider using a paid RPC service or setting up a custom node. * * * [Matching Engine](https://docs.drift.trade/about-v2/matching-engine "Matching Engine") [Revenue Pool](https://docs.drift.trade/about-v2/revenue-pool "Revenue Pool") --- # Prelaunch Market – Drift Protocol 📈 Trading Prelaunch Markets Prelaunch Market ================ Prelaunch Markets are custom markets that allow users to book trade before reliable external oracle is available. Instead of relying on an external oracle for liquidations, funding, and margin calculation, they utilize a [custom oracle source](https://docs.drift.trade/trading/market-specs#prelaunch) that current mark TWAP (with window = the funding period). In order to isolate risk from other markets, all Prelaunch Markets currently have an [Highly Speculative contract tier](https://docs.drift.trade/trading/market-specs#highly-speculative) which implies: * no external insurance fund (all insurance comes from fees collected in market) To avoid excessive manipulation, the market is configured with a custom max price and conservative open interest limits. Ultimately, once a reliable external oracle is available, the Prelaunch Market oracle source can be switched over. Prelaunch markets typically have the following configuration: * Oracle source: [Prelaunch](https://docs.drift.trade/trading/market-specs#prelaunch) * Contract tier: [Highly Speculative](https://docs.drift.trade/trading/market-specs#highly-speculative) [Market Specs](https://docs.drift.trade/trading/market-specs "Market Specs") [Perpetuals Trading](https://docs.drift.trade/trading/perpetuals-trading "Perpetuals Trading") --- # How to trade Perpetual Swaps? – Drift Protocol 📈 Trading Perpetuals Trading How to trade Perpetual Swaps? ============================= Choosing Markets[](https://docs.drift.trade/trading/perpetuals-trading#choosing-markets) ----------------------------------------------------------------------------------------- Select the market you would like to trade by clicking `Trade` followed by `Perpetuals` and choose your desired market. ![](https://docs.drift.trade/assets/2nJN8GJEzu7Jk0xzK49CM_screenshot-2023-08-11-at-114725.png) ![](https://docs.drift.trade/assets/w7WFaS0-c9hZGlO6qJI-c_screenshot-2023-08-11-at-113644.png) Select Long (Buy) or Short (Sell) from the top of the trading form and then select your order type. ![](https://docs.drift.trade/assets/EkKqbHy0IVwyVgHpIsPLW_screenshot-2023-08-11-at-113800.png) Drift offers Market and Limit Orders that you can use to manage risk. If you are a beginner and just want to buy the perpetual contract at its current price then go with a Market Order. To read more on Market Orders, you can read about it on [Order Types](https://docs.drift.trade/trading/order-types) . ![](https://docs.drift.trade/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fi1GlHgcBaJMWNeK3cyZMS_screenshot-2023-08-11-at-114239.4660c0df.png&w=640&q=75) Selecting Position Size and Leverage[](https://docs.drift.trade/trading/perpetuals-trading#selecting-position-size-and-leverage) --------------------------------------------------------------------------------------------------------------------------------- Enter the amount of the underlying asset you want for your position. You can do this in three different ways: * Using text input on the left, you can enter the amount of the underlying asset you would like. * Using the text input on the right, you can enter how much USDC collateral you want to use. * Or, you can use the leverage slider or the buttons below it to change the size of your position. The slider will automatically show how much leverage you are using. You can also set your maximum allowed slippage for your position. ![](https://docs.drift.trade/assets/oVGN1AXZXFr-YJfJUXwVB_screenshot-2023-08-11-at-114406.png) Opening a Position[](https://docs.drift.trade/trading/perpetuals-trading#opening-a-position) --------------------------------------------------------------------------------------------- When you're ready to open the position, click the button at the bottom of the Trade form. A confirmation modal will appear so you can review the details of your trade and make sure all the details are correct before you continue. Finally, you will be asked to sign the transaction with your connected wallet. ![](https://docs.drift.trade/assets/nXvS7rV7f-Nsca2lJTW5M_screenshot-2023-08-11-at-114513.png) Adjusting an Open Position[](https://docs.drift.trade/trading/perpetuals-trading#adjusting-an-open-position) ------------------------------------------------------------------------------------------------------------- If you have an open position, you can make adjustments by either buying or selling the same asset. To adjust your position follow the same steps outlined above for the relevant asset. Changes in the leverage you use will also change your liquidation price. Closing Positions[](https://docs.drift.trade/trading/perpetuals-trading#closing-positions) ------------------------------------------------------------------------------------------- Once you are done with a trade, you can close out of that position. Go to your positions under the "Positions" tab and click "Close" to realise your P&L. Be sure to sign the transaction via your connected wallet. ![Positions able](https://docs.drift.trade/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fw8fFq1mLC3VeMXnnQp0jC_image.b61426ee.png&w=3840&q=75) Your Balances and Total Collateral should reflect this if you have no Unrealised P&L left. High Leverage Mode (Beta)[](https://docs.drift.trade/trading/perpetuals-trading#high-leverage-mode-beta) --------------------------------------------------------------------------------------------------------- Users have the option to opt in to High Leverage Mode (Beta) through the Drift UI, to access increased perp leverage on the SOL/BTC/ETH markets. There are limited spots available for High Leverage Mode. Note that High Leverage mode comes with [increased fees (opens in a new tab)](https://docs.drift.trade/trading/trading-fees) . Also note that to ensure the limited spots are utilized by active traders, users can be permissionlessly removed from High Leverage Mode as long as they are above their initial margin requirement. [Prelaunch Markets](https://docs.drift.trade/trading/prelaunch-markets "Prelaunch Markets") [What are Perpetual Futures?](https://docs.drift.trade/trading/what-are-perpetual-futures "What are Perpetual Futures?") --- # What are Perpetual Futures – Drift Protocol 📈 Trading What are Perpetual Futures? What are Perpetual Futures ========================== _The terms 'Perpetual Swaps' and 'Perpetual Futures' are interchangeable. They refer to the same product._ What are Perpetual Futures?[](https://docs.drift.trade/trading/what-are-perpetual-futures#what-are-perpetual-futures) ---------------------------------------------------------------------------------------------------------------------- Perpetual futures are a type of derivative instrument. The value of a perpetual futures position comes from the price of its underlying index or asset (usually a spot trading market). Perpetual futures are the most liquid derivative instrument in decentralised finance and it accounts for more volume than their spot market counterparts. Why use Perpetual Futures?[](https://docs.drift.trade/trading/what-are-perpetual-futures#why-use-perpetual-futures) -------------------------------------------------------------------------------------------------------------------- Perpetual futures can be used for three main purposes: 1. **Hedging** - insuring against uncertain price movements or asset exposure. You can easily long or short perpetual futures. 2. **Speculating** - speculating on particular assets or markets, including with leverage. 3. **Access** - liquid access to markets and assets that would otherwise be more difficult to trade (e.g. commodities and trading indexes). ### Hedging[](https://docs.drift.trade/trading/what-are-perpetual-futures#hedging) Perpetual futures can be used to hedge your exposure to particular assets and insure against market volatility. ⬇️ **Example 1:** You bought SOL at $55 and it now sits at $80. You believe SOL's fair value to be $120 and you don't want to sell just yet. But at the same time, you think that there'll be a short-term pullback in price and want to lock in some profits in the meantime. What can you do? You can take a short position at $80 using a SOL-PERP contract to hedge against the spot SOL you hold. If the pullback happens and SOL drops to $60, then your SOL-PERP position will be in profit and you would have locked in your profit from when SOL was at $80 dollars without having to sell your SOL. This puts you in a comfortable position whilst waiting for your SOL target of $120. ### Speculating[](https://docs.drift.trade/trading/what-are-perpetual-futures#speculating) Perpetual futures lets you speculate on whether the price of an asset will go up or down. This is accomplished via longing and shorting perpetual futures. **Longing & Shorting** If you believe that the price of an asset will decrease, you can short it using perpetual futures contracts — and when you believe that the price of an asset will increase, you can long it using perpetual futures contracts. * Shorting means you are speculating on the price of the asset going down. * Longing means you are speculating on the price of the asset going up. ⬇️ **Example 1:** The current price of SOL is at $100 and you believe it's overvalued. What can you do? You can take a short position using SOL-PERP to bet against the price of SOL. This means you will make money if the price of SOL goes down and you will lose money if the price of SOL goes up. If the price of SOL decreases to $80 and you shorted it at $100, then you will have made money and will be in profit. ⬇️ **Example 2:** The current price of SOL is $100 and you believe it's undervalued. What can you do? You can take a long position using SOL-PERP to bet on the price of SOL. This means you will make money if the price of SOL goes up and you will lose money if the price of SOL goes down. If the price of SOL increases to $120 and you longed it at $100, then you will have made money and will be in profit. ### Leverage[](https://docs.drift.trade/trading/what-are-perpetual-futures#leverage) Trading perpetual futures contracts also gives you access to leverage. Leverage allows you to increase the exposure you have to a particular asset with the same amount of collateral. This increases your exposure to both the upside and the downside of your position. ⬇️ **Example 1:** The current price of SOL is $100 and you believe it's undervalued. You have $1,000, but think this is not enough. You have high conviction and want more exposure. What can you do? You can take a long position using SOL-PERP to be for the price of SOL to go up. However, you can also use 10x leverage on your $1,000 collateral - bringing your total collateral size to $10,000. You now have a $10,000 long position on SOL-PERP. This means that if the price of SOL goes up by 1%, your position will be in profit by 10%. This also means that if the price of SOL goes down by 1%, your position will be down by 10%. If however, the price of SOL goes down by 10%, this means your underlying position will go down by 100%, and you will be liquidated. For more information on liquidations visit [Liquidations](https://docs.drift.trade/liquidations/liquidations) . [Perpetuals Trading](https://docs.drift.trade/trading/perpetuals-trading "Perpetuals Trading") [Funding Rates](https://docs.drift.trade/trading/funding-rates "Funding Rates") --- # Funding Rates – Drift Protocol 📈 Trading Funding Rates Funding Rates ============= Perpetuals futures have no expiry date, final settlement, or delivery. As such, funding rate payments are used as the incentive mechanism to bring the perpetual futures' mark price in line with the oracle price. (For instance, a user with a long position in a market whose mark price is, on average, below the oracle price will receive a payoff proportional to their position size). | Field | Description | | --- | --- | | Funding Rate % Calc | 1/24 \* (market\_twap - oracle\_twap)/oracle\_twap | | TWAP Parameters | EMA with span = 1 hour | | Mark TWAP Calc | (bid TWAP + ask TWAP) / 2 | | Frequency | End of Hour\* (9:00 AM, 10:00 AM, ...) | Note: Funding rate hourly magnitudes are clamped according to the market's Contract Tier (B or greater: 0.125%, C: 0.208%, lower than C: 0.4167%) and can be delayed at large divergences (see [Oracles](https://docs.drift.trade/trading/oracles) ). Individual Market TWAP updates utilize the side of the book for trade executions, Bid and Ask TWAPs in the market are calculated and/or estimated on every trade. ### Unrealised -> Realised Funding[](https://docs.drift.trade/trading/funding-rates#unrealised---realised-funding) Funding rates are updated _lazily_ every hour\*. Any time a user opens or closes a position, the exchange tries to update the funding rate. The funding rate will still be updated if enough time has passed and no position has been opened or closed. The update will reflect the premium or discount between the AMM’s mark price and the oracle’s price TWAP over the previous hour. The cumulative funding rate is checked against user positions in case the off-chain funding rate bot does not trigger on the hour. This will show up as "Unrealised P&L" until your next user action within the market (such as a trade, deposit, withdraw etc.), see also [P&L](https://docs.drift.trade/profit-loss/profit-loss-intro) . \* _if no market trades and/or funding update calls occur within the first ~20 minutes of the hour, the next funding update will be delayed an additional hour._ Funding payments may not pay out for markets that trade infrequently. ### Capped Symmetric Funding[](https://docs.drift.trade/trading/funding-rates#capped-symmetric-funding) Drift Protocol aims to provide a symmetric funding rate to both sides of the market. When there is a long-short imbalance within the AMM, the protocol's market-specific Rebate Pool can be used to pay (or receive) the cost delta between the longs and the shorts. If the pool is empty or does not have enough to provide for funding (2/3 of the Rebate Pool balance available at each funding interval), then the receipts for funding will be capped to the available amount. See [Rebates](https://docs.drift.trade/market-makers/maker-rebate-fees) for funding pool sizes where the funding paid from the Rebate Pool will be capped. This ensures that the risk is spread in the system and the Insurance Fund isn't drained by funding rates. Over the hour, the amount available in the Rebate Pool will increase from fees as trades occur, so any existing predicted capped rate should move closer to being balanced. ⬇️ **Example:** For SOL-PERP you can check the recent history to get a better idea of what shorts will receive. ![example data](https://docs.drift.trade/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Ffunding_sol.5ecf08a9.png&w=3840&q=75) ### Oracle Resilience[](https://docs.drift.trade/trading/funding-rates#oracle-resilience) Drift's on-chain calculation of a market's oracle TWAP is updated only on trades which incorporates the oracle's confidence interval and a few interpolations to provide the most accurate and resilient value. Read more about protective checks in [Oracles](https://docs.drift.trade/trading/oracles) . ### APR calculation[](https://docs.drift.trade/trading/funding-rates#apr-calculation) Funding rates can be showcased in annual terms for easier comparison. **APR (annual percentage rate)** is calculated `rate x 24 x 365.25` **APY** would be: `(1 + rate) ^ (24 x 365.25) - 1` 💡 One can approximately track **APY** by allocating funding receipts back into the position (excluding fees/rebates). [What are Perpetual Futures?](https://docs.drift.trade/trading/what-are-perpetual-futures "What are Perpetual Futures?") [What is Spot Margin Trading?](https://docs.drift.trade/trading/spot-margin-trading "What is Spot Margin Trading?") --- # What is Spot Margin Trading? – Drift Protocol 📈 Trading What is Spot Margin Trading? What is Spot Margin Trading? ============================ Spot Trading is the direct purchase or sale of an asset. The delivery of the assets is immediate and the transaction settles on-chain. Once the spot trade has been confirmed, the settlement will be instantaneous, and you will be able to see the increase or decrease in the asset immediately in your account balances. Spot trading on Drift v2 uses liquidity from OpenBook DEX as well as our own DLOB. By default, margin trading is not enabled. Learn how to enable it in the next section. 1\. Select the SOL / USDC market in the top bar or the market's dropdown menu ![Hover over a market in the top bar](https://docs.drift.trade/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fz3zW45nt1iU64WvO7O5ZH_screenshot-2023-01-25-at-41736-pm.da633eb4.png&w=750&q=75) 2\. Select your direction (e.g. Buy or Sell) and order type (e.g. Market, Limit) 3. Input the asset amount you'd like to trade or the notional value ![Spot trading form](https://docs.drift.trade/_next/image?url=%2F_next%2Fstatic%2Fmedia%2F26S8LnOdiTA8XLW7Wyfso_screenshot-2023-01-26-at-10913-pm.37993c8b.png&w=828&q=75) 5\. Once you've confirmed your order and it has been filled, your Balances tab will update to reflect your balance changes ![](https://docs.drift.trade/_next/image?url=%2F_next%2Fstatic%2Fmedia%2FBxlg-O6wA5YszE4HVwc_O_screenshot-2023-01-26-at-11025-pm.55c3ebfa.png&w=3840&q=75) Enable Spot Margin Trading[](https://docs.drift.trade/trading/spot-margin-trading#enable-spot-margin-trading) -------------------------------------------------------------------------------------------------------------- Margin needs to be enabled per subaccount. Here's how you can enable margin: Margin trading allows you to leverage your assets as collateral to borrow funds for the trade. The leverage a trader can take in each spot market is determined by the protocol's risk engine. 1. Open Settings 2. Go to Margin Trading in the left navigation 3. Click the toggle to enable it for the subaccount you want 4. Sign the wallet transaction to confirm ![](https://docs.drift.trade/assets/KJFGX4AoQAP3FvuC7jqMn_image.png) Once margin is enabled, you should see the leverage bar appear in the trade form. ⬇️ **Spot margin trading example:** 1. Select the SOL / USDC spot market 2. Select the BUY side in the trade form and your order type 3. Enter the amount you'd like to purchase or use the leverage slider 4. Click "BUY SOL" 5. Once the order is filled, your balances tab will update with the asset amounts you've purchased and the amount you've borrowed (if applicable) ![Spot margin trade form](https://docs.drift.trade/_next/image?url=%2F_next%2Fstatic%2Fmedia%2FzS5jHR786XcbWrsJW4sqh_screenshot-2023-01-26-at-122019-pm.be886d41.png&w=1080&q=75) [Funding Rates](https://docs.drift.trade/trading/funding-rates "Funding Rates") [Spot FAQ](https://docs.drift.trade/trading/spot-faq "Spot FAQ") --- # Spot FAQ – Drift Protocol 📈 Trading Spot FAQ Spot FAQ ======== ### Why is Drift's spot market better for takers (versus alternatives)?[](https://docs.drift.trade/trading/spot-faq#why-is-drifts-spot-market-better-for-takers-versus-alternatives) Takers enter a JIT auction, which can offer price improvement, and otherwise can fill via an external program. (e.g. Serum). Takers can also utilise special order types such as oracle-offset limit orders, which appropriately can cap fills using slippage tolerance versus the oracle provider's fair value. This allows ordinary takers on a UI to control swapping at the fairest price, even without access to advanced infrastructure / bots. ### Better for makers (versus alternatives)?[](https://docs.drift.trade/trading/spot-faq#better-for-makers-versus-alternatives) Market makers can provide liquidity to an ongoing JIT auction, removing latency-based adverse selection. Additionally, as an active market maker, all resting orders earn interest within the protocol's borrow / lend. * For example: on a USDT-USDC spot market one can offer deep liquidity without compromising on lending interest [What is Spot Margin Trading?](https://docs.drift.trade/trading/spot-margin-trading "What is Spot Margin Trading?") [Margin](https://docs.drift.trade/trading/margin "Margin") --- # Order Types – Drift Protocol 📈 Trading Order Types Order Types =========== Drift supports the following order types: * market orders; * limit orders; and * advanced conditional orders. Market Orders[](https://docs.drift.trade/trading/order-types#market-orders) ---------------------------------------------------------------------------- A **Market Order** is an order to buy or sell an asset immediately at the current Market Price. Users can set a maximum **slippage tolerance**. A slippage tolerance sets an upper bound for the price that the order can be filled at, which is effectively a limit price versus the current market price. For instance, if the mark price of SOL-PERP is $100.00 and a user goes long, a user can set a maximum slippage tolerance of 0.1%. As such, the worst price that a user can fill at is $100.10. The order will fail if the quoted price exceeds the limit price (with slippage tolerance) for makers. Market Orders will trigger a Just-In-Time auction, where market makers will be able to participate in a 5-second Dutch auction to fill the user's orders. As the 5-second JIT auction finishes, the user's orders will be completed if the price is within their slippage tolerance limit order. If no market maker steps in during the JIT Auction, the remaining order will be filled against Drift's AMM. Executing a Market Order does not mean the order will execute at exactly the price displayed as the mark price of an asset may change before the JIT Auction is complete. ⚠️ The fee paid depends on whether the order is a taker order or a maker order. Maker orders are Limit orders with a 'Post' flag. See [Trading Fees](https://docs.drift.trade/trading/trading-fees) and [Advanced Orders FAQ](https://docs.drift.trade/trading/advanced-orders-faq) for more information. **Limit Orders**[](https://docs.drift.trade/trading/order-types#limit-orders) ------------------------------------------------------------------------------ The Drift DEX supports a number of queued order types. These orders take against the AMM and are executed by a decentralised network of keepers, see [Decentralised Orderbook FAQ](https://docs.drift.trade/about-v2/keepers-decentralized-orderbook-faq) , once certain conditions are met (i.e. the mark price crosses the specified trigger/limit price). These orders are executed **'best effort'** by the network with special economic incentives designed to mimic the typical execution order seen in a Centralised Limit Order Book (CLOB). A Limit Order is an order to buy or sell a given asset at a specified price. Users can specify a Limit Price they wish to be filled at. If or when the mark price of an asset moves to cross the Limit Price, the order will partially fill up to this Limit Price every time a keeper executes it. For taker orders, a user's resulting Entry Price is guaranteed to be equal to or better than the Limit Price specified. If the "Post" order flag is set, then the order will be filled at the specified limit price with a variable rebate. This variable rebate comes from the liquidity surplus from the taker fills that cross after accounting for the filler reward (which is capped at 5bps). [Margin](https://docs.drift.trade/trading/margin "Margin") [All Order Types](https://docs.drift.trade/trading/all-order-types "All Order Types") --- # All Order Types – Drift Protocol 📈 Trading All Order Types All Order Types =============== Advanced Orders[](https://docs.drift.trade/trading/all-order-types#advanced-orders) ------------------------------------------------------------------------------------ ### Stop Market[](https://docs.drift.trade/trading/all-order-types#stop-market) A Stop Market Order is an order to close the position of a given asset if its Oracle Price reaches the specified Trigger Price. If this happens, the position is closed at Market Price. Users can specify a Trigger Price, and once (or if) the of the asset reaches the specified Trigger Price and a keeper executes it, a Market Order to sell the asset will be executed. ### Stop Limit[](https://docs.drift.trade/trading/all-order-types#stop-limit) A Stop Limit Order will only execute where the Oracle Price of a given asset reaches the Trigger Price. If this happens, a Limit Order at the specified Limit Price will be placed. Once triggered, the resulting Limit Order may be immediately filled or may rest until the specified Limit Price is reached and executed by a decentralised keeper. Users can specify a Trigger Price and a Limit Price, and once (or if) the mark price of the asset reaches the specified Trigger Price and a keeper executes it, a Limit Order will be placed at the specified Limit Price. Stop Limit Orders also serve as a maximum slippage tolerance for the Stop Order. | Current Position | Order Type | Trade Direction | Trigger Condition | Reduce Only | | --- | --- | --- | --- | --- | | Long | Stop (Market If Touch) | Buy | Below | False | | **Long** | **Stop** | **Sell** | **Below** | **True/False** | | **Short** | **Stop** | **Buy** | **Above** | **True/False** | | Short | Stop (Market If Touch) | Sell | Above | False | ### Take Profit Market[](https://docs.drift.trade/trading/all-order-types#take-profit-market) A Take Profit Order is an order to close the position of a given asset if its Oracle Price reaches the specified Trigger Price. If this happens, the position is closed at Market Price. Users can specify a Trigger Price, and once (or if) the oracle price of the asset reaches the specified Trigger Price and a keeper executes it, a Market Order to sell the asset will be executed. ### Take Profit Limit[](https://docs.drift.trade/trading/all-order-types#take-profit-limit) A Take Profit Limit Order will only execute where the Oracle Price of a given asset reaches the Trigger Price. If this happens, a Limit Order at the specified Limit Price will be placed. Once triggered, the resulting Limit Order may be immediately filled or may rest until the specified Limit Price is reached and executed by a decentralised keeper. Users can specify a Trigger Price and a Limit Price, and once (or if) the oracle price of the asset reaches the specified Trigger Price and a keeper executes it, a Limit Order will be placed at the specified Limit Price. Take Profit Limit Orders also serve as a max slippage tolerance for the Stop Order. | Current Position | Order Type | Trade Direction | Trigger Condition | Reduce Only | | --- | --- | --- | --- | --- | | Long | Take Profit (Market If Touch) | Buy | Above | False | | **Long** | **Take Profit** | **Sell** | **Above** | **True/False** | | **Short** | **Take Profit** | **Buy** | **Below** | **True/False** | | Short | Take Profit (Market If Touch) | Sell | Below | False | ⚠️ **If Trigger Price < Limit Price:** order starts getting filled once the price is below the trigger price. **If Limit Price < Trigger Price:** order starts getting filled once the price is below the limit price. One limitation is that the protocol can only detect that a Trigger Price has been hit if the order has already been or can be partially filled. This means it does not allow for some order configurations to be placed: | TriggerIsAbove | DirectionIsLong | LimitPrice | | --- | --- | --- | | True | True | Must be above trigger | | True | False | Ok | | False | True | Ok | | False | False | Must be below trigger | ⬇️ **Example:** If Trigger Price is >$140 and a Long is placed with a Limit Price = $135, there is no way the order can know that $140 was hit before you try to long when the price falls $5. In the other scenario, if Trigger Price is < $140 and a Long is placed with a Limit Price = $135, we will know that $140 (AND $135) must have been hit since you were partially filled. ### Oracle Limit[](https://docs.drift.trade/trading/all-order-types#oracle-limit) An Oracle Limit Order allows you to specify an **offset** rather than limit price to execute your order. The offset represents the price above/below the current **Oracle Price** you want to be filled at. For example, if you place a **Long Oracle Limit Order** on SOL-PERP with an offset of -1, you are saying you want to be filled at 1 dollar below the oracle price, if possible. In this case, you can be filled at 99 with SOL oracle price at 100, 98 with SOL oracle price at 99, etc. For a short order, you would typically want to use a positive offset instead. The idea is that these orders can be profitable as the market price on Drift trends back towards the oracle price. It's important to note that these orders can fill at any time the offset is met, so long as the account collateral is sufficient, regardless of how far the price is from what it was at the time of order placement. ### Order Flags[](https://docs.drift.trade/trading/all-order-types#order-flags) Additionally, orders can include flags that specify execution parameters. The protocol allows for three additional order flags, as written below: * **Reduce-Only:** Enforces that the order will never increase or reverse the current position (go from long to short, or short to long). * **Post-Only**: Enforces that the order is a maker order that can provide liquidity to the pool for a reduced exchange fee (0%). Without this flag, orders that don't execute immediately are not post-only. * **Immediate or cancel (IOC)**: An order that is placed and potentially partially filled. The remainder that is not filled immediately is then cancelled. ### Protected Maker Mode[](https://docs.drift.trade/trading/all-order-types#protected-maker-mode) When a user's account is set to Protected Market Maker mode, more strigent checks are applied to filling their limit orders. These orders can only be filled at the quoted price under the following conditions: * And at least one of these criteria is met: * The taker's order qualifies for instant fills against the AMM (order counts below whats typical of latency arbitrageurs). * The taker's order has been resting for at least 10 slots, preventing latency arbitrage race against the quote price. If the above is not met, the maker will automatically update their quotes an additional 10 bps in favor (e.g. lower for bids, higher for asks) vs the current price. By doing so, this mode provides partial protection for resting liqudity orders on-chain, providing the best prices only upon timely oracle updates and non-latency-arbitrage activity. Like other special user margin modes, enabling Protected Maker Mode is permissionless but has limited slot availability. [Order Types](https://docs.drift.trade/trading/order-types "Order Types") [Advanced Orders FAQ](https://docs.drift.trade/trading/advanced-orders-faq "Advanced Orders FAQ") --- # Margin Requirements – Drift Protocol 📈 Trading Margin Margin Requirements =================== Below is a table for initial and maintenance margin requirements for each market. Pulled directly from the protocol’s on-chain state. These values include: * **Initial Margin Ratio** (`marginRatioInitial`) * **Maintenance Margin Ratio** (`marginRatioMaintenance`) * **IMF Factor**, (`imfFactor`) affects leverage at higher notional sizes Data below is updated every hour from `PerpMarketAccount`. * * * ### Perpetual Markets[](https://docs.drift.trade/trading/margin#perpetual-markets) | Index | Perpetuals | Initial Margin (Ratio / Leverage) | Maintenance Margin (Ratio / Leverage) | IMF Factor | | --- | --- | --- | --- | --- | | 0 | SOL-PERP | 5.00% / 20x | 3.00% / 33x | 0.00005 | | 1 | BTC-PERP | 5.00% / 20x | 2.00% / 50x | 0.0019 | | 2 | ETH-PERP | 5.00% / 20x | 2.00% / 50x | 0.00025 | | 3 | APT-PERP | 10.00% / 10x | 5.00% / 20x | 0.0001 | | 4 | 1MBONK-PERP | 10.00% / 10x | 5.00% / 20x | 0.00055 | | 5 | POL-PERP | 10.00% / 10x | 5.00% / 20x | 0.0001 | | 6 | ARB-PERP | 10.00% / 10x | 5.00% / 20x | 0.0001 | | 7 | DOGE-PERP | 10.00% / 10x | 5.00% / 20x | 0.0001 | | 8 | BNB-PERP | 10.00% / 10x | 5.00% / 20x | 0.0035 | | 9 | SUI-PERP | 10.00% / 10x | 5.00% / 20x | 0.00045 | | 10 | 1MPEPE-PERP | 25.00% / 4x | 12.50% / 8x | 0.00075 | | 11 | OP-PERP | 10.00% / 10x | 5.00% / 20x | 0.00045 | | 12 | RENDER-PERP | 10.00% / 10x | 5.00% / 20x | 0.00055 | | 13 | XRP-PERP | 10.00% / 10x | 6.50% / 15x | 0.00025 | | 14 | HNT-PERP | 20.00% / 5x | 6.50% / 15x | 0.00055 | | 15 | INJ-PERP | 10.00% / 10x | 6.50% / 15x | 0.00055 | | 16 | LINK-PERP | 10.00% / 10x | 6.50% / 15x | 0.00055 | | 17 | RLB-PERP | 20.00% / 5x | 10.00% / 10x | 0.0001 | | 18 | PYTH-PERP | 10.00% / 10x | 5.00% / 20x | 0.0001 | | 19 | TIA-PERP | 10.00% / 10x | 5.00% / 20x | 0.0001 | | 20 | JTO-PERP | 10.00% / 10x | 5.00% / 20x | 0.0001 | | 21 | SEI-PERP | 10.00% / 10x | 5.00% / 20x | 0.0001 | | 22 | AVAX-PERP | 10.00% / 10x | 5.00% / 20x | 0.0001 | | 23 | WIF-PERP | 10.00% / 10x | 5.00% / 20x | 0.0001 | | 24 | JUP-PERP | 10.00% / 10x | 5.00% / 20x | 0.00005 | | 25 | DYM-PERP | 20.00% / 5x | 10.00% / 10x | 0.0005 | | 26 | TAO-PERP | 20.00% / 5x | 10.00% / 10x | 0.0001 | | 27 | W-PERP | 20.00% / 5x | 10.00% / 10x | 0.0001 | | 28 | KMNO-PERP | 33.34% / 3x | 16.67% / 6x | 0.000001 | | 29 | TNSR-PERP | 20.00% / 5x | 10.00% / 10x | 0.000001 | | 30 | DRIFT-PERP | 20.00% / 5x | 10.00% / 10x | 0.00005 | | 31 | CLOUD-PERP | 33.34% / 3x | 16.67% / 6x | 0.000001 | | 32 | IO-PERP | 33.34% / 3x | 16.67% / 6x | 0.000001 | | 33 | ZEX-PERP | 33.34% / 3x | 16.67% / 6x | 0.000001 | | 34 | POPCAT-PERP | 25.00% / 4x | 12.50% / 8x | 0.0001 | | 35 | 1KWEN-PERP | 25.00% / 4x | 12.50% / 8x | 0.0001 | | 42 | TON-PERP | 20.00% / 5x | 10.00% / 10x | 0.0001 | | 44 | MOTHER-PERP | 25.00% / 4x | 12.50% / 8x | 0.0001 | | 45 | MOODENG-PERP | 25.00% / 4x | 12.50% / 8x | 0.000001 | | 47 | DBR-PERP | 33.34% / 3x | 16.67% / 6x | 0.000001 | | 51 | 1KMEW-PERP | 25.00% / 4x | 12.50% / 8x | 0.0001 | | 52 | MICHI-PERP | 25.00% / 4x | 12.50% / 8x | 0.0001 | | 53 | GOAT-PERP | 25.00% / 4x | 12.50% / 8x | 0.0001 | | 54 | FWOG-PERP | 25.00% / 4x | 12.50% / 8x | 0.0001 | | 55 | PNUT-PERP | 25.00% / 4x | 12.50% / 8x | 0.0001 | | 56 | RAY-PERP | 20.00% / 5x | 10.00% / 10x | 0.0001 | | 59 | HYPE-PERP | 10.00% / 10x | 5.00% / 20x | 0.0001 | | 60 | LTC-PERP | 10.00% / 10x | 5.00% / 20x | 0.0001 | | 61 | ME-PERP | 20.00% / 5x | 10.00% / 10x | 0.0001 | | 62 | PENGU-PERP | 25.00% / 4x | 12.50% / 8x | 0.0001 | | 63 | AI16Z-PERP | 25.00% / 4x | 12.50% / 8x | 0.0001 | | 64 | TRUMP-PERP | 25.00% / 4x | 12.50% / 8x | 0.0001 | | 65 | MELANIA-PERP | 25.00% / 4x | 12.50% / 8x | 0.0001 | | 66 | BERA-PERP | 20.00% / 5x | 10.00% / 10x | 0.0001 | | 69 | KAITO-PERP | 20.00% / 5x | 10.00% / 10x | 0.00001 | | 70 | IP-PERP | 20.00% / 5x | 10.00% / 10x | 0.0001 | | 71 | FARTCOIN-PERP | 10.00% / 10x | 5.00% / 20x | 0.0001 | | 72 | ADA-PERP | 10.00% / 10x | 5.00% / 20x | 0.0001 | | 73 | PAXG-PERP | 10.00% / 10x | 5.00% / 20x | 0.001 | | 74 | LAUNCHCOIN-PERP | 25.00% / 4x | 12.50% / 8x | 0.0001 | | 75 | PUMP-PERP | 20.00% / 5x | 10.00% / 10x | 0.000001 | * * * ### High Leverage Mode Markets[](https://docs.drift.trade/trading/margin#high-leverage-mode-markets) If a user has High Leverage Mode turned on, Taker trading fees for all perp markets will be **2× the bottom fee tier**. | Index | Perpetuals | High Leverage Initial (Ratio / Leverage) | High Leverage Maintenance (Ratio / Leverage) | | --- | --- | --- | --- | | 0 | SOL-PERP | 0.99% / 101x | 0.66% / 152x | | 1 | BTC-PERP | 0.99% / 101x | 0.66% / 152x | | 2 | ETH-PERP | 0.99% / 101x | 0.66% / 152x | [Spot FAQ](https://docs.drift.trade/trading/spot-faq "Spot FAQ") [Order Types](https://docs.drift.trade/trading/order-types "Order Types") --- # Advanced Orders FAQ – Drift Protocol 📈 Trading Advanced Orders FAQ Advanced Orders FAQ =================== **How are the Limit Orders filled?** Limit Orders are taker orders that are filled against the AMM.  The orders are stored and settled on-chain. The queue is constructed by a network of off-chain keepers that are incentivised to fill orders against the AMM based on age. **Is there a charge for placing an order? Is that charged in SOL or USDC?** Network fees aside, there is no additional SOL charge for placing an order. The taker fee is charged in USDC and is only applied if the trade is filled. If a trade is only partially filled, the fee charged will be for the notional amount filled. **Is there a charge for cancelling an order? Is that charged in SOL or USDC?** No - if you cancel an open order, you will not be charged by the protocol. Fees are only charged on filled orders. **Is my order guaranteed to execute?** These orders are executed 'best effort' by the network with special economic incentives designed to mimic the typical execution order seen in a Centralised Limit Order Book (CLOB). **What are conditional limit orders?** Conditional limit orders are only placed on the market when the conditions for the orders are met. For instance, stop orders are only placed on the market when the trigger price is hit (the condition being the trigger price). **What is the difference between a Stop Market and a Stop Limit?** Both orders are used as downside protection to stop losses. However, where they differ is how the orders are executed. A Stop Market order is immediately sold on the market in full once the trigger price is reached. Stop Limits are slightly different - rather than opening a Market Order, it opens a new limit order which can have a different price to the trigger price used to create the limit order. **What is the difference between Take Profit Market and Take Profit Limit?** The difference is in the way these orders are settled. Take Profit Market orders are immediately sold on market upon hitting their trigger price. On the other hand, Take Profit Limit orders are not sold immediately but are partially filled as limit orders. The subsequent limit orders don’t need to have the same target price as their trigger price. **What is the difference between a Stop Loss and a Take Profit?** Both order types are set on the market when their triggers are met. Where the two orders differ is in their direction. Stop Losses are used for downside protection to close losing positions and Take Profits are used to close positions that are in profit. **Why my stop loss didn't trigger?** Limit orders will only execute if the oracle prices intersect. For precise historical price data based on the oracle, we recommend switching from 'Candles: Fills' to 'Candles: Oracle' in the top right corner of the chart. Even if the oracle price triggers your stop, executions are not guaranteed due to the decentralized orderbook. Fillers can place orders in a permissionless manner, operating on a first-come, first-served basis. If the price briefly matches your order, it may not be executed. We are continually enhancing our filler network. For technically inclined individuals seeking guaranteed fills, you can operate your own filler for personal orders; however, even then, execution cannot be assured. This trade-off is necessary to achieve a decentralized and scalable system. Occasionally, stale oracle information may result in unfilled orders during certain periods. **Why did my take profit order not work?** Take profit orders on Drift use the oracle price, not the mark price. This means the order is triggered based on a fair market price from a reliable source (Pyth) instead of the current trading price on the exchange. You can switch between the oracle and mark price view on the chart for better understanding. **My stop-loss order didn't trigger, and the price went up. Why did I lose money?** Similar to the take profit scenario, stop-loss orders are also triggered based on the oracle price. If the oracle price briefly touched your stop-loss level and then bounced back, your order might have been executed even though the market price never reached that level. **What is the difference between a trigger price and a limit price?** * Trigger price: This price point determines when your order (take profit or stop-loss) gets activated. It uses the oracle price for execution. * Limit price: This price specifies the exact price at which your order gets filled. It can be used with stop-loss and take-profit orders to guarantee execution at a specific price, but comes with potential slippage (filling at a slightly different price) and fees. **What does trigger price mean?** Trigger price refers to the price the particular asset needs to hit before the limit order can be executed against the AMM by a Keeper. **Why is the orderbook constructed off-chain?** Drift doesn't construct a central limit orderbook on-chain and instead opts for a flat structure to achieve cost-effective scalability. The network of Keepers monitor on-chain orders and construct their own orderbooks off-chain. This achieves (1) decentralisation (as each Keeper stores its own copy of the orderbook); and (2) computational efficiency (as the high throughput and intensive computations are calculated off-chain). Theoretically, this should also translate to better performance during periods of high network congestion. **What is reduce-only?** **Reduce-only** orders guarantee that you will: * NOT be made longer if you are already long (or shorter if you are already short); and * NOT be made short if you were previously long (or vice versa). **What are Keeper bots? How can I participate?** A Keeper will track and fill orders and earn a reward. Guide to running different types of [Keeper Bots](https://docs.drift.trade/tutorial-bots) . [All Order Types](https://docs.drift.trade/trading/all-order-types "All Order Types") [Health Breakdown](https://docs.drift.trade/trading/account-health "Health Breakdown") --- # Account Health Breakdown – Drift Protocol 📈 Trading Health Breakdown Account Health Breakdown ======================== Users can get a detailed overview of the status of their collateral and current margin requirements in the Account Health Breakdown. The Account Health Breakdown is located in the Overview tab above the Portfolio Value chart: ![](https://docs.drift.trade/assets/find-account-health.png) The account health percentage indicates the overall health status of your main account, which can change based on your open positions and their margin requirements; when it reaches zero, it signifies that the weighted value of your total collateral has fallen below the maintenance margin requirement, potentially leading to liquidation. Health Breakdown is calculated as `1 - Maintenance Margin / Margin Collateral`. Initial and Maintenance Margin[](https://docs.drift.trade/trading/account-health#initial-and-maintenance-margin) ----------------------------------------------------------------------------------------------------------------- In the Health Breakdown, you can switch between the _Initial_ and _Maintenance_ margin breakdowns. Initial margin represents the total collateral you deposited across all markets, calculated with their respective asset weights. It is the amount required to take risk-increasing actions. If your initial margin is fully utilized (shown as a yellow-colored bar instead of green) within your existing position margin requirements and potentially existing borrow, you may not be able to open new positions. Non-USDC collateral carries a discount weighting; for example, SOL has an initial asset weight of 80% and a maintenance asset weight of 90%. Additionally, the initial asset weight can programmatically shrink based on total notional deposits. Each asset has a calculated asset weight. You can see each asset's weight in the [Cross-collateral deposits](https://docs.drift.trade/getting-started/cross-collateral-deposits) . ![](https://docs.drift.trade/assets/health-breakdown-switch.png) The total collateral in the Maintenance margin breakdown will appear greater because it represents the amount required to avoid liquidation. Find the table for each asset's initial and margin requirements for each market on the [Margin](https://docs.drift.trade/trading/margin) page. Assets[](https://docs.drift.trade/trading/account-health#assets) ----------------------------------------------------------------- Under the Assets breakdown, you can see your deposited assets and Unsettled P&L. Unsettled P&L represents the unrealized profit or loss from open positions that have not yet been closed, fluctuating with market prices; it becomes realized when the positions are closed. More comprehensive explanation in [What is unsettled P&L?](https://docs.drift.trade/profit-loss/what-is-unsettled-profit-loss) ![](https://docs.drift.trade/assets/health-breakdown-asset.png) Liabilities[](https://docs.drift.trade/trading/account-health#liabilities) --------------------------------------------------------------------------- Liabilities account for all of your open positions and borrows. If your liabilities are equal to or greater than your assets, you will not be able to place any new trades until you close existing positions, settle P&L, or deposit more collateral. ![](https://docs.drift.trade/assets/health-breakdown-liabilities.png) Account Health Breakdown FAQ[](https://docs.drift.trade/trading/account-health#account-health-breakdown-faq) ------------------------------------------------------------------------------------------------------------- ### I have free collateral, why can't I trade with margin?[](https://docs.drift.trade/trading/account-health#i-have-free-collateral-why-cant-i-trade-with-margin) Make sure you're looking at the Initial Margin breakdown, not the Maintenance Margin. Initial Margin is the amount required to take risk-increasing actions, while Maintenance Margin represents the amount required to avoid liquidation. ### How can I increase my account health?[](https://docs.drift.trade/trading/account-health#how-can-i-increase-my-account-health) Deposit more collateral, settle P&L, repay borrowed funds, or reduce active positions. ### If the health is 0%, will the position be fully liquidated or just partially to maintain a proper health value?[](https://docs.drift.trade/trading/account-health#if-the-health-is-0-will-the-position-be-fully-liquidated-or-just-partially-to-maintain-a-proper-health-value) It starts as being partially liquidated and progresses to full liquidation if the user doesn't reduce the position manually or deposit more collateral. [Advanced Orders FAQ](https://docs.drift.trade/trading/advanced-orders-faq "Advanced Orders FAQ") [Auction Parameters](https://docs.drift.trade/trading/auction-parameters "Auction Parameters") --- # Auction Parameters – Drift Protocol 📈 Trading Auction Parameters Auction Parameters ================== Drift Protocol allows orders to set custom auction parameters. These settings allow users to customize how their orders are executed on the Drift Protocol by setting specific auction parameters. You can see the implementation of these auction settings [here (opens in a new tab)](https://github.com/drift-labs/drift-common/blob/master/common-ts/src/common-ui-utils/commonUiUtils.ts#L374) . ℹ️ **Double Check:** One can always review their Auction Parameters for a particular order in the Confirmation Modal before submitting. (you can expand details with "Advanced" checked) **Start Price Fields:** 1. Oracle Price (current oracle price of the market) 2. Best Bid/Ask (use best bid/ask price) 3. Est. Entry Price (price includes estimated price impact on DLOB/AMM) 4. Best Overall (select best price of all of the above) ⚠️ **For Large Size:** It's recommended to set a longer duration, "Use Oracle Offset", and wider start, end buffers. ![](https://docs.drift.trade/_next/image?url=%2F_next%2Fstatic%2Fmedia%2FhP5UraVYsWUZWP2ntEZI1_screen-shot-2023-11-03-at-71615-am.54c88310.png&w=3840&q=75) With Drift Protocol, users can determine the duration of their order in 'slots', and set starting and ending prices based on the keeper network's view of the DLOB. For the given specifications above: * the user wants the order to start at a price 0.05% better than the estimated fill price. * The order will end at a price that's the worst fill, but with a safety buffer of 0.05% slippage. * This entire process will take place over 20 slots, which is roughly 10 seconds. * If the order isn't fully executed within this time, any remaining amount can be filled at a price 0.5% worse than the estimated entry price up to the order's expiry. Note: By default, market orders expire after 60 slots. Additionally, user's can specify their auctions as offsets from oracle price. This means during the auction (and at runtime) the auction is dynamically moving with the oracle prices as they update (increasing the chance of fair value fills). ### Auctions for Limit Orders[](https://docs.drift.trade/trading/auction-parameters#auctions-for-limit-orders) When submitted limit orders crosses local DLOB and/or AMM, a limit order without post only flag will actually submit an auction first. The limit order uses the user defined rule for start price for its start auction param. It effectively the same as a market auction order **except the user explicitly overrides the End Price and Slippage Tolerance Limit Price.** ### Atomic Fills against Resting Liquidity[](https://docs.drift.trade/trading/auction-parameters#atomic-fills-against-resting-liquidity) When 'Fill against resting liquidity first' is enabled, placed orders will go through the 'place\_and\_take' instruction. In Place And Take, a list of makers can be passed in with the user's order and if the user's _auction END price_ crosses the makers' limit price(s), the order will match. Any remaining amount of the order after this step will go through a typical auction (from start to end), unless IOC is enabled (in which case the order will cancel after attempting to fill vs makers). Note than Drift's AMM will not provide liquidity to takers atomically in the first step. [Health Breakdown](https://docs.drift.trade/trading/account-health "Health Breakdown") [Trading Fees](https://docs.drift.trade/trading/trading-fees "Trading Fees") --- # Metamask Setup – Drift Protocol 👋🏻 Getting Started Wallet Setup MetaMask Metamask Setup[](https://docs.drift.trade/getting-started/wallet-setup/metamask-setup#metamask-setup) ------------------------------------------------------------------------------------------------------ With CONNECT by Drift, MetaMask can be used to trade and sign transactions on Drift. CONNECT by Drift is an open source wallet extension that is powered by [MetaMask Snaps (opens in a new tab)](https://metamask.io/snaps/) , an innovation that extends the functionality of the MetaMask platform to other chains. > Note: MetaMask Snaps is in open beta and is available for you to use at your own risk. If you're experiencing any issues, you can reach out to our team via [discord (opens in a new tab)](https://discord.gg/YaK2a5ge) > . Getting Started[](https://docs.drift.trade/getting-started/wallet-setup/metamask-setup#getting-started) -------------------------------------------------------------------------------------------------------- ### 1\. Connect your MetaMask wallet[](https://docs.drift.trade/getting-started/wallet-setup/metamask-setup#1-connect-your-metamask-wallet) Click connect in the top right corner to get started. If you have MetaMask already installed, CONNECT will automatically detect this. Select MetaMask to continue. ![](https://docs.drift.trade/assets/zVsh4Q-JhPX9uxgy3zfOf_image.png) ### 2\. Install MetaMask Snaps[](https://docs.drift.trade/getting-started/wallet-setup/metamask-setup#2-install-metamask-snaps) If this is your first time interacting with MetaMasks Snaps, you'll be prompted within MetaMask to install it. ![](https://docs.drift.trade/assets/kSPfJGiHmwpt0f5d0c_GX_cleanshot-2023-09-05-at-143123.png) ### 3\. Connect to Drift[](https://docs.drift.trade/getting-started/wallet-setup/metamask-setup#3-connect-to-drift) Next, you'll be prompted to connect to Drift via MetaMask Snaps. Once you connect, a new Solana compatible wallet will be automatically created for you in MetaMask. ![](https://docs.drift.trade/assets/EhZkDFLwYTlNCW5hLbMar_image.png) ### 4\. Fund your wallet[](https://docs.drift.trade/getting-started/wallet-setup/metamask-setup#4-fund-your-wallet) To start trading on Drift, your new MetaMask wallet will need some SOL for transaction fees and you'll need to deposit collateral to Drift. The onboarding flow will guide you from one step to the next. You can use [Mayan Cross Chain Swaps (opens in a new tab)](https://mayan.finance/) to bridge assets over from your EVM wallet to your Solana wallet, including gas drop off, all in one step! ![](https://docs.drift.trade/assets/ql39QrhU2kgdZa7Hs9xiB_image.png) If you'd like to fund your new MetaMask wallet from another Solana wallet, select "Fund from another wallet" for a step-by-step guide. ### 5\. Deposit Collateral to Drift[](https://docs.drift.trade/getting-started/wallet-setup/metamask-setup#5-deposit-collateral-to-drift) Once funds have been added to the wallet, you're now ready to deposit collateral to Drift for trading. If you've exited the onboarding flow, you can click on `Bridge` to use Mayan Swaps or Wormhole. To deposit collateral, you can click on the `Deposit/Withdraw` button. ![](https://docs.drift.trade/assets/AEdM8EMizcQFF6yHQMXxY_image.png) ### 6\. Managing funds in your MetaMask Solana Wallet[](https://docs.drift.trade/getting-started/wallet-setup/metamask-setup#6-managing-funds-in-your-metamask-solana-wallet) MetaMask Snaps is currently in Open Beta and does not yet support viewing funds/balances from within MetaMask itself. You can view your MetaMask Solana Wallet balances within Drift by accessing the account dropdown and selecting `Manage Metamask Wallet`. > Note: Drift can only display the balances in your MetaMask Solana wallet, you have full control over these funds. ![](https://docs.drift.trade/assets/i8GYsXqJ57cJKVUxrVB6g_image.png) ![](https://docs.drift.trade/assets/ex6Z7tZFZHHGjpI7StycV_image.png) CONNECT by Drift FAQs[](https://docs.drift.trade/getting-started/wallet-setup/metamask-setup#connect-by-drift-faqs) -------------------------------------------------------------------------------------------------------------------- ### What is CONNECT by Drift?[](https://docs.drift.trade/getting-started/wallet-setup/metamask-setup#what-is-connect-by-drift) CONNECT by Drift is an open source wallet connector powered by MetaMask Snaps, allowing users to interface with any Solana dApp using their Metamask wallet. ### What is MetaMask Snaps?[](https://docs.drift.trade/getting-started/wallet-setup/metamask-setup#what-is-metamask-snaps) MetaMask Snaps extends the functionality of the MetaMask platform, allowing users to interact with any dApp on any chain with the same security and a familiar UI. You can learn more about MetaMask Snaps [here (opens in a new tab)](https://metamask.io/snaps/) . ### Where can I find my private key or seed phrase?[](https://docs.drift.trade/getting-started/wallet-setup/metamask-setup#where-can-i-find-my-private-key-or-seed-phrase) Drift doesn't have access to your private keys or seed phrase. You can export your seed phrase from MetaMask directly to import into another wallet of your choice. ### Does CONNECT by Drift work on mobile?[](https://docs.drift.trade/getting-started/wallet-setup/metamask-setup#does-connect-by-drift-work-on-mobile) Not yet. Once MetaMask announces support for mobile, we'll be sure to include it! ### Can I install other Snaps?[](https://docs.drift.trade/getting-started/wallet-setup/metamask-setup#can-i-install-other-snaps) Yes, you'll be able to install and use other snaps. ### Why am I'm having trouble connecting to other dApps?[](https://docs.drift.trade/getting-started/wallet-setup/metamask-setup#why-am-im-having-trouble-connecting-to-other-dapps) Sometimes wallet adapter software can be out-of-date. Visit the discord of the dApp you're trying to connect to and determine if they've added CONNECT by Drift to their wallet adapter. ### Can I use Connect for my own dApp?[](https://docs.drift.trade/getting-started/wallet-setup/metamask-setup#can-i-use-connect-for-my-own-dapp) Yes! You can add CONNECT by Drift to your dApps' wallet adapter by installing the [npm package (opens in a new tab)](https://www.npmjs.com/package/@drift-labs/snap-solana) . CONNECT by Drift is also open source, you can view the code here if you'd like to develop you're own MetaMask Solana Snap. Last updated on July 21, 2025 [Phantom](https://docs.drift.trade/getting-started/wallet-setup/phantom-setup " Phantom") [Bot Wallet](https://docs.drift.trade/getting-started/wallet-setup/bot-wallet-setup "Bot Wallet") --- # Bot Wallet Setup – Drift Protocol 👋🏻 Getting Started Wallet Setup Bot Wallet Bot Wallet Setup[](https://docs.drift.trade/getting-started/wallet-setup/bot-wallet-setup#bot-wallet-setup) ------------------------------------------------------------------------------------------------------------ Bots require a private key in order to sign transactions. The private key is stored in a wallet file and can either be in base58 format, or a numbers array format. Generate a Fresh keypair[](https://docs.drift.trade/getting-started/wallet-setup/bot-wallet-setup#generate-a-fresh-keypair) ---------------------------------------------------------------------------------------------------------------------------- ### 1\. Download and install the Solana CLI[](https://docs.drift.trade/getting-started/wallet-setup/bot-wallet-setup#1-download-and-install-the-solana-cli) First download and install the Solana CLI following the [official instructions (opens in a new tab)](https://docs.solanalabs.com/cli/install) . ### 2\. Generate a new keypair[](https://docs.drift.trade/getting-started/wallet-setup/bot-wallet-setup#2-generate-a-new-keypair) Create a new keypair file named `new_keypair.json`: solana-keygen new -o new_keypair.json This will contain a new keypair in JSON format. Export Keypair from a browser wallet[](https://docs.drift.trade/getting-started/wallet-setup/bot-wallet-setup#export-keypair-from-a-browser-wallet) ---------------------------------------------------------------------------------------------------------------------------------------------------- Alternatively you may export the private key from an existing browser wallet such as [Phantom](https://docs.drift.trade/getting-started/wallet-setup/phantom-setup) . Last updated on July 21, 2025 [MetaMask](https://docs.drift.trade/getting-started/wallet-setup/metamask-setup "MetaMask") [Wallet FAQ](https://docs.drift.trade/getting-started/wallet-setup/wallet-faq "Wallet FAQ") --- # Passwordless login – Drift Protocol 👋🏻 Getting Started Passwordless and Social Login Passwordless login ================== You can get started on Drift quickly and securely without any passwords or seed phrases to access your account or funds. You can sign up/log in with your email. Social logins are coming soon. ### How does passwordless login work?[](https://docs.drift.trade/getting-started/passwordless-login#how-does-passwordless-login-work) When you sign up for Drift with your email, a [Magic Wallet (opens in a new tab)](https://magic.crisp.help/en/category/magic-wallet-user-faq-1xtseie/) is automatically created for you. This is a non-custodial crypto wallet associated with your Drift account that you have sole control over. Here’s what you can expect when you sign up with email: 1. **Sign up with an email** * No password is required, you’ll be prompted to authorize via email * An authentication email will be sent to you each time you want to log in. * Once authorized, the sign-in page will reload and a Magic Wallet will be created for you. * Magic Wallets are provided by [Magic Link (opens in a new tab)](https://magic.crisp.help/en/category/magic-wallet-user-faq-1xtseie/) * This is a non-custodial wallet * In the future, if you prefer to connect with your own Solana wallet to Drift, you can do this at any time and a new Drift account will be created 2. **Your Magic Wallet address and private key** * At this step, you’ll be presented with your wallet address and private key to store. You can retrieve your private key at any time. * Drift and Magic Link do not have access to your Magic Wallet or Private Keys and won’t be able to help you recover it if you lose access. 3. **Deposit SOL and collateral** * A small amount of SOL in your wallet is needed for transaction fees and you’ll also be asked to deposit assets onto Drift as collateral for trading * You can fund your wallet from another wallet or centralized exchange using the QR code. Need help depositing/transferring funds? [Transferring funds from Binance, Kraken, and Coinbase (opens in a new tab)](https://www.drift.trade/learn/how-to-transfer-funds-from-a-cex-onto-drift) [Transferring funds from another chain (e.g. Ethereum) (opens in a new tab)](https://www.drift.trade/learn/how-to-bridge-assets) 4. **Start trading** FAQ[](https://docs.drift.trade/getting-started/passwordless-login#faq) ----------------------------------------------------------------------- **What is Passwordless Authentication?** Neither Drift nor Magic Link sets or keeps passwords used for authentication. When you sign up with email, a Magic Link email is sent to that address to authorize sign-up and log-in requests. Passwordless authentication eliminates use cases where users’ passwords can be phished. **Is Magic Wallet a noncustodial wallet?** Your Magic Wallet is noncustodial, meaning you have complete control over your private keys and funds inside the wallet. Drift and Magic Link do not have access to your wallet or passwords. **Is Magic Wallet secure?** Magic Wallet uses a Delegated Key Management system that is secured by Hardware Security Modules (HSMs). These HSMs are similar to hardware-based wallets like Trezor or Ledger but they sit on the cloud and are secured by AWS data centers. In addition to this, Magic Link is SOC2-Type 2 and GDPR compliant — meaning the effectiveness of their security and privacy procedures have been audited. To learn more about security, deep dive into Magic Link's [whitepaper (opens in a new tab)](https://magic.link/docs/home/security) . **Where can I find my wallet address?** 1. In the top right-hand corner of the app, click on the account button to reveal the dropdown 2. Click on "Manage Magic Wallet" (see screenshot) 3. Your wallet address will be located below your wallet balance ![](https://docs.drift.trade/assets/EO9M9zIRWxQoBPZCx8g7L_frame-427320883.png) ![](https://docs.drift.trade/assets/oV4RYUjdHvDMyPcrfoDUM_image.png) **Where can I find my private key?** 1. In the same wallet modal, click on the 3-dots menu and select "Get Private Key". 2. You'll be connected to a secure site to retrieve it ![](https://docs.drift.trade/assets/XiJ2eLH1vopzxDLVlZcVX_image.png) **How can I set up Multifactor Authentication (MFA) for my Magic Wallet?** MFA is coming soon! [Wallet FAQ](https://docs.drift.trade/getting-started/wallet-setup/wallet-faq "Wallet FAQ") [Cross-collateral deposits](https://docs.drift.trade/getting-started/cross-collateral-deposits "Cross-collateral deposits") --- # Creating and Managing Subaccount – Drift Protocol 👋🏻 Getting Started Managing Subaccount Creating and Managing Subaccount ================================ Drift features a powerful subaccount tool for users to clearly separate positions within a single address. Each subaccount's margin and positions are isolated from other subaccounts, meaning that users can trade on isolated margin via different subaccounts. Each subaccount has independent positions, balances and margins, and can trade independently. Balances or liquidations from each subaccount will not affect other subaccounts. Each subaccount is cross-margined. ℹ️ A subaccount can hold up to 8 perpetual and 8 spot positions and 32 open orders total. A perpetual position with 0 base, but only unsettled P&L counts as an open position. Adding a Subaccount[](https://docs.drift.trade/getting-started/managing-subaccount#adding-a-subaccount) -------------------------------------------------------------------------------------------------------- Here's how you can add a subaccount: 1. Go to the account dropdown in the top right of the app. ![](https://docs.drift.trade/assets/vyi6ndY7NLKNxsgOKwlul_accountswitch.png) 2\. Click "Add Subaccount." ![](https://docs.drift.trade/assets/4p3uxGuLrHi_3RxxEXGd-_subaccount.png) 3\. You'll be asked to name your new subaccount and deposit collateral from your wallet to fund that account. You can also transfer collateral to your new subaccount from an existing one to fund it. ![](https://docs.drift.trade/assets/G648H8RneRHotAOLTrdjP_typeadd-account-wallet-statefocused.png) Editing and Deleting a Subaccount[](https://docs.drift.trade/getting-started/managing-subaccount#editing-and-deleting-a-subaccount) ------------------------------------------------------------------------------------------------------------------------------------ How to delete an account? 1- Make sure your account has zero balances. This includes open borrows, any unsettled pnl's. 2- Make sure your account is idle, accounts that have no activity for few hours (4-5) are marked as idle. 3- Click the trash bin icon on the interface. Deleting an account instantly gives you the rent back, there are no additional steps to claim the rent $SOL. \*Deleting an account deletes the history attached to that address and there is no backup for this. Excess Account Rent Redeeming (Users who paid rent for more than 0.035) Users paying excess rent can claim their excess amount after 13 days. It can be claimed at Account>ManageAccounts>Claim (under Reclaimable Rent) ### Switching Subaccounts[](https://docs.drift.trade/getting-started/managing-subaccount#switching-subaccounts) Once you've created a new account, you can use the same account switcher to move between them. ![](https://docs.drift.trade/assets/fwwcCcRroK8pA4hGg_L9B_screen-shot-2022-10-18-at-62504-pm.png) Managing Subaccount Assets[](https://docs.drift.trade/getting-started/managing-subaccount#managing-subaccount-assets) ---------------------------------------------------------------------------------------------------------------------- You can easily manage your assets via the Accounts button in the top navigation, via the Balances & Interest page in your Overview, or the Manage Subaccounts page in the Overview. Navigate to the Balances & Interest page within your portfolio to get an overview of the assets you've deposited. To see the assets of a single subaccount, use the account switcher in the left navigation to switch to that account. From the Balances & Interest page or the Manage Collateral window, you can: * Deposit additional assets * Withdraw to your wallet * Transfer assets between accounts Here's how you can access it via the navigation bar: ![](https://docs.drift.trade/assets/-fvDPAylp8Kc0Ais_6BkA_collateral.png) [Cross-collateral deposits](https://docs.drift.trade/getting-started/cross-collateral-deposits "Cross-collateral deposits") [Delegated Accounts](https://docs.drift.trade/getting-started/delegated-accounts "Delegated Accounts") --- # Wallet Faq – Drift Protocol 👋🏻 Getting Started Wallet Setup Wallet FAQ Wallet FAQ[](https://docs.drift.trade/getting-started/wallet-setup/wallet-faq#wallet-faq) ------------------------------------------------------------------------------------------ ### Do I need SOL in my wallet?[](https://docs.drift.trade/getting-started/wallet-setup/wallet-faq#do-i-need-sol-in-my-wallet) Yes, all interactions with the platform will require a small amount of SOL for the gas fees on the blockchain. ### I have paid some SOL while creating an account on Drift. What is this?[](https://docs.drift.trade/getting-started/wallet-setup/wallet-faq#i-have-paid-some-sol-while-creating-an-account-on-drift-what-is-this) It is called dynamic account rent and it is reclaimable. Every account pays an account rent of around 0.035 SOL to create an account on Drift. During sybil activity (when a lot of users are signing up), Drift's program adds an excess fee above this rent amount. For example, a user can pay 0.035 + 0.1901 SOL = 0.2251 SOL to create an account. This amount can be fully redeemed. For the excess amount (0.1901 in the above example), users need to wait 7 days to reclaim their excess SOL rent. For the base rent (0.035 in the above example), users need to delete their account created on Drift to redeem that amount back. 🚫 Deleting an account deletes all history attached to that Drift account, and there is no retrieval for this. Steps for reclaiming dynamic account rent: Click on your wallet address displayed in the top right corner of the screen. Click on 'Manage'. You'll see a trash/bin icon with a red color. Make sure: * You don't have any open borrows on your account. You can check that on the 'Balances' page (opens in a new tab). * Make sure you don't have any unsettled PnL. If you have any, make sure to settle it. * Get your account to zero balances (Withdraw your balances from Drift). Clicking the trash/bin icon will delete your account history and redeem your account rent instantly, without requiring any additional steps. Steps for reclaiming excess fee: Users need to wait 7 days to reclaim their excess fee. Click on your wallet address displayed in the top right corner of the screen. Click on 'Manage'. Under 'reclaimable rent', you'll see a 'Claim' button. Clicking that button will instantly return any excess fee (if you paid while creating an account on Drift) to your account. ### Does my wallet support versioned transactions?[](https://docs.drift.trade/getting-started/wallet-setup/wallet-faq#does-my-wallet-support-versioned-transactions) Versioned transactions need to be turned on to use Drift's Swaps feature. Read more about versioned transactions and which wallets support it [here](https://docs.drift.trade/trading/versioned-transactions) . ### I deposited into Drift and it’s not showing up in my balance.[](https://docs.drift.trade/getting-started/wallet-setup/wallet-faq#i-deposited-into-drift-and-its-not-showing-up-in-my-balance) Log out and in again, refresh the site. [Bot Wallet](https://docs.drift.trade/getting-started/wallet-setup/bot-wallet-setup "Bot Wallet") [Passwordless and Social Login](https://docs.drift.trade/getting-started/passwordless-login "Passwordless and Social Login") --- # Other Trading Fees – Drift Protocol 📈 Trading Other Trading Fees Other Trading Fees ================== These are additional fees charged across perpetual and spot markets. ### Definitions[](https://docs.drift.trade/trading/other-trading-fees#definitions) * **`liquidator_fee`**: Additional premium for taking over asset/liability pairs at oracle. * **`insurance_fee`**: Fee reserved for revenue pool → insurance fund. * **`borrow_rate_fee`**: Fraction of borrow interest reserved for revenue pool → insurance fund. * * * ### Other Perp Fees[](https://docs.drift.trade/trading/other-trading-fees#other-perp-fees) | Market | Liquidator Fee | Insurance Fee | | --- | --- | --- | | SOL-PERP | 0.0075 | 0.0075 | | BTC-PERP | 0.005 | 0.0075 | | ETH-PERP | 0.005 | 0.0075 | | APT-PERP | 0.01 | 0.025 | | 1MBONK-PERP | 0.025 | 0.05 | | POL-PERP | 0.01 | 0.02 | | ARB-PERP | 0.01 | 0.025 | | DOGE-PERP | 0.01 | 0.025 | | BNB-PERP | 0.01 | 0.02 | | SUI-PERP | 0.01 | 0.02 | | 1MPEPE-PERP | 0.025 | 0.05 | | OP-PERP | 0.01 | 0.02 | | RENDER-PERP | 0.01 | 0.02 | | XRP-PERP | 0.01 | 0.02 | | HNT-PERP | 0.025 | 0.025 | | INJ-PERP | 0.02 | 0.02 | | LINK-PERP | 0.02 | 0.02 | | RLB-PERP | 0.025 | 0.025 | | PYTH-PERP | 0.025 | 0.025 | | TIA-PERP | 0.02 | 0.02 | | JTO-PERP | 0.025 | 0.025 | | SEI-PERP | 0.02 | 0.02 | | AVAX-PERP | 0.01 | 0.02 | | WIF-PERP | 0.025 | 0.05 | | JUP-PERP | 0.02 | 0.025 | | DYM-PERP | 0.025 | 0.045 | | TAO-PERP | 0.025 | 0.045 | | W-PERP | 0.03 | 0.045 | | KMNO-PERP | 0.01 | 0.02 | | TNSR-PERP | 0.01 | 0.05 | | DRIFT-PERP | 0.01 | 0.05 | | CLOUD-PERP | 0.045 | 0.045 | | IO-PERP | 0.045 | 0.045 | | ZEX-PERP | 0.045 | 0.045 | | POPCAT-PERP | 0.025 | 0.05 | | 1KWEN-PERP | 0.025 | 0.05 | | TON-PERP | 0.01 | 0.05 | | MOTHER-PERP | 0.025 | 0.05 | | MOODENG-PERP | 0.025 | 0.05 | | DBR-PERP | 0.045 | 0.045 | | 1KMEW-PERP | 0.025 | 0.05 | | MICHI-PERP | 0.025 | 0.05 | | GOAT-PERP | 0.025 | 0.05 | | FWOG-PERP | 0.025 | 0.05 | | PNUT-PERP | 0.025 | 0.05 | | RAY-PERP | 0.01 | 0.05 | | HYPE-PERP | 0.01 | 0.05 | | LTC-PERP | 0.01 | 0.02 | | ME-PERP | 0.01 | 0.02 | | PENGU-PERP | 0.02 | 0.05 | | AI16Z-PERP | 0.025 | 0.05 | | TRUMP-PERP | 0.025 | 0.05 | | MELANIA-PERP | 0.025 | 0.05 | | BERA-PERP | 0.025 | 0.05 | | KAITO-PERP | 0.01 | 0.015 | | IP-PERP | 0.025 | 0.05 | | FARTCOIN-PERP | 0.01 | 0.015 | | ADA-PERP | 0.01 | 0.015 | | PAXG-PERP | 0.01 | 0.015 | | LAUNCHCOIN-PERP | 0.01 | 0.015 | | PUMP-PERP | 0.04 | 0.04 | * * * ### Other Spot Fees[](https://docs.drift.trade/trading/other-trading-fees#other-spot-fees) | Market | Liquidator Fee | Insurance Fee | Borrow Rate Fee | | --- | --- | --- | --- | | USDC | 0 | 0.005 | 0.1 | | SOL | 0.0075 | 0.0225 | 0.2 | | mSOL | 0.0075 | 0.0325 | 0.1 | | wBTC | 0.0075 | 0.0325 | 0.2 | | wETH | 0.0075 | 0.0325 | 0.2 | | USDT | 0.005 | 0.015 | 0.1 | | jitoSOL | 0.0075 | 0.0325 | 0.1 | | PYTH | 0.01 | 0.065 | 0.1 | | bSOL | 0.0075 | 0.0325 | 0.1 | | JTO | 0.01 | 0.065 | 0.1 | | WIF | 0.015 | 0.085 | 0.35 | | JUP | 0.01 | 0.065 | 0.1 | | RENDER | 0.01 | 0.065 | 0.1 | | W | 0.01 | 0.065 | 0.35 | | TNSR | 0.01 | 0.065 | 0.1 | | DRIFT | 0.015 | 0.06 | 0.1 | | INF | 0.0075 | 0.0325 | 0.1 | | dSOL | 0.0075 | 0.0325 | 0.1 | | USDY | 0.0075 | 0.0125 | 0.1 | | JLP | 0.0075 | 0.0325 | 0.1 | | POPCAT | 0.015 | 0.085 | 0.1 | | CLOUD | 0.01 | 0.065 | 0.1 | | PYUSD | 0.0075 | 0.0125 | 0.1 | | USDe | 0.0175 | 0.0625 | 0.35 | | sUSDe | 0.0175 | 0.0625 | 0.1 | | BNSOL | 0.0075 | 0.0325 | 0.1 | | MOTHER | 0.015 | 0.085 | 0.2 | | cbBTC | 0.0075 | 0.0325 | 0.1 | | USDS | 0.0075 | 0.0125 | 0.1 | | META | 0.0325 | 0.0625 | 0.1 | | ME | 0.0125 | 0.0375 | 0.1 | | PENGU | 0.0125 | 0.0475 | 0.1 | | Bonk | 0.015 | 0.085 | 0.1 | | JLP-1 | 0.005 | 0.015 | 0.1 | | USDC-1 | 0 | 0.0005 | 0.1 | | AI16Z | 0.015 | 0.075 | 0.1 | | TRUMP | 0.015 | 0.075 | 0.1 | | MELANIA | 0.015 | 0.085 | 0.1 | | AUSD | 0.0075 | 0.0125 | 0.1 | | FARTCOIN | 0.0375 | 0.0625 | 0.1 | | JitoSOL-3 | 0.005 | 0.015 | 0.1 | | PT-fragSOL-10JUL25 | 0.005 | 0.015 | 0.1 | | PT-kySOL-15JUN25-3 | 0.005 | 0.015 | 0.1 | | PT-dSOL-30JUN25-3 | 0.005 | 0.015 | 0.1 | | JTO-3 | 0.005 | 0.015 | 0.1 | | zBTC | 0.0075 | 0.0225 | 0.1 | | ZEUS | 0.0375 | 0.0625 | 0.1 | | USDC-4 | 0.001 | 0.001 | 0.02 | | USDT-4 | 0.001 | 0.001 | 0.02 | | SOL-2 | 0.005 | 0.015 | 0.1 | | JitoSOL-2 | 0.005 | 0.015 | 0.1 | | JTO-2 | 0.005 | 0.015 | 0.1 | | dfdvSOL | 0.005 | 0.015 | 0.1 | | sACRED-4 | 0.01 | 0.01 | 0.02 | | EURC | 0.0075 | 0.0125 | 0.1 | | PT-fragSOL-31OCT25-3 | 0.005 | 0.015 | 0.1 | | PUMP | 0.0275 | 0.0425 | 0.1 | | syrupUSDC | 0.005 | 0.0125 | 0.1 | * * * [Trading Fees](https://docs.drift.trade/trading/trading-fees "Trading Fees") [Fee Pool](https://docs.drift.trade/trading/fee-pool "Fee Pool") --- # Cross-collateral deposits – Drift Protocol 👋🏻 Getting Started Cross-collateral deposits Cross-collateral deposits ========================= By default, markets are quoted in USD and P&L is settled in USDC. All tokens deposited within the protocol can earn yield via Borrow/Lend. Until unrealised P&L is settled into your Balances, it will not earn (if profits) or be charged (if losses) the deposit/borrow interest respectively. Below is a table of assets supported by Drift Protocol. Each asset counts towards margin for derivatives trading and has a weight applied to account for their respective volatilities. > For instance, depositing USDC gives users a 1:1 margin for derivatives trading, but depositing SOL (80% asset weight) means that 80% of the value of your SOL at the opening of your position will be available as margin for perpetual futures trading. Margin Parameters[](https://docs.drift.trade/getting-started/cross-collateral-deposits#margin-parameters) ---------------------------------------------------------------------------------------------------------- **Main Pool Asset Weights** | Asset | Initial Asset Weight | Maintenance Asset Weight | Initial Liability Weight | Maintenance Liability Weight | IMF Factor | | --- | --- | --- | --- | --- | --- | | Loading... | | | | | | **JLP Pool Asset Weights** | Asset | Initial Asset Weight | Maintenance Asset Weight | Initial Liability Weight | Maintenance Liability Weight | IMF Factor | | --- | --- | --- | --- | --- | --- | | Loading... | | | | | | **Exponent Pool Asset Weights** | Asset | Initial Asset Weight | Maintenance Asset Weight | Initial Liability Weight | Maintenance Liability Weight | IMF Factor | | --- | --- | --- | --- | --- | --- | | Loading... | | | | | | Initial Asset Weights are also scaled lower based on notional value of total deposits. As a reference, you can check out UI or the SpotMarket `get_scaled_initial_weight_asset` for this scale factor. The IMF Factor acts as a discount on account size: `Initial Asset Weight` on 2000 SOL Collateral (using above) would be: `weight = min (.80, 1.1 / [ 1 + (0.003 * sqrt(2000)] )` `= min(.80, ~.96987) = .80` An asset's liability weight can be converted into an LTV ratio using: `ltv = 1 / liability weight` **Main Pool LTVs** | Asset | Initial LTV | Max LTV | | --- | --- | --- | | Loading... | | | **JLP Pool LTVs** | Asset | Initial LTV | Max LTV | | --- | --- | --- | | Loading... | | | **Exponent Pool LTVs** | Asset | Initial LTV | Max LTV | | --- | --- | --- | | Loading... | | | [Passwordless and Social Login](https://docs.drift.trade/getting-started/passwordless-login "Passwordless and Social Login") [Managing Subaccount](https://docs.drift.trade/getting-started/managing-subaccount "Managing Subaccount") --- # Delegated Accounts – Drift Protocol 👋🏻 Getting Started Delegated Accounts Delegated Accounts ================== What is a Delegated Account?[](https://docs.drift.trade/getting-started/delegated-accounts#what-is-a-delegated-account) ------------------------------------------------------------------------------------------------------------------------ This feature allows users to grant another Solana account limited access to their account on Drift. Users using Drift's account delegation feature may wish to delegate trading execution to a professional trading team. Each subaccount on Drift has its own delegate parameter. ### What can a Delegated Account do?[](https://docs.drift.trade/getting-started/delegated-accounts#what-can-a-delegated-account-do) Delegated authorities on Drift can **ONLY**: * deposit funds; * swap assets; * place and cancel orders. Users can only delegate access to one account or authority. It's important to note that full control over the account remains with the owner. A delegated party can **NOT**: * borrow/withdraw funds; * close the account; and/or * change or remove existing account delegation parameters. * change any settings Delegated authorities are restricted to depositing funds, swapping assets, and placing or canceling orders, therefore limiting their capabilities. All other actions must be carried out by the account owner. ### How do I delegate access to my account?[](https://docs.drift.trade/getting-started/delegated-accounts#how-do-i-delegate-access-to-my-account) To delegate access to another Solana account using Drift's UI, go to the **Overview** tab and click on **Manage Subaccounts**. In this section, you'll find the option to set up a delegate account, as shown in the image below. ![](https://docs.drift.trade/_next/image?url=%2F_next%2Fstatic%2Fmedia%2FPw5LRFtbgBfVuEY_g1P7w_image.d1746033.png&w=640&q=75) Afterwards, you will need to enter the Solana address or account to which you want to delegate access, and then select "confirm." ![](https://docs.drift.trade/_next/image?url=%2F_next%2Fstatic%2Fmedia%2FSOCULv1Rg8jPsY2p7qkpe_image.0bb6a4ce.png&w=3840&q=75) ### Hardware Wallets[](https://docs.drift.trade/getting-started/delegated-accounts#hardware-wallets) If you are using a hardware wallet such as Ledger to connect to Drift via a wallet provider (Phantom, Solflare, Backpack), you may encounter errors when signing certain orders. To ensure a seamless trading experience, we recommend creating a **delegate account**. This allows you to continue trading on Drift, while maintaining the security benefits of using your hardware wallet. Please follow the guide above to set up a delegate account from your hardware wallet. [Managing Subaccount](https://docs.drift.trade/getting-started/managing-subaccount "Managing Subaccount") [Versioned Transactions](https://docs.drift.trade/getting-started/versioned-transactions "Versioned Transactions") --- # Versioned Transactions – Drift Protocol 👋🏻 Getting Started Versioned Transactions Versioned Transactions ====================== [Solana added Versioned Transactions (opens in a new tab)](https://docs.solana.com/developing/versioned-transactions) to enable additional functionality in the Solana Runtime. These changes improved the capabilities of Solana dapps, but they have created some compatibility problems because unfortunately not all products in the ecosystem have integrated them. One of the biggest compatibility problems is in detecting whether a wallet supports versioned transactions or not. For example, WalletConnect has added support for Versioned Transactions, but most\* of the underlying wallets have not. ### Why do I care about versioned transactions?[](https://docs.drift.trade/getting-started/versioned-transactions#why-do-i-care-about-versioned-transactions) If your wallet supports versioned transactions, you don't need to worry and everything on the Drift UI should work as expected without a hiccup (as long as you have versioned transactions enabled in Drift, the default setting). If your wallet does not support versioned transactions, you will currently not be able to use Drift's spot swap functionality, as this feature currently only works with versioned transactions. ### How do I enable versioned transactions in Drift?[](https://docs.drift.trade/getting-started/versioned-transactions#how-do-i-enable-versioned-transactions-in-drift) By default versioned transactions should be enabled, but you can double-check and edit this setting by going to Settings -> Other -> Enable Versioned Transactions ![](https://docs.drift.trade/_next/image?url=%2F_next%2Fstatic%2Fmedia%2FlvtSVVMz9URv0ocBM76zt_screenshot-2023-11-15-at-13654-pm.f2426a98.png&w=3840&q=75) ### How do I know if my wallet supports versioned transactions?[](https://docs.drift.trade/getting-started/versioned-transactions#how-do-i-know-if-my-wallet-supports-versioned-transactions) Probably the easiest way to tell is just to turn versioned transactions on, and test whether you are able to interact and make Drift transactions as expected. If you are, then your wallet supports versioned transactions, if not it doesn't. Your wallet may specify its capabilities in its own documentation. ### Tips for users whose wallets don't support versioned transactions[](https://docs.drift.trade/getting-started/versioned-transactions#tips-for-users-whose-wallets-dont-support-versioned-transactions) If you don't intend on using swaps in Drift, then you should be able to continue to use the product as usual\*. But if you _would_ like to switch to a wallet which does support versioned transactions, then here are some wallets which we can confirm support versioned transactions based on our own testing.\*\*\* * [Phantom (opens in a new tab)](https://phantom.app/) * [Solflare (opens in a new tab)](https://solflare.com/) * [Backpack (opens in a new tab)](https://www.backpack.app/) * [Brave Wallet (opens in a new tab)](https://brave.com/wallet/) * * * \* Based on results of manually testing a range of WalletConnect-supporting wallets. This is by no means exhaustive, and is expected to change over time. \*\* This may change in the future \*\*\* Note : We have not exhaustively checked all wallets, and **this is not an endorsement of the security practises of the wallet provider**. You should do your own research when choosing a wallet. [Delegated Accounts](https://docs.drift.trade/getting-started/delegated-accounts "Delegated Accounts") [Withdraw and Close Account](https://docs.drift.trade/getting-started/withdraw-and-close-account "Withdraw and Close Account") --- # Withdraw and Close Account – Drift Protocol 👋🏻 Getting Started Withdraw and Close Account Withdraw and Close Account ========================== ### Withdraw collateral[](https://docs.drift.trade/getting-started/withdraw-and-close-account#withdraw-collateral) To withdraw collateral, ensure you meet the following requirements: * No open positions. * No open borrows (check your 'Balances' page - opens in a new tab). * No unsettled PnL (settle any PnL before proceeding). You can partially withdraw collateral if you have enough initial free collateral. To check your collateral, refer to your [Account Health Breakdown](https://docs.drift.trade/trading/account-health) . ⚠️ Do not delete your account or subaccounts if you're staking at Insurance Vaults. This may cause difficulty unstaking. 🚫 Referred accounts cannot be deleted. ### Dynamic rent reclaiming[](https://docs.drift.trade/getting-started/withdraw-and-close-account#dynamic-rent-reclaiming) Every account incurs a base account rent of ~0.035 SOL. During periods of high sign-ups (sybil activity), Drift's program adds an excess fee on top of this base rent. For example, a user might pay 0.035 SOL (base rent) + 0.1901 SOL (excess fee) = 0.2251 SOL to create an account. ### Idle Account Deletion[](https://docs.drift.trade/getting-started/withdraw-and-close-account#idle-account-deletion) The Drift Security Council periodically triggers the cleanup of idle accounts in the Drift program. This is done to clear unused space and optimize infrastructure and keeper networks. Authorities of these accounts receive their SOL rent back to their wallets. Accounts eligible for deletion [must be inactive for ~3 months and hold under ~$0.05 in notional value (opens in a new tab)](https://github.com/drift-labs/protocol-v2/blob/d005aae63375f6d8884480f089034a9d6d072d13/programs/drift/src/instructions/keeper.rs#L2138) . Account history will still available through the UI and the account may be re-created by the user at any time. ### Recovering Funds[](https://docs.drift.trade/getting-started/withdraw-and-close-account#recovering-funds) **Excess Fee** Users can reclaim the excess fee after a 7-day waiting period. Click your wallet address in the top right corner, then "Manage." Look for the "reclaimable rent" section and click "Claim" to retrieve any excess fees paid during account creation. ![](https://docs.drift.trade/assets/delete-claim-fee.png) **Base Rent** To reclaim the base rent (0.035 SOL in the example above), you'll need to delete your Drift account. Steps for Deleting Your Account (and Recovering Base Rent): * Click your wallet address in the top right corner. * Click "Manage." * Locate the red trash/bin icon. Alternatively: Go to Overview > Manage Subaccounts. **Important:** Ensure you have no open borrows, unsettled PnL, open positions, or any remaining balances before deleting your account. Withdraw any balances from Drift before proceeding. Clicking the trash/bin icon will permanently delete your account history and instantly redeem your base account rent. No further steps are required. ![](https://docs.drift.trade/assets/delete-trash-bin.png) [Versioned Transactions](https://docs.drift.trade/getting-started/versioned-transactions "Versioned Transactions") [Market Specs](https://docs.drift.trade/trading/market-specs "Market Specs") --- # Perpetual Markets Specs – Drift Protocol 📈 Trading Market Specs Perpetual Markets Specs ======================= Contract Tier[](https://docs.drift.trade/trading/market-specs#contract-tier) ----------------------------------------------------------------------------- Contract tiers are used to categorically label and rank the risk of perpetual markets. There are five unique tiers: * A * B * C * Speculative * Highly Speculative * Isolated These ranked tiers are used for priority access to collateral in liquidations, max limits for insurance, determining acceptable range of oracle price divergence, and sanitization rules for twap / funding rate updates. Fundamentally, a market in Contract Tier B is in a 'safer' tranche vs Contract Tier C, Speculative, and Isolated. As of this update, most markets are currently under 'Contract Tier C', with the following exceptions: A: BTC-PERP B: SOL-PERP, ETH-PERP Speculative: 1MBONK-PERP, 1MPEPE-PERP, WIF-PERP Highly Speculative: W-PERP #### Speculative[](https://docs.drift.trade/trading/market-specs#speculative) Speculative tier has no access to external insurance funds (only the perpetual market's fee pool) #### Highly Speculative[](https://docs.drift.trade/trading/market-specs#highly-speculative) Same restrictions as Speculative, but sits a tranche below. #### Isolated[](https://docs.drift.trade/trading/market-specs#isolated) Isolated tier requires the user account refrain / disable cross margin trading (on both perpetual and spot markets). Users with 'Margin Trading' enabled, a non-USDC borrow, or another perpetual position will NOT be allowed to enter an Isolated Tier market If the account has liabilities beyond the perpetual market's quote asset and the isolated perpetual market, it is forced to enter Reduce Only mode. Oracle Source[](https://docs.drift.trade/trading/market-specs#oracle-source) ----------------------------------------------------------------------------- The oracle provider which provides a price, confidence band, and timeliness information for the market. * Pyth * Switchboard * Prelaunch #### Pyth[](https://docs.drift.trade/trading/market-specs#pyth) [Read more (opens in a new tab)](https://docs.pyth.network/home) #### Switchboard[](https://docs.drift.trade/trading/market-specs#switchboard) [Read more (opens in a new tab)](https://docs.switchboard.xyz/) #### Prelaunch[](https://docs.drift.trade/trading/market-specs#prelaunch) "Prelaunch" is a custom internal oracle source for [Prelaunch Markets](https://docs.drift.trade/trading/prelaunch-markets) (markets without external oracle). For Prelaunch markets, given there is no spot reference price, that oracle sources uses the mark twap as the oracle price. The oracle is also configured with a custom maximum price to prevent price manipulation. This self-referential and leads to funding payments that encourage price stability (those holding positions in trend will pay those holding against trend) and ultimately relies upon market participants anticipating a valid oracle in the future. Every Prelaunch oracle has an initial price AND max price. The oracle value cannot exceed the max price. ### Max Open Interest[](https://docs.drift.trade/trading/market-specs#max-open-interest) A maximum amount of open interest that can exist within the perpetual market. Additional orders/fills that would breach this open interest limit are blocked. ### IMF Factor[](https://docs.drift.trade/trading/market-specs#imf-factor) A margin fraction factor. Used to increase liability weight and decrease asset weight for large positions Spot Markets Specs ================== ### Asset Tier[](https://docs.drift.trade/trading/market-specs#asset-tier) Asset tiers are used to categorically label and rank the risk of a spot markets. There are five unique tiers: * Collateral: full privilege * Protected: collateral, but no borrow * Cross: not collateral, allow multi-borrow * Isolated: not collateral, only single borrow * Unlisted: no privilege ### Scale Initial Asset Weight Start[](https://docs.drift.trade/trading/market-specs#scale-initial-asset-weight-start) The notional value of total user deposits needed to begin scaling down the initial asset weight ### Max Token Deposits[](https://docs.drift.trade/trading/market-specs#max-token-deposits) A maximum amount of tokens that can be added to collateral vault. ### IMF Factor[](https://docs.drift.trade/trading/market-specs#imf-factor-1) A margin fraction factor. Used to increase liability weight and decrease asset weight for large positions ### Order Step/Tick Size[](https://docs.drift.trade/trading/market-specs#order-steptick-size) Spot orders must have base lots which are a multiple of the step size and price lots which are a multiple of tick size [Withdraw and Close Account](https://docs.drift.trade/getting-started/withdraw-and-close-account "Withdraw and Close Account") [Prelaunch Markets](https://docs.drift.trade/trading/prelaunch-markets "Prelaunch Markets") --- # Trading Fees – Drift Protocol 📈 Trading Trading Fees Trading Fees ============ Drift offers a highly competitive fee structure with low taker fees and attractive maker rebates across all tiers, with the potential for even lower fees as trading volume increases. Fees are calculated per trade based on the filled notional position size and are charged in the market's quote asset (USDC), affecting the position's cost basis. If a user holds only non-USDC assets, a USDC borrow may be triggered upon settlement of a loss in perpetual markets (see [P&L](https://docs.drift.trade/profit-loss/profit-loss-intro) ). Drift's tiered fees for futures markets are based on an on-chain calculation of **30-Day Volume**. You can earn discounts on taker fees and extra rebates on maker fees by staking DRIFT. These apply _on top_ of your volume tier. Perp Market Fees[](https://docs.drift.trade/trading/trading-fees#perp-market-fees) ----------------------------------------------------------------------------------- | Tier | 30D Volume | Rookie Taker | Rookie Maker | Champion Taker | Champion Maker | Kickstarter Taker | Kickstarter Maker | Racer Taker | Racer Maker | Elite Taker | Elite Maker | Master Taker | Master Maker | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | 1 | ≤ $2M | 0.0350% | \-0.0025% | 0.0210% | \-0.0035% | 0.0333% | \-0.0026% | 0.0315% | \-0.0028% | 0.0280% | \-0.0030% | 0.0245% | \-0.0033% | | 2 | \> $2M | 0.0300% | \-0.0025% | 0.0180% | \-0.0035% | 0.0285% | \-0.0026% | 0.0270% | \-0.0028% | 0.0240% | \-0.0030% | 0.0210% | \-0.0033% | | 3 | \> $10M | 0.0275% | \-0.0025% | 0.0165% | \-0.0035% | 0.0261% | \-0.0026% | 0.0248% | \-0.0028% | 0.0220% | \-0.0030% | 0.0193% | \-0.0033% | | 4 | \> $20M | 0.0250% | \-0.0025% | 0.0150% | \-0.0035% | 0.0238% | \-0.0026% | 0.0225% | \-0.0028% | 0.0200% | \-0.0030% | 0.0175% | \-0.0033% | | 5 | \> $80M | 0.0225% | \-0.0025% | 0.0135% | \-0.0035% | 0.0214% | \-0.0026% | 0.0203% | \-0.0028% | 0.0180% | \-0.0030% | 0.0158% | \-0.0033% | | VIP | \> $200M | 0.0200% | \-0.0025% | 0.0120% | \-0.0035% | 0.0190% | \-0.0026% | 0.0180% | \-0.0028% | 0.0160% | \-0.0030% | 0.0140% | \-0.0033% | ### Fee Benefits via DRIFT Staking[](https://docs.drift.trade/trading/trading-fees#fee-benefits-via-drift-staking) Earn **additional discounts on taker fees** and **extra rebates on maker fees** by staking DRIFT. These stack on top of your volume tier. These benefits only apply to perp fees. | Tier | DRIFT Staked | Taker Fee Discount | Maker Fee Rebate | | --- | --- | --- | --- | | Rookie | 0 | 0% | 0% | | Kickstarter | 1,000 | –5% | +5% | | Racer | 10,000 | –10% | +10% | | Elite | 50,000 | –20% | +20% | | Master | 100,000 | –30% | +30% | | Champion | 250,000 | –40% | +40% | **Examples:** * _A Tier 3 taker (0.0275%) with 20% staking discount pays 0.022% effective fee._ * _A maker (–0.0025% rebate) with 20% staking gets –0.003% rebate._ Spot Market Fees[](https://docs.drift.trade/trading/trading-fees#spot-market-fees) ----------------------------------------------------------------------------------- | Tier | Maker Fee | Taker Fee | Referree Taker Discount | Referrer Reward | Filler Reward | | --- | --- | --- | --- | --- | --- | | 1 | \-2 bps | 5 bps | 0% | 0% | 10% | Fee-Adjusted Markets[](https://docs.drift.trade/trading/trading-fees#fee-adjusted-markets) ------------------------------------------------------------------------------------------- _Some markets offer additional discounts, these are part of a temporary campaign, and be will subject to change in the future._ ### Perp Markets[](https://docs.drift.trade/trading/trading-fees#perp-markets) | Market | Fee Adjustment | | --- | --- | | BTC-PERP | \-100% (discount) | | ETH-PERP | \-100% (discount) | ### Spot Markets[](https://docs.drift.trade/trading/trading-fees#spot-markets) | Market | Fee Adjustment | | --- | --- | | PYTH | +100% (premium) | | JTO | +100% (premium) | | WIF | +100% (premium) | | JUP | +100% (premium) | | W | +100% (premium) | | TNSR | +100% (premium) | | DRIFT | +100% (premium) | | POPCAT | +100% (premium) | | MOTHER | +100% (premium) | | Bonk | +100% (premium) | | AI16Z | +100% (premium) | | MELANIA | +100% (premium) | * * * ### Drift staking benefits[](https://docs.drift.trade/trading/trading-fees#drift-staking-benefits) The fee benefits via DRIFT staking only apply to perpetual contract fees. ### Taker Fees (High Leverage Mode)[](https://docs.drift.trade/trading/trading-fees#taker-fees-high-leverage-mode) If a user has High Leverage Mode turned on, taker trading fees for all perp markets will be 2x the bottom fee tier. ### Referee Discount / Referer Reward[](https://docs.drift.trade/trading/trading-fees#referee-discount--referer-reward) These apply to accounts that were signed up using a referred account. These percentages are applied to the effective taker fee paid. ### Filler Reward[](https://docs.drift.trade/trading/trading-fees#filler-reward) Filler rewards are variable but up to 10% of the effective taker fee paid by the user. See [Keeper Incentives](https://docs.drift.trade/about-v2/keeper-incentives) . ### Fee Adjustments[](https://docs.drift.trade/trading/trading-fees#fee-adjustments) Longer tail assets can have increased fees to stay in line with external markets fee schedules. Some markets will periodically have flat discounts applied to all fee tiers. [See Fee-Adjusted Markets](https://docs.drift.trade/trading/trading-fees#fee-adjusted-markets) ### Disclaimers[](https://docs.drift.trade/trading/trading-fees#disclaimers) _Drift Protocol reserves the right to end the promotional period and the Taker Incentive Program at any time. If the Drift Protocol chooses to do so, it will provide notice to participating users, but such notice is not required in order to conclude the program early or extend the program. Please note that the terms and conditions of this program are subject to change without notice._ _There are risks associated with Insurance Fund Staking. Read more about the [Insurance Fund Staking](https://docs.drift.trade/insurance-fund/insurance-fund-staking) and [Risks](https://docs.drift.trade/security/risks) )._\*\* [Auction Parameters](https://docs.drift.trade/trading/auction-parameters "Auction Parameters") [Other Trading Fees](https://docs.drift.trade/trading/other-trading-fees "Other Trading Fees") --- # Fee Pool – Drift Protocol 📈 Trading Fee Pool Fee Pool ======== Both Perpetual and Spot Markets have Fee Pools. Fee pools are set up to accumulate a fraction of exchange fees to eventually be sent to the associated Revenue Pool. Perpetual Market Fee Pool can be utilized for bankruptcy resolution after its insurance fund threshold is reached. [Other Trading Fees](https://docs.drift.trade/trading/other-trading-fees "Other Trading Fees") [Versioned Transactions](https://docs.drift.trade/trading/versioned-transactions "Versioned Transactions") --- # Block Conditions – Drift Protocol 📈 Trading Block Conditions Block Conditions ================ ### Deposits[](https://docs.drift.trade/trading/block-conditions#deposits) * user attempting to deposit when the max\_deposits for that spot asset would be or has been reached * spot market is in reduce only mode and deposit does not pay off a borrow ### Withdraws[](https://docs.drift.trade/trading/block-conditions#withdraws) * user attempting to withdraw with outstanding liabilities when an oracle is invalid * attempting to borrow or withdraw when there are outstanding liabilities and any asset or liability's Oracle the user has is deemed invalid ("invalid" in accordance with _`MarginCalc`_ action) * user attempting to increase the number of liabilities above 1 with an isolated tier liability * users can only have one outstanding liability when the liability has the isolated asset tier. * users cannot withdraw assets that would put their total collateral (weighted collateral value) below their initial margin requirement * users cannot withdraw an asset amount that would put that particular asset's protocol liquidity below the rolling limits * these limits differ based on whether the withdraw would open borrow or not ### Placing Orders[](https://docs.drift.trade/trading/block-conditions#placing-orders) * users cannot place orders that are risk-increasing and would put their initial margin requirement above their total collateral * users cannot place orders that would increase their number of outstanding liabilities above 1 if the liability has the isolated asset tier * \[SPOT ONLY\] without margin trading enabled on an account, users won't be able to open spot orders than would create borrows on the account * \[SPOT ONLY\] with margin trading enabled, users won't be able to borrow using the same rolling limits for withdraws ### Filling Orders[](https://docs.drift.trade/trading/block-conditions#filling-orders) * a user's orders will not fill if it sends them under the margin requirement plus buffer (since they have \`InsufficientCollateral\`) * within a match, if either user hits this condition, the match won't go through ### Settle Perp PnL[](https://docs.drift.trade/trading/block-conditions#settle-perp-pnl) * when market's oracle is deemed invalid * when user account value is below the maintenance margin requirement * when AMM repeg cost exceeds budget [Versioned Transactions](https://docs.drift.trade/trading/versioned-transactions "Versioned Transactions") [Oracles](https://docs.drift.trade/trading/oracles "Oracles") --- # Versioned Transactions – Drift Protocol 📈 Trading Versioned Transactions Versioned Transactions ====================== [Solana added Versioned Transactions (opens in a new tab)](https://docs.solana.com/developing/versioned-transactions) to enable additional functionality in the Solana Runtime. These changes improved the capabilities of Solana dapps, but they have created some compatibility problems because unfortunately not all products in the ecosystem have integrated them. One of the biggest compatibility problems is in detecting whether a wallet supports versioned transactions or not. For example, WalletConnect has added support for Versioned Transactions, but most\* of the underlying wallets have not. ### Why do I care about versioned transactions?[](https://docs.drift.trade/trading/versioned-transactions#why-do-i-care-about-versioned-transactions) If your wallet supports versioned transactions, you don't need to worry and everything on the Drift UI should work as expected without a hiccup (as long as you have versioned transactions enabled in Drift, the default setting). If your wallet does not support versioned transactions, you will currently not be able to use Drift's spot swap functionality, as this feature currently only works with versioned transactions. ### How do I enable versioned transactions in Drift?[](https://docs.drift.trade/trading/versioned-transactions#how-do-i-enable-versioned-transactions-in-drift) By default versioned transactions should be enabled, but you can double-check and edit this setting by going to Settings -> Other -> Enable Versioned Transactions ![](https://docs.drift.trade/_next/image?url=%2F_next%2Fstatic%2Fmedia%2FlvtSVVMz9URv0ocBM76zt_screenshot-2023-11-15-at-13654-pm.f2426a98.png&w=3840&q=75) ### How do I know if my wallet supports versioned transactions?[](https://docs.drift.trade/trading/versioned-transactions#how-do-i-know-if-my-wallet-supports-versioned-transactions) Probably the easiest way to tell is just to turn versioned transactions on, and test whether you are able to interact and make Drift transactions as expected. If you are, then your wallet supports versioned transactions, if not it doesn't. Your wallet may specify its capabilities in its own documentation. ### Tips for users whose wallets don't support versioned transactions[](https://docs.drift.trade/trading/versioned-transactions#tips-for-users-whose-wallets-dont-support-versioned-transactions) If you don't intend on using swaps in Drift, then you should be able to continue to use the product as usual\*. But if you _would_ like to switch to a wallet which does support versioned transactions, then here are some wallets which we can confirm support versioned transactions based on our own testing.\*\*\* * [Phantom (opens in a new tab)](https://phantom.app/) * [Solflare (opens in a new tab)](https://solflare.com/) * [Backpack (opens in a new tab)](https://www.backpack.app/) * [Brave Wallet (opens in a new tab)](https://brave.com/wallet/) * * * \* Based on results of manually testing a range of WalletConnect-supporting wallets. This is by no means exhaustive, and is expected to change over time. \*\* This may change in the future \*\*\* Note : We have not exhaustively checked all wallets, and **this is not an endorsement of the security practises of the wallet provider**. You should do your own research when choosing a wallet. [Fee Pool](https://docs.drift.trade/trading/fee-pool "Fee Pool") [Block Conditions](https://docs.drift.trade/trading/block-conditions "Block Conditions") --- # Oracles – Drift Protocol 📈 Trading Oracles Oracles ======= Drift Protocol has a number of resiliency checks around new oracle data as well as updates an oracle twap for its margin risk engine. Each market tracks the last seen oracle values and updates an EMA of TWAP for over both 1hr (funding period) and 5min intervals. Drift utilises as an oracle source. The protocol has the flexibility to update and customize as necessary on a per-market basis. ### Validity Checks[](https://docs.drift.trade/trading/oracles#validity-checks) For robustness, Drift's program checks oracle validity. The validity is evaluated on a per-check and action basis to determine whether to block actions. See [Protocol Guard Rails](https://docs.drift.trade/risk-and-safety/protocol-guard-rails) for more details. 1\. Stale(ForAmm/ForMargin): (last slot update too far behind the current slot, **10/120 slots**) 2\. InvalidPrice: Negative price (any price field **< 0**) 3\. TooVolatile: (TWAP / price ratio out of bounds, **5x or 1/5x**) 4\. TooUncertain: Confidence interval is too large (confidence if a very large percentage of the price, **\>10%**) **When the oracle for a Perpetuals Market is deemed invalid, the market can block some order fills, withdraws, liquidations, and funding rate updates (if they increase protocol risk).** **For the duration of the invalid period, on-chain oracle TWAP calculation aims to shrink toward mark TWAP to avoid erroneous funding payment magnitudes.** [Block Conditions](https://docs.drift.trade/trading/block-conditions "Block Conditions") [Introduction to Profit & Loss](https://docs.drift.trade/profit-loss/profit-loss-intro "Introduction to Profit & Loss") --- # Introduction to Profit & Loss – Drift Protocol 💸 Profit & Loss (P&L) Introduction to Profit & Loss Introduction to Profit & Loss ============================= This guide explains how to track your Profit and Loss (P&L or PnL) on Drift to understand the performance of your open positions in perpetual markets. ### What is P&L?[](https://docs.drift.trade/profit-loss/profit-loss-intro#what-is-pl) P&L reflects the potential profit or loss on your open positions. It's a dynamic value that changes based on the current market price of the underlying asset compared to your average entry price. In simpler terms, it indicates whether your positions are currently trending towards profit or loss. ![](https://docs.drift.trade/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpnl-positions.abb641ba.png&w=3840&q=75) A user's current position on Drift is the cumulative sum of all their filled orders (increasing, reducing, or closing) over time. All trading lots, per market and per subaccount, are combined into a single position to determine P&L. The P&L in the table above is calculated as the difference between the position's `Entry Price` with the current mark price (can toggle to oracle price) multiplied by the `Size` (view can be switched between $ and %). ⚠️ P&L in the _Positions_ tab is **unrealised P&L** (uP&L) and as such doesn't represent actual withdrawable amount (claimed and settled P&L). Read the [Types of P&L](https://docs.drift.trade/profit-loss/profit-loss-intro#types-of-pl) for more details. ### Types of P&L[](https://docs.drift.trade/profit-loss/profit-loss-intro#types-of-pl) * `Unrealised P&L (uP&L)`: Potential profit or loss on open positions based on current market price vs. your entry price. It fluctuates with the market. * `Settled P&L`: Actual realised profit and loss (can be settled without closing the position). * `Claimable / Unsettled P&L`: Claimable P&L represents the portion of unsettled P&L that is available to be claimed at this moment. It is possible to have unsettled P&L that is not claimable due to insufficient funds in the P&L Pool, invalid oracle, or other reasons. ![](https://docs.drift.trade/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpnl-unsettled.9883a17a.png&w=3840&q=75) ⬇️ For example: 1. You open a position (e.g., buying BTC-PERP) creating **unsettled P&L** of $0 (no initial change). Unsettled P&L reflects the potential profit or loss based on the current oracle price compared to your average entry price. _Note:_ Immediately after you place a position, unsettled P&L can appear as positive or negative due to market trading above or below oracle price. 2. As the price moves, the difference between the current oracle price and your cost basis creates **claimable / unsettled P&L**. This is the potential profit or loss on your open position. 3. When you try to close the position, closing price is used to calculate your realised P&L. This is the actual profit or loss you lock in, based on the difference between the closing price and your cost basis. This portion becomes **settled P&L**, which you can then withdraw to your USDC balance. Withdrawing your profits (settled P&L) depends on the P&L pool. If the pool has enough funds, your profits are available right away. If not, you might need to wait for others to settle their losses before you can withdraw your profits. 4. You decide to close your position by selling all or part of your contract. The closing price is used to calculate your **realised P&L**. This is the actual profit or loss you lock in, based on the difference between the closing price and your cost basis. 5. Settled P&L (a portion of realized P&L) becomes available for **withdrawal** from the [P&L pool](https://docs.drift.trade/profit-loss/profit-loss-pool) if the pool has enough funds. If not, you might need to wait for others to settle their losses before you can withdraw your profits. **What is the difference between Settling P&L and Realising P&L?** The key difference lies in the availability for withdrawal: * Realised P&L doesn't automatically guarantee immediate withdrawal. You need sufficient settled funds in the Market's P&L Pool, which comes from accumulated settled losses from other users. * Settled P&L is the realised profit that's already been processed and added to the pool. This is the portion you can withdraw immediately. ### P&L Settlement and Withdrawal[](https://docs.drift.trade/profit-loss/profit-loss-intro#pl-settlement-and-withdrawal) * Settling P&L moves profit/loss from a perpetual market to your USDC balance. * Requires claiming settled P&L before withdrawal. * P&L pool liquidity determines if settled [P&L pool](https://docs.drift.trade/profit-loss/profit-loss-pool) is claimable immediately. ⚠️ **Withdrawing realised P&L requires settling/claiming it first.** Closing your position realizes your P&L, but it doesn't automatically make it available for withdrawal. ### Claiming Settled P&L[](https://docs.drift.trade/profit-loss/profit-loss-intro#claiming-settled-pl) 1. Navigate to the "Unsettled P&L" tab. 2. Select "Claim" for specific positions or "Claim All". ![](https://docs.drift.trade/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fpnl-claim.a842ac37.png&w=3840&q=75) Users can claim positive P&L when: 1. the open position has been closed or reduced (i.e. your uP&L has been partially or wholly realised); _note: this step is only necessary when the P&L pool balance is limited_ 2. the market's P&L Pool has available balances to claim; and 3. their Cost Basis is below the Entry Price for longs or above the Entry Price for shorts. ⚠️ **Automatic P&L Settlement** P&L settlement is a permissionless action - anyone could settle two account's P&Ls at any time. Settling the P&L will improve the accounts health. [Oracles](https://docs.drift.trade/trading/oracles "Oracles") [Accounting and Settlement](https://docs.drift.trade/profit-loss/accounting-settlement "Accounting and Settlement") --- # Accounting & Settlement – Drift Protocol 💸 Profit & Loss (P&L) Accounting and Settlement Accounting & Settlement ======================= Within Drift Protocol, all token deposits are held in a global collateral vault. This is required for seamless cross-margin and borrow-lend. The only exception to this is the insurance fund vault residing outside. Ensuring proper accounting across users requires a robust settlement mechanism. The protocol uses intermediate Pool Balances to facilitate transfers and ensure that claimed gains are required to come from settled offsetting losses. ![High Level Architecture](https://docs.drift.trade/_next/image?url=%2F_next%2Fstatic%2Fmedia%2F7o9CDj7ho4pmKHiTI8_aD_img9824.3df796fd.png&w=3840&q=75) ### Perpetual Market[](https://docs.drift.trade/profit-loss/accounting-settlement#perpetual-market) An individual perpetual market has two pools: A. P&L Pool: to accumulate funds from users with losses for settlement to users with profits B. Fee Pool: to accumulate a fraction of exchange fees for the Quote Spot Market's Revenue Pool The P&L Pool receives the highest priority on claimed funds, in order to give user's the best possible experience. The default fraction of exchange fees for the Fee Pool is `total_exchange_fee / 2` and this fraction is determined by: `SHARE_OF_FEES_ALLOCATED_TO_CLEARING_HOUSE`. ⬇️ The Fee Pool will only get partially filled up by up to 1% of intermediate P&L settled from a user's losses and aggressively drawn down for the benefit of the P&L Pool otherwise. ### Spot Market[](https://docs.drift.trade/profit-loss/accounting-settlement#spot-market) An individual spot market has two pools: A. Revenue Pool: to accumulate revenue across the protocol, denominated in this token B. Fee Pool: to pay fillers and settle portions to the revenue pool The Revenue Pool can collect fees from: * Borrow interest * Liquidations * Perpetual Markets and can pay out to: * Insurance Fund Stakers * Perpetual Markets (see details of these rules in [Revenue Pool](https://docs.drift.trade/about-v2/revenue-pool) ) The Fee Pool collects exchange fees from swaps and uses them to pay out the Keeper Network [Keepers & Decentralised Orderbook](https://docs.drift.trade/about-v2/keepers-decentralized-orderbook-faq) ### Future Work[](https://docs.drift.trade/profit-loss/accounting-settlement#future-work) Currently, a Perpetuals Market can only pull from the Spot Market Revenue Pool and Insurance Fund for its quote currency. * In the future, it may be possible for a distressed associative perp market (BTC-PERP) to be able to pull funds from the associated spot market (BTC) revenue/insurance pool and immediately swap for USDC to top off its fee/P&L pool. [Introduction to Profit & Loss](https://docs.drift.trade/profit-loss/profit-loss-intro "Introduction to Profit & Loss") [What is unsettled P&L?](https://docs.drift.trade/profit-loss/what-is-unsettled-profit-loss "What is unsettled P&L?") --- # What is unsettled P&L? – Drift Protocol 💸 Profit & Loss (P&L) What is unsettled P&L? What is unsettled P&L? ====================== ### Settling P&L[](https://docs.drift.trade/profit-loss/what-is-unsettled-profit-loss#settling-pl) Settling P&L refers to settling the total funds available in the per-market pool of funds that users can claim. This pool is called the **P&L Pool** (read more here: [Accounting and Settlement](https://docs.drift.trade/profit-loss/accounting-settlement) ). A trader that has made a profitable trade and realises its profits may wish to withdraw that realised profit. However, users can only withdraw realised profits if there is enough settled P&L available in the P&L Pool. The P&L Pool is comprised of all the accumulated realised losses of other participants in that market. It represents the total amount available for withdrawal. For each dollar to be withdrawn from realised profits, there must also be a corresponding dollar of realised losses (which will be made available in the P&L Pool). This mechanism exists to ensure that users do not withdraw more from the platform than what actually exists. If a user made a profitable trade and has a positive realised P&L from the position, but there isn't enough Settled P&L in the Per-Market P&L pool to pay out the user to withdraw, the user may need to wait for the pool to be replenished by settled losses. When this occurs, the user's P&L will be considered to be **unsettled P&L.** For more information on what happens when there is not enough Settled P&L, read [P&L Pool](https://docs.drift.trade/profit-loss/profit-loss-pool) . ### Margining of Unsettled P&L[](https://docs.drift.trade/profit-loss/what-is-unsettled-profit-loss#margining-of-unsettled-pl) If positive P&L is unsettled, it may account for less initial margin for trading perpetuals than USDC. Please see the treatment of non-USD assets here [Cross-Collateral Deposits](https://docs.drift.trade/getting-started/cross-collateral-deposits) . Each market has a maximum imbalanced P&L limit. When the net user P&L in a market breaches the limit, the asset weight will be decreased. Additionally, P&L in excess of the limit is subject to deficit resolutions from the Insurance Fund (up to the market's max insurance fund limit). ℹ️ Discounting the unsettled P&L lowers the maximum leverage extended for users (and only decreases a user's initial margin). These guards don't lower the maintenance margin weights and are not relevant for liquidations. ### Withdrawals[](https://docs.drift.trade/profit-loss/what-is-unsettled-profit-loss#withdrawals) Only the lesser value of your Free Collateral and Asset Balance will be available for withdrawal (without opening a borrow). Realising positive unrealised P&L (by reducing/closing positions) will allow for that P&L to be settled to your Asset Balance for withdrawal. ℹ️ A suggestion for users that want to stay in their position and withdraw unrealised profits in excess of their asset balance is to reduce/close then reopen the position. Read more in [Glossary](https://docs.drift.trade/glossary) . [Accounting and Settlement](https://docs.drift.trade/profit-loss/accounting-settlement "Accounting and Settlement") [P&L Pool](https://docs.drift.trade/profit-loss/profit-loss-pool "P&L Pool") --- # P&L Pool – Drift Protocol 💸 Profit & Loss (P&L) P&L Pool P&L Pool ======== Any account can call the `settlePNL` instruction, which will trigger negative P&L accounts to be settled, adding to each per-market P&L pool. Negative P&L being settled increases the amount available to be settled, whilst positive P&L being settled decreases the amount available for settlement. ![](https://docs.drift.trade/_next/image?url=%2F_next%2Fstatic%2Fmedia%2F8bAYsBqUpelsCx7xgTblP_drift-pandl-settlement-mechanism-banner-v2-1.2941ce0f.png&w=3840&q=75) **_Note_**: calling `settlePNL` does not affect open positions. The function only settles the funds available in the PNL Pool for withdrawal. It's important to recognise the difference between **settling P&L** and **realising P&L** (read more here: [Introduction to Profit & Loss](https://docs.drift.trade/profit-loss/profit-loss-intro) ). ### Calling `settlePNL`[](https://docs.drift.trade/profit-loss/profit-loss-pool#calling-settlepnl) Any account can call `settlePNL` instruction. Once called, all unrealised P&L will be settled and added to (or subtracted from) the market's P&L Pool to be made available for withdrawal. Users with open positions that have negative unrealised P&L will have their unrealised P&L settled and sent to the P&L Pool; **however, their position will be unaffected**. As users are settled against, the Cost Basis for their position will be adjusted so that their position remains unchanged even though a portion of their unrealised negative P&L has been realised and sent to the P&L Pool. The P&L settled as a result of the `settlePNL` instruction will be reflected in the`Unrealised P&L` tab, specifically within the`Realised P&L` column. The adjusted cost basis for the position is reflected in the `Cost Basis` column. ![](https://docs.drift.trade/_next/image?url=%2F_next%2Fstatic%2Fmedia%2FL1J0T17SoiEsYYH8FO8MJ_image.03a14106.png&w=3840&q=75) [What is unsettled P&L?](https://docs.drift.trade/profit-loss/what-is-unsettled-profit-loss "What is unsettled P&L?") [What is Liquidation?](https://docs.drift.trade/liquidations/liquidations "What is Liquidation?") --- # What is lending and borrowing? – Drift Protocol 🏦 Lend & Borrow What is lending and borrowing? What is lending and borrowing? ============================== Drift Protocol is also a decentralised money markets protocol that supports the borrowing and lending of assets. As a decentralised money markets protocol, you can: * deposit assets into Drift Protocol and earn yield; or * borrow assets deposited by other Lenders at a variable interest rate. Lenders provide liquidity to the market to earn yield on their assets, while borrowers are able to borrow from available liquidity pools in an over-collateralised fashion. Any interest earned from lending is vested immediately and automatically compounds. You can view current lend and borrow interest rates in the Drift app at [https://app.drift.trade/earn (opens in a new tab)](https://app.drift.trade/earn) [Liquidators](https://docs.drift.trade/liquidations/liquidators "Liquidators") [Supply & Borrow APY](https://docs.drift.trade/lend-borrow/supply-borrow-apy "Supply & Borrow APY") --- # Liquidators – Drift Protocol 💀 Liquidations Liquidators Liquidators =========== Liquidations act as position transfers between accounts. Liquidator accounts thus need to be collateralised in order to satisfy the transfer's initial margin requirements. There are four instructions pertaining to liquidations: | Instruction | Details | | --- | --- | | liquidate\_perp | Liquidator takes over user perpetual positions at a discount. | | liquidate\_borrow | Liquidator takes over borrow at a discount to the deposit value. | | liquidate\_borrow\_for\_perp\_pnl | Liquidator takes over borrow for discount P&L. | | liquidate\_perp\_pnl\_for\_deposit | Liquidator takes over negative P&L for discounted deposit. | Bankruptcy (see [Insurance Fund](https://docs.drift.trade/insurance-fund/insurance-fund-intro) ) is possible if you still have outstanding liabilities and no further assets after liquidation. Liquidators are open-sourced and can be triggered by anybody running a liquidator bot. Liquidators, also known as Keepers, will have their collateral reward credited to their Drift account. Liquidations will be triggered and positions will be liquidated based on oracle price, not the mark price of the exchange. The user's trade price at liquidation for a perpetual position will be based on the oracle price + the penalty / fee that is set per market. 🚫 **In the case of an extreme oracle error: the market will pause most fills, liquidations, and funding rate updates.** If you would like to run a liquidator bot, see [Tutorial: Liquidation Bot](https://docs.drift.trade/tutorial-bots/keeper-bots/tutorial-liquidation-bot) [What is Liquidation?](https://docs.drift.trade/liquidations/liquidations "What is Liquidation?") [What is lending and borrowing?](https://docs.drift.trade/lend-borrow/what-is-lend-borrow "What is lending and borrowing?") --- # Supply and Borrow APY – Drift Protocol 🏦 Lend & Borrow Supply & Borrow APY Supply and Borrow APY ===================== Drift's Borrow and Lend products allow users that deposit collateral into the platform to automatically earn interest. Interest is calculated on the sum of all collateral deposited and settled and is continually paid into user accounts. Users can also borrow against their collateral to initiate a withdrawal. ℹ️ Spot deposit/borrow interest is paid out continuously and directly to the spot balance. There are no records of interest paid/received or cumulative interest. * * * ### Supply APY[](https://docs.drift.trade/lend-borrow/supply-borrow-apy#supply-apy) All deposits on Drift, both perpetuals and in Drift's borrow & lend markets, will earn interest. The annualised percentage yield (APY) differs per market and is displayed on the platform's UI. ![](https://docs.drift.trade/_next/image?url=%2F_next%2Fstatic%2Fmedia%2FIjPTQ7BZXMIhgNOt8IhYf_image.27dc9d02.png&w=3840&q=75) APY is auto-compounding from the time of deposit and is calculated on the user's total settled collateral. Since assets supplied to Drift's borrow & lend can also be cross-margined to use for perpetual futures trading, users will earn interest on both their deposits and on their positions. The Supply APY is a function of the utilisation ratio which is calculated: `Total Borrowed / Total Deposits` The interest rate will slowly increase to an optimal ratio of X% and will increase above that in order to encourage the market to deposit more funds. ### Borrow APY[](https://docs.drift.trade/lend-borrow/supply-borrow-apy#borrow-apy) Users must pay a Borrow APY to the pool when borrowing assets. This interest payment is then distributed to lenders via the Supply APY. Drift's interest rate is calibrated to manage liquidity risk and optimise asset utilisation. The formula for the borrow interest rates can be found at [Borrow Interest Rate](https://docs.drift.trade/lend-borrow/borrow-interest-rate) . The Borrow APY for each asset is shown on the UI. There is no 'deadline' for loans to be repaid. The interest owed will accrue over time and you can repay whenever you're ready. ![](https://docs.drift.trade/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fy_D7XVjmDvigSgXyl_n0e_image.a9f7d95d.png&w=3840&q=75) [What is lending and borrowing?](https://docs.drift.trade/lend-borrow/what-is-lend-borrow "What is lending and borrowing?") [Borrow Interest Rate](https://docs.drift.trade/lend-borrow/borrow-interest-rate "Borrow Interest Rate") --- # Liquidations – Drift Protocol 💀 Liquidations What is Liquidation? Liquidations ============ ⚠️ Trading on leverage can be risky. Make sure you are aware of the liquidation rules outlined below before applying margin. What are Liquidations?[](https://docs.drift.trade/liquidations/liquidations#what-are-liquidations) --------------------------------------------------------------------------------------------------- Liquidations are a part of leveraged trading. Traders that elect to use leverage are using the collateral they deposited as margin to borrow money from the protocol. Traders may choose to do this in order to open a larger position and have more exposure to a particular asset, i.e. _leveraged exposure_. When this occurs, the protocol must protect itself by ensuring that there is enough margin for the position to settle any losses that occur. There is a prescribed minimum ratio between a position's value and its margin for each asset (**Minimum Maintenance Margin**). If a position drops below its Minimum Maintenance Margin, liquidators are incentivized by the protocol to take over positions so a user's remaining collateral may settle the losses that have occurred. Read [Insurance Fund](https://docs.drift.trade/insurance-fund/insurance-fund-intro) for what happens when prices move rapidly and/or liquidations don't happen in time. How do Liquidations work? ========================= In the Drift v2 margin system, all positions within a subaccount (deposits, borrows, and perpetuals positions) are cross-margined. As such, liquidations are calculated based on your account level leverage rather than isolated to the leverage present in your perpetuals and/or borrow account. You can be liquidated when your `totalCollateral` becomes less than your`maintenanceMarginRequirement`. Your total collateral is the weighted value of your deposits and perp pnl. Your margin requirement is the weighted value of your borrows and perp positions. Once your total collateral value falls below your margin requirement, liquidations will first cancel any open orders + LP positions. After this, until your account's total collateral is above the `maintenanceMarginRequirement + liqBufferRatio` liquidators can iteratively liquidate any portion of assets and liabilities over a throttled time window (to avoid single price instance from a heavily deleveraging account). The `liqBufferRatio` is set on the Drift State Account and is meant to sufficiently bring an account away from the liquidation boundary but not heavily punish users. The `Health` measure on the user page can help visualise how close a user is to liquidation territory. At 0 Health, a user can get liquidated. `Health = 100% - maint. margin / total collateral` The user's trade price at liquidation for a perpetual position will be based on the oracle price. The penalty / fee that is set per market, likely above the normal taker fee, in order to give the liquidator a rebate. Liquidations triggered and positions will be liquidated using margin engine prices. 🚫 **In the case of an extreme oracle error: the market will pause most fills, liquidations, and funding rate updates.** ⬇️ **Example:** You deposit 500 USDC and you long 200 SOL-PERP at $25 Your position value is $5000 USDC and your margin/collateral is $500 USDC, you have 10x leverage Note that the Minimum Maintenance Margin for a SOL-PERP is 3% (see Minimum Maintenance Margin for assets here: [Margin](https://docs.drift.trade/trading/margin) ) Your total collateral is `$500 * 1.00 = $500` and your margin requirement is `$5000 * .05 = 250` You are liquidated if the price of SOL decreases by 5.28% to $23.6825. This is because your perp pnl is `200 * $25 * -.0527 = -263.5` and thus your total collateral is `$500 - 263.5 = $236.5`while your margin requirement is `$23.6825 * 200 * .05 = $236.825`. Being a Liquidator ================== Read [Liquidators](https://docs.drift.trade/liquidations/liquidators) if you want to learn more about being a liquidator on the platform. Liquidators earn a fee for their services. [P&L Pool](https://docs.drift.trade/profit-loss/profit-loss-pool "P&L Pool") [Liquidators](https://docs.drift.trade/liquidations/liquidators "Liquidators") --- # Lend Borrow FAQ – Drift Protocol 🏦 Lend & Borrow Lend & Borrow FAQ Lend Borrow FAQ =============== **Can the same collateral be used to trade perpetuals?** * Yes it can, up to the margin requirement. **How does interest get charged on borrows?** * Interest automatically accrues to the account. Interest is paid in the same currency as the currency borrowed. **Are there any fees on borrows?** * There is no borrow initiation fee. * Each spot market has a `total_if_factor` which allocates a portion of interest collected from borrows to the insurance fund. **Are there any risks to lending?** * Yes, there is always the risk of _borrower default_. When there is not enough insurance available, the losses will be socialised across depositors. To help mitigate the risks, the protocol imposes prudent requirements and guards around borrows. **Where are borrows withdrawn to?** * Borrows are withdrawn to your wallet **Why can I not borrow a particular asset?** * If you've deposited an asset as collateral (say USDC or SOL); you can't borrow that asset until you have fully withdrawn it from the platform. **What is the LTV limit for borrows against SOL?** * 83% **What is the initial LTV?** * `1 / initial liability weight` * For `initial liability weight` for listed assets, see [Cross-Collateral Deposits](https://docs.drift.trade/getting-started/cross-collateral-deposits) **What is the maintenance LTV?** * `1/ maintenance liability weight` * For `maintenance liability weight` for listed assets, see [Cross-Collateral Deposits](https://docs.drift.trade/getting-started/cross-collateral-deposits) [Borrow Interest Rate](https://docs.drift.trade/lend-borrow/borrow-interest-rate "Borrow Interest Rate") [Isolated Pools](https://docs.drift.trade/lend-borrow/isolated-pools "Isolated Pools") --- # Borrow Interest Rate – Drift Protocol 🏦 Lend & Borrow Borrow Interest Rate Borrow Interest Rate ==================== Drift's lending pools use a borrow interest rate model inspired by [Aave (opens in a new tab)](https://docs.aave.com/risk/liquidity-risk/borrow-interest-rate) . Each spot market defines: * A **minimum rate** `R_min` * An **optimal rate** `R_opt` at a target utilization `U*` * A **maximum rate** `R_max` at full utilization The borrow interest rate is a function of utilization (U), or how much capital in the pool is currently lent out. ### Utilization Rate and Liquidity[](https://docs.drift.trade/lend-borrow/borrow-interest-rate#utilization-rate-and-liquidity) * If **U** is high -> there is abundant capital within the system and the protocol users are given incentives in the form of low-interest rates to encourage borrowing * If **U** is low -> capital within the system is scarce and the protocol will increase interest rates to incentivise more capital supply and repayment of debt. ### Multi-Kink Interest Rate Model[](https://docs.drift.trade/lend-borrow/borrow-interest-rate#multi-kink-interest-rate-model) To balance capital efficiency with liquidity protection, Drift uses a **multi-kink model**. This allows linear rates up to the optimal utilization point, and then introduces increasingly steeper rate hikes as utilization increases, especially in the 85–100% range. This design allows for more aggressive max utilization rates while not adding too much rate volatility near optimal rate. ### Formula[](https://docs.drift.trade/lend-borrow/borrow-interest-rate#formula) The interest rate function is defined as: U∗\=optimalUtilizationSPOT\_MARKET\_UTILIZATION\_PRECISION,ΔR\=Rmax⁡−Ropt,R(U)\=max⁡{Rmin⁡, Rraw(U)},Rraw(U)\={Ropt UU∗,U≤U∗,Ropt+ΔR 501000 U−U∗0.85−U∗,U∗ 50). For full examples, check out the margin tests [here (opens in a new tab)](https://github.dev/drift-labs/protocol-v2/blob/190b042a4eeec8521aa6e9b54c094fbdea6a28d9/programs/clearing_house/src/math/margin.rs#L789-L790) . A user that decides to provide liquidity can opt to use leverage, similar to open orders. This puts them at increased risk of liquidation. Fortunately, a liquidation will remove their BAL shares (to acquire more free margin) prior to liquidating any positions and applying larger penalties. This gives BAL shares more leeway prior to liquidation. ### Funding[](https://docs.drift.trade/backstop-amm-liquidity/bal-provider-info#funding) Users with BAL shares who acquire positions through the AMM acquire **unsettled positions**. Only once the positions are settled can they participate in funding payments. By default, the AMM will act as the custodian of their position for funding payments prior to being settled. This means that BAL providers will need to be settled each funding period to earn their full funding payments. BAL providers only earn funding on settled positions, to defend against malicious BAL providers and ensure all BAL providers earn the correct amount of funding. ### Design Consideration / Constraints[](https://docs.drift.trade/backstop-amm-liquidity/bal-provider-info#design-consideration--constraints) At a high level, we track how much base/quote_asset\_amount to give each lp by tracking a "last\_...\_per\_lp" variable for both the base and quote amount when they first add liquidity (ie, \_last_\_base_asset\_amount\_per\_lp and \_last_\_quote\_asset\_amount\_per\_lp respectively). For each trade that occurs on the protocol, the program updates these variables so the LBAL providersPs get a slice of the opposite side of the trade (ie, if a trader opens a long then the base\_asset\_amount\_per\_lp variable would be decremented to track that the lp opens a short) ([code (opens in a new tab)](https://github.com/drift-labs/protocol-v2/blob/190b042a4eeec8521aa6e9b54c094fbdea6a28d9/programs/clearing_house/src/controller/position.rs#L433-L448) ). To determine how much base/quote to give BAL providers when they burn their shares, the program takes the difference between the current per\_lp values and the last per\_lp values and multiply it by the number of shares they have ([code (opens in a new tab)](https://github.com/drift-labs/protocol-v2/blob/190b042a4eeec8521aa6e9b54c094fbdea6a28d9/programs/clearing_house/src/math/lp.rs#L62-L73) ). Following a similar pattern with the funding payments (eg, using a last\_funding\_payments\_per\_lp variable which is updated each time funding payments are distributed) would not work because the per\_lp metrics can only tell you how much base asset amount the BAL providers have in total and not how much each LP has taken on individually. Following this pattern would enable an attack where a malicious LP adds a large amount of liquidity before the funding rate is updated and removes it right after the funding is updated, earning all of the funding payment without holding any base asset amount. The solution to this problem is to give unsettled positions to BAL providers which don't earn funding until they call the [`settle_lp function` (opens in a new tab)](https://github.com/drift-labs/protocol-v2/blob/190b042a4eeec8521aa6e9b54c094fbdea6a28d9/programs/clearing_house/src/lib.rs#L780) and then calculate funding payments on these settled market positions like normal. ### Protections[](https://docs.drift.trade/backstop-amm-liquidity/bal-provider-info#protections) The AMM has many protections against toxic flow which are implicitly applied to BAL providers (see [Optimisations](https://docs.drift.trade/about-v2/optimizations) ). Guards against botting activity aimed at taking advantage of auction order flow are also in place. These guards can be fine-tuned over time. ⬇️ A brief cooldown period to burn BAL shares (30 seconds since the last liquidity addition) is in place to prevent the potential atomic MEV capture of flow from the protocol/non-bot BAL providers. [Backstop AMM Liquidity (BAL)](https://docs.drift.trade/backstop-amm-liquidity/bal-provider-overview "Backstop AMM Liquidity (BAL)") [Liquidity Provider FAQ](https://docs.drift.trade/backstop-amm-liquidity/bal-provision-faq "Liquidity Provider FAQ") --- # Referral Links – Drift Protocol 🤝 Partnerships 💌 Referral Link Referral Links ============== Create your own referral link today and boost your earnings when you refer new users to trade on Drift! For every new user you bring to Drift, you will earn a portion of their trading fees as a reward for bringing on a new user! Referrers earn **15%** of the fees from users they refer to Drift, and the referred user will also receive a discount of **5%** off their fees! This document will walk you through setting up your referral link to begin earning today. ℹ️ Rewards for the referrer accrue only from taker volume. `current_epoch_referrer_rewards` are capped at 150,000 USDC per epoch (28 days); the next epoch begins when the cluster time passes `next_epoch_ts` on the UserStats account. ⚠️ The referral link applies solely to _new_ Drift accounts created through your link. For it to apply, users must have clicked the link, connected their wallet, and made a deposit within the same session. 1. First, in order to create your own ref link you must click on the “Overview” tab inside the Drift app. Once there you will want to scroll down to where it says “Referrals”. ![](https://docs.drift.trade/assets/ref-1.png) 2. Once there, click on “Create my referral link”. ![](https://docs.drift.trade/assets/ref-2.png) 3. Customize your referral link in under 32 characters and click “Create”. You won’t be able to change your referral link after setting it up the first time. ![](https://docs.drift.trade/assets/ref-3.png) 4. Once you’ve approved the transaction, you will find your rewards under “Total Rewards Earned” and a way to copy your link directly to your clipboard. ![](https://docs.drift.trade/assets/ref-4.png) 5. Share your referral link with your friends and community and you’ll start earning fees from their trading activity! It’s that easy! **Share your link and start earning today!** [🛠️ Drift Builder Codes](https://docs.drift.trade/partnerships/DBC "🛠️ Drift Builder Codes") [🤖 Tutorial Bots](https://docs.drift.trade/tutorial-bots "🤖 Tutorial Bots") --- # Preparing Environment – Drift Protocol [🤖 Tutorial Bots](https://docs.drift.trade/tutorial-bots) Keeper Bots Introduction[](https://docs.drift.trade/tutorial-bots/keeper-bots#introduction) -------------------------------------------------------------------------------- Keeper Bots in the Drift Protocol keep the protocol operational by performing automated actions as autonomous off-chain agents. Keepers are rewarded depending on the duties that they perform. The various types of keeper bots are: | Bot Type | Difficulty | Capital Required | Rewards | Link | | --- | --- | --- | --- | --- | | Matching Bot | Basic | No | TBD | [Tutorial: Order Matching Bot](https://docs.drift.trade/tutorial-bots/keeper-bots/tutorial-order-matching-bot) | | Order Trigger | Basic | No | TBD | [Tutorial: Order Trigger Bot](https://docs.drift.trade/tutorial-bots/keeper-bots/tutorial-order-trigger-bot) | | Liquidator | Advanced | Yes | TBD | [Tutorial: Liquidation Bot](https://docs.drift.trade/tutorial-bots/keeper-bots/tutorial-liquidation-bot) | _Note: all bots require some amount of SOL for user account rent and to pay transaction fees._ The reference implementation for all Keeper bots mentioned in these docs is available [here (opens in a new tab)](https://github.com/drift-labs/keeper-bots-v2) . Preparing Environment ===================== First clone the keeper-bots-v2 repo (make sure to check out the correct branch for the cluster you are targetting) | **Branch Name** | **Cluster** | | --- | --- | | master | devnet | | devnet | devnet | | mainnet-beta | mainnet-beta | git clone https://github.com/drift-labs/keeper-bots-v2 -b devnet Prepare the required environment variables by copying over `.env.example`, modify `.env` with your preferred values cp .env.example .env ### Required Environment Variables[](https://docs.drift.trade/tutorial-bots/keeper-bots#required-environment-variables) `KEEPER_PRIVATE_KEY`: the private key of the account to use for signing transactions. This account is the signing of authority of all accounts used by this bot. The value can be a number array (as in the example) or a path to a `keypair.json` file as generated by `solana-keygen` `ENDPOINT:` the JSON-RPC endpoint to use `ENV`: devnet Initialise `User` ================= The signing account needs to have a `User` account before they are able to interact with the `DriftClient` program. We've included a `--init-user` flag on the Keeper Bot script to help with initializing new users. yarn run start --init-user if (!(await driftClient.getUser().exists())) { logger.info(`Creating DriftClient for ${wallet.publicKey}`); const [txSig] = await driftClient.initializeUserAccount(); logger.info(`Initialized user account in transaction: ${txSig}`); } ### Depositing Collateral[](https://docs.drift.trade/tutorial-bots/keeper-bots#depositing-collateral) ❗Only required if you are trading or your bot needs to maintain open positions (JIT makers and certain liquidators) Trading, as well as some Keeper functions (Liquidators and JIT makers), require the account to maintain open positions, and so those accounts must hold collateral. The Keeper Bot script includes a `--force-deposit` flag to help with depositing collateral. # deposit 10,000 USDC from account yarn run start --force-deposit 10000 [🤖 Tutorial Bots](https://docs.drift.trade/tutorial-bots "🤖 Tutorial Bots") [Tutorial: Order Matching Bot](https://docs.drift.trade/tutorial-bots/keeper-bots/tutorial-order-matching-bot "Tutorial: Order Matching Bot") --- # Tutorial: Bots – Drift Protocol 🤖 Tutorial Bots Tutorial: Bots ============== ### Introduction[](https://docs.drift.trade/tutorial-bots#introduction) There are two primary types of bots that run on Drift Protocol: 1. Keeper Bots; and 2. Trading Bots. The reference implementation for all Keeper bots mentioned in these docs is available [here (opens in a new tab)](https://github.com/drift-labs/keeper-bots-v2) . All bots require some amount of SOL to pay transaction fees. ### Keeper Bots[](https://docs.drift.trade/tutorial-bots#keeper-bots) Keeper Bots are integral to the performance of Drift Protocol. They perform automated actions as autonomous off-chain agents that are crucial to the platform. Keepers are rewarded depending on the duties that they perform. The various types of keeper bots are: | Bot Type | Difficulty | Capital Required | Rewards | Link | | --- | --- | --- | --- | --- | | Matching Bot | Basic | No | TBD | [Tutorial: Order Matching Bot](https://docs.drift.trade/tutorial-bots/keeper-bots/tutorial-order-matching-bot) | | Order Trigger | Basic | No | TBD | [Tutorial: Order Trigger Bot](https://docs.drift.trade/tutorial-bots/keeper-bots/tutorial-order-trigger-bot) | | Liquidator | Advanced | Yes | TBD | | ### Trading Bots[](https://docs.drift.trade/tutorial-bots#trading-bots) Trading Bots are for-profit bots run on Drift Protocol for the purposes of automating particular trading strategies. In addition to the financial incentive, Trading Bots provide other users on the exchange with better, more accurate pricing and better liquidity. There are two primary types of trading bots that can be run on Drift Protocol. We have provided examples here: | Bot Type | Difficulty | Capital Required | Rewards | Link | | --- | --- | --- | --- | --- | | JIT Maker Bot | Advanced | Yes | TBD | [Tutorial: JIT Maker Bot](https://docs.drift.trade/tutorial-bots/trading-bots/tutorial-jit-trading-bot) | [💌 Referral Link](https://docs.drift.trade/partnerships/referral-link "💌 Referral Link") [Keeper Bots](https://docs.drift.trade/tutorial-bots/keeper-bots "Keeper Bots") --- # Tutorial: Order Trigger Bot – Drift Protocol [🤖 Tutorial Bots](https://docs.drift.trade/tutorial-bots) [Keeper Bots](https://docs.drift.trade/tutorial-bots/keeper-bots) Tutorial: Order Trigger Bot Tutorial: Order Trigger Bot =========================== Introduction ============ Order Trigger Bots (Trigger Bots) are responsible for marking orders that satisfy the trigger condition, including: * **Trigger Market Orders -** Stop Market and Take Profit * **Trigger Limit Orders -** Stop Limit and Take Profit Limit Trigger Bots receive a small compensation for each successfully marked order. See [Keepers & Decentralised Orderbook](https://docs.drift.trade/about-v2/decentralized-orderbook) for a technical explanation of how the decentralised orderbook (DLOB) and matching incentives work. Trigger Bots are similar to [Tutorial: Order Matching Bot](https://docs.drift.trade/tutorial-bots/keeper-bots/tutorial-order-matching-bot) in that they: * also maintain a local copy of the [Keepers & Decentralised Orderbook](https://docs.drift.trade/about-v2/decentralized-orderbook) ; * do not require the operator to manage collateral; and * receive a small reward for performing their duties. Getting Started =============== The reference implementation of a Trigger Bot is available [here (opens in a new tab)](https://github.com/drift-labs/keeper-bots-v2/blob/master/src/bots/trigger.ts) . Follow the instructions at [Keeper Bots](https://docs.drift.trade/about-v2/keepers) to set the required environment variables and make sure a `ClearingHouseUser` is initialised. Start the Trigger Bot: yarn run dev:trigger Technical Explanation ===================== 1\. Get nodes from the DLOB that are ready to be triggered[](https://docs.drift.trade/tutorial-bots/keeper-bots/tutorial-order-trigger-bot#1-get-nodes-from-the-dlob-that-are-ready-to-be-triggered) ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- The DLOB implementation includes a method for getting orders ready to be triggered: const market = this.driftClient.getMarketAccounts()[0]; // get a MarketAccount const oraclePriceData = this.driftClient.getOracleDataForMarket(marketIndex); const nodesToTrigger = this.dlob.findNodesToTrigger( marketIndex, this.slotSubscriber.getSlot(), oraclePriceData.price ); 2\. Call `trigger_order` on `DriftClient`[](https://docs.drift.trade/tutorial-bots/keeper-bots/tutorial-order-trigger-bot#2-call-trigger_order-on-driftclient) --------------------------------------------------------------------------------------------------------------------------------------------------------------- const user = this.userMap.get(nodeToTrigger.node.userAccount.toString()); const txSig = await this.driftClient.triggerOrder( nodeToTrigger.node.userAccount, user.getUserAccount(), nodeToTrigger.node.order ); [Tutorial: Order Matching Bot](https://docs.drift.trade/tutorial-bots/keeper-bots/tutorial-order-matching-bot "Tutorial: Order Matching Bot") [Tutorial: Order Liquidation Bot](https://docs.drift.trade/tutorial-bots/keeper-bots/tutorial-liquidation-bot "Tutorial: Order Liquidation Bot") --- # Tutorial: Order Matching Bot – Drift Protocol [🤖 Tutorial Bots](https://docs.drift.trade/tutorial-bots) [Keeper Bots](https://docs.drift.trade/tutorial-bots/keeper-bots) Tutorial: Order Matching Bot Tutorial: Order Matching Bot ============================ Introduction ============ Order Matching Bots (Matching Bots) are responsible for matching two orders that cross or a taker order against the AMM. Specifically, this includes: * **Market Orders**: Market Buy and Market Sell * **Limit Orders**: Limit Buy and Limit Sell Matching Bots receive a small compensation for each order that they successfully fill. See [Keepers & Decentralised Orderbook](https://docs.drift.trade/about-v2/decentralized-orderbook) for a technical explanation of how the decentralised orderbook (DLOB) and matching incentives work. Matching Bots are similar to [Tutorial: Order Trigger Bot](https://docs.drift.trade/tutorial-bots/keeper-bots/tutorial-order-trigger-bot) in that they: * also maintain a local copy of the Decentralised Limit Orderbook (DLOB); * do not require the operator to manage collateral; and * receive a small reward for performing their duties. Getting Started =============== The reference implementation of the Order Matching Bot is available [here (opens in a new tab)](https://github.com/drift-labs/keeper-bots-v2/blob/master/src/bots/filler.ts) . Follow the instructions at [Keeper Bots](https://docs.drift.trade/about-v2/keepers) to set the required environment variables and make sure a `ClearingHouseUser` is initialized. Start the Matching Bot: yarn run dev:filler Technical Explanation ===================== 1\. Get nodes from the DLOB that are ready to be filled[](https://docs.drift.trade/tutorial-bots/keeper-bots/tutorial-order-matching-bot#1-get-nodes-from-the-dlob-that-are-ready-to-be-filled) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Market orders that are sent on the Drift Protocol first go through the [Just-In-Time (JIT) Auctions](https://docs.drift.trade/about-v2/matching-engine) . After the auction period, Matching Bots step in to fill orders for a small reward. The DLOB implementation includes a method for getting orders ready to be filled: const market = this.clearingHouse.getMarketAccounts()[0]; // get a MarketAccount const oraclePriceData = this.driftClient.getOracleDataForMarket(marketIndex); const oracleIsValid = isOracleValid( market.amm, oraclePriceData, this.driftClient.getStateAccount().oracleGuardRails, this.slotSubscriber.getSlot() ); const vAsk = calculateAskPrice(market, oraclePriceData); const vBid = calculateBidPrice(market, oraclePriceData); const nodesToFill = this.dlob.findNodesToFill( marketIndex, vBid, vAsk, this.slotSubscriber.getSlot(), oracleIsValid ? oraclePriceData : undefined ); 2\. Filter for Fillable Nodes[](https://docs.drift.trade/tutorial-bots/keeper-bots/tutorial-order-matching-bot#2-filter-for-fillable-nodes) -------------------------------------------------------------------------------------------------------------------------------------------- To avoid trying to fill orders that aren't ready to be filled, filter out orders that are too small to fill if ( !nodeToFill.makerNode && (isVariant(nodeToFill.node.order.orderType, "limit") || isVariant(nodeToFill.node.order.orderType, "triggerLimit")) ) { const baseAssetAmountMarketCanExecute = calculateBaseAssetAmountMarketCanExecute( market, nodeToFill.node.order, oraclePriceData ); if ( baseAssetAmountMarketCanExecute.lt(market.amm.baseAssetAmountStepSize) ) { // skip order continue; } } 3\. Call `fill_order` on `DriftClient`[](https://docs.drift.trade/tutorial-bots/keeper-bots/tutorial-order-matching-bot#3-call-fill_order-on-driftclient) ---------------------------------------------------------------------------------------------------------------------------------------------------------- const user = this.userMap.get(nodeToFill.node.userAccount.toString()); const txSig = await this.driftClient.fillOrder( nodeToFill.node.userAccount, user.getUserAccount(), nodeToFill.node.order, undefined ); [Keeper Bots](https://docs.drift.trade/tutorial-bots/keeper-bots "Keeper Bots") [Tutorial: Order Trigger Bot](https://docs.drift.trade/tutorial-bots/keeper-bots/tutorial-order-trigger-bot "Tutorial: Order Trigger Bot") --- # RPC Providers – Drift Protocol [🤖 Tutorial Bots](https://docs.drift.trade/tutorial-bots) RPC Providers RPC Providers ============= Solana utilizes a network of [RPC Nodes (opens in a new tab)](https://solana.com/rpc) to serve data to users. These nodes require a lot of resources to run and therefore can be quite expensive to operate. Some of the commonly used free RPC providers are insufficient for operating drift bots because we require some functions that are commonly disabled (i.e. websockets and `getProgramAccounts`). [Helius (opens in a new tab)](https://www.helius.dev/) has a generous free plan that is sufficient for getting started. But consider upgrading to a paid plan as you get more serious with operating bots on Drift or Solana in general. A more complete list is available [here (opens in a new tab)](https://solana.com/rpc) [Tutorial: JIT Maker Bot](https://docs.drift.trade/tutorial-bots/trading-bots/tutorial-jit-trading-bot "Tutorial: JIT Maker Bot") [Troubleshooting](https://docs.drift.trade/tutorial-bots/troubleshooting "Troubleshooting") --- # Tutorial: Liquidation Bot – Drift Protocol [🤖 Tutorial Bots](https://docs.drift.trade/tutorial-bots) [Keeper Bots](https://docs.drift.trade/tutorial-bots/keeper-bots) Tutorial: Order Liquidation Bot Tutorial: Liquidation Bot ========================= Introduction ============ Liquidation Bots improve the overall health of the protocol by deleveraging users approaching bankruptcy. The liquidation in the protocol is a liability transfer mechanism from the selected liquidatee (user in liquidation territory) to the liquidator (the user running the Liquidation Bot). Liquidators inherit the liabilities they liquidate and receive an asset at a discount for doing so. In order to participate, liquidators must have even collateral in their account in order to satisfy the initial margin requirements for the transferred positions. For more information on our liquidation system, please read [Liquidations](https://docs.drift.trade/liquidations/liquidations) . Getting Started =============== The reference implementation of a Liquidation Bot is available [here (opens in a new tab)](https://github.com/drift-labs/keeper-bots-v2/blob/master/src/bots/liquidator.ts) . A step-by-step guide to initialising and running the liquidator bot will be coming soon! Advanced ======== If you're interested to make the liquidator bot run better, you can make edits to the above to improve its efficiency. In particular, you can: 1. Sort users in an efficient data structure based on their liquidation price; 2. Monitor the market's price to determine when to run liquidation checks / RPC checks. We encourage the community to build out stronger liquidations engines and bots to secure our Insurance Fund and user collateral. If interested to chat or have any questions, please reach out to us on [Discord (opens in a new tab)](https://discord.com/invite/95kByNnDy5) or [Twitter (opens in a new tab)](https://twitter.com/driftprotocol) ! [Tutorial: Order Trigger Bot](https://docs.drift.trade/tutorial-bots/keeper-bots/tutorial-order-trigger-bot "Tutorial: Order Trigger Bot") [Tutorial: JIT Maker Bot](https://docs.drift.trade/tutorial-bots/trading-bots/tutorial-jit-trading-bot "Tutorial: JIT Maker Bot") --- # Troubleshooting – Drift Protocol [🤖 Tutorial Bots](https://docs.drift.trade/tutorial-bots) Troubleshooting Failed to get token account balance[](https://docs.drift.trade/tutorial-bots/troubleshooting#failed-to-get-token-account-balance) ---------------------------------------------------------------------------------------------------------------------------------- The account in `KEEPER_PRIVATE_KEY` does not have a USDC account SolanaJSONRPCError: failed to get token account balance: Invalid param: could not find account at Connection.getTokenAccountBalance (/Users/user/Drift/keeper-bots-v2/node_modules/@solana/web3.js/src/connection.ts:2704:13) at processTicksAndRejections (internal/process/task_queues.js:95:5) at async runBot (/Users/user/Drift/keeper-bots-v2/src/index.ts:252:22) at async recursiveTryCatch (/Users/user/Drift/keeper-bots-v2/src/index.ts:473:3) at async recursiveTryCatch (/Users/user/Drift/keeper-bots-v2/src/index.ts:481:3) { code: -32602, data: undefined } `ClearingHouseUser` does not exist[](https://docs.drift.trade/tutorial-bots/troubleshooting#clearinghouseuser-does-not-exist) ------------------------------------------------------------------------------------------------------------------------------ The account in `KEEPER_PRIVATE_KEY` has not been initialised on the `ClearingHouse` program yet. See [Keeper Bots](https://docs.drift.trade/tutorial-bots/keeper-bots) for how to initialise the `ClearingHouseUser` [2022-08-15T22:46:19.236Z] error: ClearingHouseUser for bot69e9FXGoKzvAdGnN8uVVDCfLdLUX6K5wsXdrS3Dd3 does not exist Error: Run with '--init-user' flag to initialize a ClearingHouseUser at runBot (/Users/user/Drift/keeper-bots-v2/src/index.ts:271:10) at processTicksAndRejections (internal/process/task_queues.js:95:5) at async recursiveTryCatch (/Users/user/Drift/keeper-bots-v2/src/index.ts:473:3) Misc Transaction Errors[](https://docs.drift.trade/tutorial-bots/troubleshooting#misc-transaction-errors) ---------------------------------------------------------------------------------------------------------- Since running a Keeper is a profit-seeking endeavour, it is not unusual to run into competition while filling orders and liquidating dangerous positions. These errors can happen at various commitment levels, and how you handle them will be dependent on your skillset and craftiness. If you're looking for friends, come to [#dev-chat (opens in a new tab)](https://discord.com/channels/849494028176588802/878700556904980500) and leak some alpha 🤓. [RPC Providers](https://docs.drift.trade/tutorial-bots/rpc-providers "RPC Providers") [Historical Data v1](https://docs.drift.trade/historical-data/historical-data-v1 "Historical Data v1") --- # Historical Data V1 – Drift Protocol ⏳ Historical Data Historical Data v1 Historical Data v1[](https://docs.drift.trade/historical-data/historical-data-v1#historical-data-v1) ----------------------------------------------------------------------------------------------------- For data analysis conveince, the following are [protocol-v1 (opens in a new tab)](https://github.com/drift-labs/protocol-v1) historical data snapshots collected and stored off-chain (~99% of records). Encourage anyone in the community to confirm by parse the logs using the Anchor IDL for transactions including to program id = [`dammHkt7jmytvbS3nHTxQNEcP59aE57nxwV21YdqEDN` (opens in a new tab)](https://solana.fm/address/dammHkt7jmytvbS3nHTxQNEcP59aE57nxwV21YdqEDN?cluster=mainnet-solanafmbeta) to verify the history. To download records of interest, combine the URL Prefix with one of the Route Suffixes in the table below. URL Prefix: [https://drift-historical-data.s3.eu-west-1.amazonaws.com/program/dammHkt7jmytvbS3nHTxQNEcP59aE57nxwV21YdqEDN/ (opens in a new tab)](https://drift-historical-data.s3.eu-west-1.amazonaws.com/program/dammHkt7jmytvbS3nHTxQNEcP59aE57nxwV21YdqEDN/) | Record Type | Route Suffix | Example | | --- | --- | --- | | Trade | market/`market-symbol`/trades/`year`/`month`user/`user-authority`/trade/`year` | [Market Trades 03/2022 (opens in a new tab)](https://drift-historical-data.s3.eu-west-1.amazonaws.com/program/dammHkt7jmytvbS3nHTxQNEcP59aE57nxwV21YdqEDN/market/SOL-PERP/trades/2022/3)
[User Trader 2022 (opens in a new tab)](https://drift-historical-data.s3.eu-west-1.amazonaws.com/program/dammHkt7jmytvbS3nHTxQNEcP59aE57nxwV21YdqEDN/user/121MD8DdecTFdUyboAWtn9H6xjcdUTLE7b7mN3RwiJDS/trades/2022) | | Funding Rates | market/`market-symbol`/funding-rates/`year`/`month` | [Funding Rates 03/2022 (opens in a new tab)](https://drift-historical-data.s3.eu-west-1.amazonaws.com/program/dammHkt7jmytvbS3nHTxQNEcP59aE57nxwV21YdqEDN/market/SOL-PERP/funding-rates/2022/3) | | Funding Payments | user/`user-authority`/funding-payments/`year` | [User Funding Payments 2021 (opens in a new tab)](https://drift-historical-data.s3.eu-west-1.amazonaws.com/program/dammHkt7jmytvbS3nHTxQNEcP59aE57nxwV21YdqEDN/user/13NasSfdZUyAfQYPGNFU2wQTbzK91vZf1Yszxq9GSHj4/funding-payments/2021) | | Deposits | user/`user-authority`/deposit/`year` | [User Deposits 2021 (opens in a new tab)](https://drift-historical-data.s3.eu-west-1.amazonaws.com/program/dammHkt7jmytvbS3nHTxQNEcP59aE57nxwV21YdqEDN/user/13NasSfdZUyAfQYPGNFU2wQTbzK91vZf1Yszxq9GSHj4/deposit/2021) | | Orders | user/`user-authority`/order/`year` | [User Orders 2022 (opens in a new tab)](https://drift-historical-data.s3.eu-west-1.amazonaws.com/program/dammHkt7jmytvbS3nHTxQNEcP59aE57nxwV21YdqEDN/user/1264MYNRHy1LTCp37jAPzn1i6FYXm7PY69iBHMcuT6e4/order/2022) | | Liquidations | user/`user-authority`/liquidation/`year` | [User Liquidations 2022 (opens in a new tab)](https://drift-historical-data.s3.eu-west-1.amazonaws.com/program/dammHkt7jmytvbS3nHTxQNEcP59aE57nxwV21YdqEDN/user/DgtZ1dBzCaR4K38CxgyhxaGCdwXM69N4CZDZ4nsZXYE4/liquidation/2022) | | Candles | market/`market-symbol`/candles/resolution/`resolution`/`year`/`month` | [1 Min Candles (opens in a new tab)](https://drift-historical-data.s3.eu-west-1.amazonaws.com/program/dammHkt7jmytvbS3nHTxQNEcP59aE57nxwV21YdqEDN/market/SOL-PERP/candles/resolution/1/2022/3) | [Troubleshooting](https://docs.drift.trade/tutorial-bots/troubleshooting "Troubleshooting") [Historical Data v2](https://docs.drift.trade/historical-data/historical-data-v2 "Historical Data v2") --- # JIT Maker Bot – Drift Protocol [🤖 Tutorial Bots](https://docs.drift.trade/tutorial-bots) Trading Bots Tutorial: JIT Maker Bot JIT Maker Bot ============= This tutorial shows how to run a JIT Maker bot in Typescript from the [keeper-bots-v2 repo (opens in a new tab)](https://github.com/drift-labs/keeper-bots-v2) . A similar example written in Python is available in [keepyrs (opens in a new tab)](https://github.com/drift-labs/keepyrs) . Market orders go through the [Just-In-Time (JIT) Auctions](https://docs.drift.trade/about-v2/matching-engine) where Makers fight to fill orders before the order is allowed to fill against the [Drift AMM](https://docs.drift.trade/about-v2/drift-amm) . Running the bot[](https://docs.drift.trade/tutorial-bots/trading-bots/tutorial-jit-trading-bot#running-the-bot) ---------------------------------------------------------------------------------------------------------------- **☠️ This bot requires collateral to run. This tutorial is a developer's guide and holds no responsibility over bot outcomes.** ### 1\. Clone the repository[](https://docs.drift.trade/tutorial-bots/trading-bots/tutorial-jit-trading-bot#1-clone-the-repository) The JIT Maker example lives in the keeper-bots-v2 repo, clone it to your local machine: git clone https://github.com/drift-labs/keeper-bots-v2.git ### 2\. Prepare a keypair and drift account.[](https://docs.drift.trade/tutorial-bots/trading-bots/tutorial-jit-trading-bot#2-prepare-a-keypair-and-drift-account) Refer to the [bot wallet setup](https://docs.drift.trade/getting-started/wallet-setup/bot-wallet-setup) tutorial for how to set up a bot wallet. ### 3\. Prepare the config file.[](https://docs.drift.trade/tutorial-bots/trading-bots/tutorial-jit-trading-bot#3-prepare-the-config-file) The [`jit-maker-config.yaml` (opens in a new tab)](https://github.com/drift-labs/keeper-bots-v2/blob/master/jit-maker-config.yaml) file is good starting point. You will need to fill in the following values: * `global.endpoint`: set this to your RPC endpoint (see [RPC Providers](https://docs.drift.trade/tutorial-bots/rpc-providers) ) * `global.keeperPrivateKey`: set this to your bot private key (alternatively you can leave it blank and set the `KEEPER_PRIVATE_KEY` environment variable) * `botConfigs.jitMaker.aggressivenessBps`: this is how aggressive you want your jit maker to be. If set to 30, the bot will attempt to buy 30 bps above the best bid, and sell 30 bps below the best ask. * `botConfigs.jitMaker.marketType` (`perp` or `spot`): this is the type of market we want to jit make * `botConfigs.jitMaker.marketIndexes`: this is the list of markets that we want to jit make, it * `botConfigs.jitMaker.subaccounts`: this is the subaccount to use for each marketIndex provided Note: `subaccounts` and `marketIndexes` are a direct mapping, so the below config will use subaccount 0 for marketIndex 0, and subaccount 1 for marketIndex 1: botConfigs: jitMaker: marketType: perp marketIndexes: - 0 - 1 subaccounts: - 0 - 1 ### 4\. Run the bot[](https://docs.drift.trade/tutorial-bots/trading-bots/tutorial-jit-trading-bot#4-run-the-bot) Now you are ready to run the bot, start it with: yarn run dev --config-file=jit-maker-config.yaml Technical Explanation[](https://docs.drift.trade/tutorial-bots/trading-bots/tutorial-jit-trading-bot#technical-explanation) ---------------------------------------------------------------------------------------------------------------------------- ### Strategy overview[](https://docs.drift.trade/tutorial-bots/trading-bots/tutorial-jit-trading-bot#strategy-overview) This bot uses the [`JitterShotgun` (opens in a new tab)](https://github.com/drift-labs/jit-proxy/blob/master/ts/sdk/src/jitter/jitterShotgun.ts#L13) strategy and the [`jit-proxy` (opens in a new tab)](https://github.com/drift-labs/jit-proxy) program to try to fill jit maker fills. The JitterShotgun strategy continuously sends transactions in an attempt to fill orders as soon as it sees one that crosses. The `jit-proxy` program is a permissionless and stateless program that does the last-mile checks on-chain to ensure the fill is within our desired bid/ask price and does not exeeed min/max positions. ### JIT-able orders[](https://docs.drift.trade/tutorial-bots/trading-bots/tutorial-jit-trading-bot#jit-able-orders) Orders with `auctionDuration > 0` may be filled by jit makers at any time. This bot finds these orders by using the `programSubscribe` RPC method, and filtering for users with new orders that meet this criteria. ### Final notes and future optimizations[](https://docs.drift.trade/tutorial-bots/trading-bots/tutorial-jit-trading-bot#final-notes-and-future-optimizations) This is a very simple and naiive strategy, some oppotunities for improvements: * allow multiple markets and spot + perp at the same time * asymetric bid/ask offsets, allow the different `aggressivenessBps` for bid/ask depending on how you want to skew your quotes * an improved `JitterShotgun` strategy that is more cognizant of time and transactions sent Troubleshooting[](https://docs.drift.trade/tutorial-bots/trading-bots/tutorial-jit-trading-bot#troubleshooting) ---------------------------------------------------------------------------------------------------------------- ### Resubscribing log messages[](https://docs.drift.trade/tutorial-bots/trading-bots/tutorial-jit-trading-bot#resubscribing-log-messages) No ws data from user in 30000ms, resubscribing No ws data from userStats in 30000ms, resubscribing No ws data from perpMarket in 30000ms, resubscribing No ws data from perpMarket in 30000ms, resubscribing No ws data from perpMarket in 30000ms, resubscribing No ws data from spotMarket in 30000ms, resubscribing This is a notification from the Drift SDK that it is restarting its websocket connection with the RPC due to no messages being received within the set time. This is generatlly not an error and pretty common for less active markets that don't have much activity. ### Running JIT periodic tasks...[](https://docs.drift.trade/tutorial-bots/trading-bots/tutorial-jit-trading-bot#running-jit-periodic-tasks) [2024-02-27T00:04:31.387Z] Running JIT periodic tasks... [2024-02-27T00:04:31.389Z] info: (mkt index: JTO-PERP) base to market make (targetLvg=0.95): 1481.8891930588115 = 3476.551044 / 2.228725 * 0.95 This is a normal status message that the bot is running its periodic tasks. If you see this message, it means the bot is running as expected. ### Order does not cross params yet, retrying[](https://docs.drift.trade/tutorial-bots/trading-bots/tutorial-jit-trading-bot#order-does-not-cross-params-yet-retrying) Trying to fill 24yfkkuFv849BpCBBo49tV6i6ycfc3aEUY6wWKFsN4SS-177961 SendTransactionError: failed to send transaction: Transaction simulation failed: Error processing Instruction 2: custom program error: 0x1771 ... logs: [\ 'Program ComputeBudget111111111111111111111111111111 invoke [1]',\ 'Program ComputeBudget111111111111111111111111111111 success',\ 'Program ComputeBudget111111111111111111111111111111 invoke [1]',\ 'Program ComputeBudget111111111111111111111111111111 success',\ 'Program J1TnP8zvVxbtF5KFp5xRmWuvG9McnhzmBd9XGfCyuxFP invoke [1]',\ 'Program log: Instruction: Jit',\ 'Program log: slot = 250667476 auction duration = 32 slots_left = 15',\ 'Program log: taker order type Oracle auction start -12100 auction end -200 limit price 0 oracle price offset -193',\ 'Program log: taker price 2220700 < worst ask 2234257',\ 'Program log: AnchorError occurred. Error Code: AskNotCrossed. Error Number: 6001. Error Message: AskNotCrossed.',\ 'Program J1TnP8zvVxbtF5KFp5xRmWuvG9McnhzmBd9XGfCyuxFP consumed 39672 of 599700 compute units',\ 'Program J1TnP8zvVxbtF5KFp5xRmWuvG9McnhzmBd9XGfCyuxFP failed: custom program error: 0x1771'\ ] Failed to fill 24yfkkuFv849BpCBBo49tV6i6ycfc3aEUY6wWKFsN4SS-177961 Order does not cross params yet, retrying This is a failed tx message from the RPC provider when a transaction is sent. It is common for the shotgun strategy to get this message as it sends many transactions at once. Decoding it further: * It is a jit fill attempt on taker `24yfkkuFv849BpCBBo49tV6i6ycfc3aEUY6wWKFsN4SS`'s orderId:`177961` * the current slot (that the RPC is simulating the transaction in) is 250667476, the auction lasts for 32 slots, and there are 15 slots left * the taker's order is an Oracle order, with an offset of -12100 (-$0.0121) to -200 (-$0.0020) * the taker's order is a `buy` (since it is comparing with our `ask` price) * the taker's price at that slot is 2220700 ($2.2207), which is below our worst ask 2234257 ($2.2343), so the jit-proxy program threw and error to prevent us from sending a failing transaction on chain [Tutorial: Order Liquidation Bot](https://docs.drift.trade/tutorial-bots/keeper-bots/tutorial-liquidation-bot "Tutorial: Order Liquidation Bot") [RPC Providers](https://docs.drift.trade/tutorial-bots/rpc-providers "RPC Providers") --- # Historical Data V2 – Drift Protocol ⏳ Historical Data Historical Data v2 Historical Data v2[](https://docs.drift.trade/historical-data/historical-data-v2#historical-data-v2) ----------------------------------------------------------------------------------------------------- To download records of interest, **combine the URL Prefix with one of the Route Suffixes in the table below**. URL Prefix: [https://drift-historical-data-v2.s3.eu-west-1.amazonaws.com/program/dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH/ (opens in a new tab)](https://drift-historical-data-v2.s3.eu-west-1.amazonaws.com/program/dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH/) | Record Type | Route Suffix | Example | | --- | --- | --- | | Trades | user/`accountKey`/tradeRecords/`year`/`yearmonthday` | [User Trades 20240124 (opens in a new tab)](https://drift-historical-data-v2.s3.eu-west-1.amazonaws.com/program/dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH/user/C13FZykQfLXKuMAMh2iuG7JxhQqd8otujNRAgVETU6id/tradeRecords/2024/20240124) | | Market Trades | market/`marketSymbol`/tradeRecords/`year`/`yearmonthday` | [Market Trades 20240220 (opens in a new tab)](https://drift-historical-data-v2.s3.eu-west-1.amazonaws.com/program/dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH/market/SOL-PERP/tradeRecords/2024/20240220) | | Funding Rates | market/`marketSymbol`/fundingRateRecords/`year`/`yearmonthday` | [Funding Rates 20240319 (opens in a new tab)](https://drift-historical-data-v2.s3.eu-west-1.amazonaws.com/program/dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH/market/SOL-PERP/fundingRateRecords/2024/20240319) | | Funding Payments | user/`accountKey`/fundingPaymentRecords/`year`/`yearmonthday` | [User Funding Payments 20231224 (opens in a new tab)](https://drift-historical-data-v2.s3.eu-west-1.amazonaws.com/program/dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH/user/C13FZykQfLXKuMAMh2iuG7JxhQqd8otujNRAgVETU6id/fundingPaymentRecords/2023/20231224) | | Deposits | user/`accountKey`/depositRecords/`year`/`yearmonthday` | [User Deposits 20240215 (opens in a new tab)](https://drift-historical-data-v2.s3.eu-west-1.amazonaws.com/program/dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH/user/C13FZykQfLXKuMAMh2iuG7JxhQqd8otujNRAgVETU6id/depositRecords/2024/20240215) | | Liquidations | user/`accountKey`/liquidationRecords/`year`/`yearmonthday` | [User Liquidations 20240106 (opens in a new tab)](https://drift-historical-data-v2.s3.eu-west-1.amazonaws.com/program/dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH/user/H7s1cVn4gnC1uhLeNPbwEmg298DNW4N17zD6rQfGs8da/liquidationRecords/2024/20240106) | | Settle PNL | user/`accountKey`/settlePnlRecords/`year`/`yearmonthday` | [User Settle PNL 20240124 (opens in a new tab)](https://drift-historical-data-v2.s3.eu-west-1.amazonaws.com/program/dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH/user/C13FZykQfLXKuMAMh2iuG7JxhQqd8otujNRAgVETU6id/settlePnlRecords/2024/20240124) | | LP (BAL) | user/`accountKey`/lpRecord/`year`/`yearmonthday` | [User LP 20240119 (opens in a new tab)](https://drift-historical-data-v2.s3.eu-west-1.amazonaws.com/program/dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH/user/BYhwfY1bkUJZG8N7TQfLXZQF3xHJtM2S4H9DfMjto6Q1/lpRecord/2024/20240119) | | Insurance Fund | market/`marketSymbol`/insuranceFundRecords/`year`/`yearmonthday` | [Market Insurance Fund 20240214 (opens in a new tab)](https://drift-historical-data-v2.s3.eu-west-1.amazonaws.com/program/dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH/market/USDC/insuranceFundRecords/2024/20240214) | | Insurance Fund Stake | authority/`authorityAccountKey`/insuranceFundStakeRecords/`year`/`yearmonthday` | [Insurance Fund Stake 20240305 (opens in a new tab)](https://drift-historical-data-v2.s3.eu-west-1.amazonaws.com/program/dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH/authority/ELoqJYcFTc8qjGhJShUupEkRomed8rykb3CUhrzAT4Q1/insuranceFundStakeRecords/2024/20240305) | ### Example:[](https://docs.drift.trade/historical-data/historical-data-v2#example) Get historical trades on SOL-PERP for Jan 1, 2024: [https://drift-historical-data-v2.s3.eu-west-1.amazonaws.com/program/dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH/market/SOL-PERP/tradeRecords/2024/20240101 (opens in a new tab)](https://drift-historical-data-v2.s3.eu-west-1.amazonaws.com/program/dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH/market/SOL-PERP/tradeRecords/2024/20240101) ### Variables[](https://docs.drift.trade/historical-data/historical-data-v2#variables) | variable | description | example | | --- | --- | --- | | accountKey | user sub account public key (not authority) | | | authority | authority public key | | | marketSymbol | market name | SOL-PERP | | year | | 2023 | | month | | 4 | | day | utc time | 25 | | candleResolution | | 1M | ⚠️ **Your user subaccount public key is not your wallet's public key (authority)!** If you use your wallet's public key instead of user subaccount public key, you will get **"Access Denied"**. **Authority** is your wallet's public key, what you see in the URL when you connect your wallet to [app.drift.trade (opens in a new tab)](https://app.drift.trade/) . Example: `https://app.drift.trade/overview?authority=` **User subaccount public key** is your subaccount unique identifier and even though one wallet can have multiple subaccounts, each subaccount public key is unique. ### Where to find user subaccount public key?[](https://docs.drift.trade/historical-data/historical-data-v2#where-to-find-user-subaccount-public-key) You can find your user subaccount public key in the Settings modal, if you hover over ℹ️ icon: ![](https://docs.drift.trade/assets/subaccount-pubkey.png) [Historical data in the API documentation (opens in a new tab)](https://drift-labs.github.io/v2-teacher/?typescript#url-suffix) [Historical Data v1](https://docs.drift.trade/historical-data/historical-data-v1 "Historical Data v1") [Historical Data Glossary](https://docs.drift.trade/historical-data/historical-data-glossary "Historical Data Glossary") --- # Risk Parameters – Drift Protocol ⛑️ Risk and Safety Risk Parameters Risk Parameters =============== These risk parameters are relevant to perpetual futures. Further risk parameters are also set out in [Risks](https://docs.drift.trade/security/risks) . ### Price Bands[](https://docs.drift.trade/risk-and-safety/risk-parameters#price-bands) In Drift v2, to prevent market manipulation and protect users during volatile events, markets will prevent users from sending orders if the oracle-mark price breaches the 10% band of the oracle's 5-minute time-weighted average price (TWAP). If the mark and the 5-minute oracle TWAP diverge by 10%, markets will prevent orders from filling until the price reverts back within this band. These formulas are defined below: Oracle-mark divergence = `(mark - oracle) * max_spread` Oracle-TWAP-mark band = `within 10% of mark - oracle_twap_{5 minutes}` ### Collateral Weight[](https://docs.drift.trade/risk-and-safety/risk-parameters#collateral-weight) To guard against concentration risk from a single whale, when assets exceed a certain size, their asset weights can be discounted. Size Weightage = `1.1 / (weight * sqrt{size} * imf_factor)` Additionally, liabilities (borrows, perp positions, etc) can have premiums applied. `max(.8 * wgt + sqrt(size) * imf_factor, wgt)` ### Price Manipulation Prevention[](https://docs.drift.trade/risk-and-safety/risk-parameters#price-manipulation-prevention) The Clearinghouse will also pause risk-increasing trades that further increase large oracle-mark divergence. Closing/reducing a position that further breaches this divergence is also not allowed (unless the divergence has already been breached). ### Order/Execution Limits[](https://docs.drift.trade/risk-and-safety/risk-parameters#orderexecution-limits) An individual user sub-account can have up to 32 outstanding orders at any one time. A Market Order sent has limits _within each instruction_ (so may be filled iteratively). Market Orders have the possibility of only being partially filled before expiration if any of the following limits occur: * exceeds its slippage tolerance implied limit price * exceeds its active time limit (for market orders, the Clearinghouse sets this at 30 seconds) * exceed 2% price impact (set by the market's `max_slippage_ratio` ) Within a single transaction, orders can be filled up by the `max_base_asset_amount` against the AMM. This maximum is set per market and calling of multiple fill instructions may work. For example, if the maximum amount was 10,000 SOL, an order for 100,000 SOL can be filled against the AMM in 10 instruction calls. The following conditions will also expire/cancel the remainder(s) of orders: * Out of favour oracle price divergence from maker's set limit price (post only orders) * oracle's price is 2.5% above the maker's ask limit price * oracle's price is 2.5% below the maker's bid limit price * order fill would reduce free collateral below 0 (for taker orders) Note that whenever a user's orders are cancelled, fillers receive a small reward for the user they filled, if they did not receive payment otherwise. ### Unbounded P&L and Market Delisting[](https://docs.drift.trade/risk-and-safety/risk-parameters#unbounded-pl-and-market-delisting) This risk is addressed in [Risks](https://docs.drift.trade/security/risks) and [P&L](https://docs.drift.trade/profit-loss/profit-loss-intro) . Users can technically achieve unbounded unrealised P&L from entering and exiting a trade against the AMM. Further, as the AMM allows for asynchronous trading; there may not be an offsetting loss within the system to account for the gain made by particular users. As such, even if the user can achieve unbounded unrealised gains - those gains cannot be settled and withdrawable as collateral until there is a dollar of offsetting loss to account for the dollar of gain. In a circumstance where the majority of participants are in extreme positive unrealised P&L and the unrealised P&L cannot be settled; the market may be eligible for settlement through the [Delisting Process](https://docs.drift.trade/risk-and-safety/delisting-process) . [Protocol Guard Rails](https://docs.drift.trade/risk-and-safety/protocol-guard-rails "Protocol Guard Rails") [🛡️ Drift Safety Module](https://docs.drift.trade/drift-safety-module "🛡️ Drift Safety Module") --- # Introduction to Prediction Markets – Drift Protocol 🎲 Prediction Markets Introduction to Prediction Markets Introduction to Prediction Markets ================================== Overview[](https://docs.drift.trade/prediction-markets/prediction-markets-intro#overview) ------------------------------------------------------------------------------------------ B.E.T is the first capital-efficient prediction market on Solana. Bet bigger on real-world outcomes. Here’s how: * Use 30+ tokens (supported as collateral) — not just USDC. * Hedge your bets on a unified platform. * Earn yield while in position. Each Drift prediction market supports a binary outcome (YES or NO) represented by price 1 or 0. These markets support all the advanced order types (limit, stop, etc) available in other markets and have multiple capital efficiency benefits vs other prediction markets: * earn lending interest on all supported collateral * get margin extended on all supported non-usdc collateral tokens, with 0% interest until losses (realized or unrealized) get settled by a counterparty. after losses get settled, the account pays a floating borrow rate specified [here (opens in a new tab)](https://app.drift.trade/earn/lend-borrow/borrow) . * trading with sufficient/solely USDC do not risk any margin/borrow interest * additionally, solely USDC collateralized accounts (with no other positions) face no liquidation risk (even with depeg in usdc like in march 2023) * every account's margin requirement is only the 'worst case liability'. * this can be more capital efficient vs typical open order allocation: 1. users can still earn lending interest with open orders. 2. liquidity providers with two-sided orders or orders that would only reduce risk require no additional margin. Initialization, Resolution, and Settlement[](https://docs.drift.trade/prediction-markets/prediction-markets-intro#initialization-resolution-and-settlement) ------------------------------------------------------------------------------------------------------------------------------------------------------------ ### Initialization[](https://docs.drift.trade/prediction-markets/prediction-markets-intro#initialization) Upon sufficient community requests and liquidity support/interest, Drift's security council (an elected multisig under realms governance) can initialize. For conservative purposes, markets will require full margin requirement. Prices are bounded between 0 and 1 and a market margin ratio of 100% requires liability value of the position (`1 - price` for shorts and `price` for longs). ### Resolution[](https://docs.drift.trade/prediction-markets/prediction-markets-intro#resolution) The security council (an elected multisig under realms governance) also acts as the resolver for all prediction markets. After an indicated resolution time, the resolution step is to update the oracle (to a fixed value 0 or 1) and setting an expiry date. ### Settlement[](https://docs.drift.trade/prediction-markets/prediction-markets-intro#settlement) After the expiry date is set, users can only trade the market in reduce only mode (no new entrants or risk-increasing positions). After expiry date and settlement is triggered, users can settle their positions at the settlement price (determined by the stable resolution oracle). In a tail-risk event where the market has a shortfall that is not covered by fees or insurance, the shortfall will be socialized into a settlement price (i.e. settlement price can be < 1 despite a resolution set to 1). ### Under what circumstances can a shortfall occur?[](https://docs.drift.trade/prediction-markets/prediction-markets-intro#under-what-circumstances-can-a-shortfall-occur) Despite setting a market's margin ratio for 100% collateralization, if a user uses another token (for example consider with 80%/90% initial/maintainance asset weight), if the value falls beyond 1-`initial_asset_weight`% (20% in example case) before liquidators take over, and SOL insurance is depleted, that means that USDC insurance is required to service the prediction market position. Again, the shortfall must exceed the market's USDC insurance fund or market's specific fee pool for settlement price to be impacted. FAQ[](https://docs.drift.trade/prediction-markets/prediction-markets-intro#faq) -------------------------------------------------------------------------------- ### How do prices reflect the probability of winning?[](https://docs.drift.trade/prediction-markets/prediction-markets-intro#how-do-prices-reflect-the-probability-of-winning) Prices are the cost of buying 1 share, and they range between $0 to $1. When the market is resolved, the price of the correct share will resolve to $1, whereas the shares of the opposing side will resolve to $0. For the more advanced users, you may notice that `Cost of “Yes” share + Cost of “No” share = $1` This is because a “No” share is essentially selling a “Yes” share on margin. ### How do I make money?[](https://docs.drift.trade/prediction-markets/prediction-markets-intro#how-do-i-make-money) When the markets are resolved, and you own shares of the correct side, the prices of those shares will resolve to $1. Example: You bought `Yes` shares for “Donald Trump wins 2024 US Elections” market at $0.70 per share. If Donald Trump does indeed win the 2024 US Elections, you will make a profit of ($1 - $0.70 = $0.30) per `Yes` share that you own. The same calculation works for `No` shares too. ### Can I sell my shares at any time?[](https://docs.drift.trade/prediction-markets/prediction-markets-intro#can-i-sell-my-shares-at-any-time) Yes, you can sell your shares at any time. If you bought `Yes` shares at $0.40/share, and it is now worth $0.60/share, you may want to de-risk and sell some/all of your `Yes` shares for a profit. ### Does my B.E.T activity earn Fuel?[](https://docs.drift.trade/prediction-markets/prediction-markets-intro#does-my-bet-activity-earn-fuel) All B.E.T trades will be boosted by Fuel. The Fuel booster will be available for two weeks - from the 19th of August till the 1st of September. **How is Fuel calculated?** For every $1 trade, you will receive 1 FUEL. This is further boosted by a 5X Fuel Boost. This means that during the 2-week period, you will receive 5 FUEL for every $1 traded. ### What are the fees?[](https://docs.drift.trade/prediction-markets/prediction-markets-intro#what-are-the-fees) Prediction markets have the same fee structure as perp markets, which you can read more about [here (opens in a new tab)](https://docs.drift.trade/trading/trading-fees) . [Overview](https://docs.drift.trade/fuel/overview "Overview") [Delisting Process](https://docs.drift.trade/risk-and-safety/delisting-process "Delisting Process") --- # Delisting Process – Drift Protocol ⛑️ Risk and Safety Delisting Process Delisting Process ================= Delisting a perpetuals market can occur in a tail risk event, but the protocol has an on-chain procedure in place similar to the expiry of any derivatives contract (futures, options). The process is as follows: ### Perpetual Markets[](https://docs.drift.trade/risk-and-safety/delisting-process#perpetual-markets) 1. The market immediately enters "reduce only mode" once an expiry date is set * all new orders are forced to have reduce only flag * all current orders that will increase risk will get cancelled on fill attempts * no new funding rate updates * users cannot settle unrealized P&L prior to expiry 2. After the expiry date, the market can lock in a settlement price * must call the instruction: `settle_expired_market` * the target price is the amm's calculated 1-hour oracle twap but is altered such that it allows for full solvency across all users 3. After the expiry date + optional time buffer, users can settle their "expired positions" at the settlement price, which are closed * the optional time buffer is the settlement duration, which acts as a buffer for liquidations * any necessary insurance fund draws and/or social loss can occur * at position closure, the taker fee is applied (so as to encourage close during reduce only mode) 4. Once the number of users in the market reaches zero, the remaining balance PnL Pool can be settled into the quote asset's [Revenue Pool](https://docs.drift.trade/about-v2/revenue-pool) ### Spot Markets[](https://docs.drift.trade/risk-and-safety/delisting-process#spot-markets) 1. The market immediately enters "reduce only mode" once an expiry date is set * this blocks new borrows, new deposits, and new buys in the market 2. After the expiry date, the market is set into "force close mode" \[TODO\] * deposits are sent back to the user's associated token address up to an amount that still satisfies their margin requirement * opens the possibility for liquidation of borrows and/or swaps of deposits to other accepted collateral [Introduction to Prediction Markets](https://docs.drift.trade/prediction-markets/prediction-markets-intro "Introduction to Prediction Markets") [Protocol Guard Rails](https://docs.drift.trade/risk-and-safety/protocol-guard-rails "Protocol Guard Rails") --- # Introduction – Drift Protocol 🛡️ Drift Safety Module Introduction ============ Drift Safety Module ("DSM") is a fully on-chain system for automatically covering bad debt and managing protocol risk. DSM introduces a more capital-efficient and automated way to protect the protocol without requiring governance intervention. DSM allows users to stake DRIFT into its insurance fund. DSM enhances the resilience of the Drift Protocol by introducing an automated staking system. If a deficit occurs in a given asset, DSM enables the corresponding staked assets to be act as a backstop for any bankruptcies, removing the need for governance decisions or manual intervention. This creates a more efficient, responsive, and predictable safety mechanism for the protocol and its users. DSM can be interacted with using the app.drift.trade interface. Safety Incentives[](https://docs.drift.trade/drift-safety-module#safety-incentives) ------------------------------------------------------------------------------------ The potential incentives for the safety module can include what is outlined in a successfully passed governance proposal by the DAO ([here (opens in a new tab)](https://driftgov.discourse.group/t/launch-drift-staking-vault-fee-discounts-for-drift-stakers/12) ). Overtime, further utility functions can be added to DRIFT across validator and other network functions through DAO proposals. Slashing Risk and Deficit Protection[](https://docs.drift.trade/drift-safety-module#slashing-risk-and-deficit-protection) -------------------------------------------------------------------------------------------------------------------------- In return for earning safety incentives, stakers accept the possibility of slashing if a deficit arises on the specific pool and asset they have staked. Staking risk is isolated to the specific asset and network where the DRIFT is staked. For example, staking DRIFT helps cover bad debt in DRIFT pairs only. In the case of a bankruptcy in DRIFT markets, staked DRIFT would potentially be liquidated. Similar to other Insurance Fund pools on Drift, the risk of bankruptcies is compensated by the revenue pool. [Risk Parameters](https://docs.drift.trade/risk-and-safety/risk-parameters "Risk Parameters") [Audits](https://docs.drift.trade/security/audits "Audits") --- # Audits – Drift Protocol 🔐 Security Audits Audits ====== ### Trail of Bits[](https://docs.drift.trade/security/audits#trail-of-bits) **Overview** Drift Protocol engaged Trail of Bits (TOB) to audit the security of its decentralized exchange and smart contract. Founded in 2012 and headquartered in New York, TOB provides technical security assessment and advisory services and specializes in software testing and code review projects. TOB is recognized as a Tier-1 security auditor, having worked with notable clients such as Google and Microsoft. From November 7 to December 2, 2022, the TOB team conducted a security audit of Drift Protocol’s decentralized exchange. TOB’s testing efforts were focused on the identification of flaws that could result in a compromise of confidentiality, integrity, or availability of Drift’s decentralized exchange and smart contract. The audit was conducted by TOB with full knowledge of the target system, including access to the source code and documentation. TOB utilized a mix of static and dynamic testing of the target system and its codebase, using both automated and manual processes. **Audit Result** The audit did not uncover any high-severity flaws that could impact system confidentiality, integrity, or availability. After the initial audit findings, between January 23 and January 25, 2023, Trail of Bits reviewed the fixes and mitigations implemented by Drift Protocol to resolve the issues described in this report. _A summary of outstanding findings is shown below._ ![](https://docs.drift.trade/_next/image?url=%2F_next%2Fstatic%2Fmedia%2FUJlUS9AzTG1yI-iSq2EOl_auditresult.81e28689.png&w=3840&q=75) A full listing of unresolved or partially resolved findings can be found on page 73 of the TOB Audit Report (Report). The undetermined finding relates to Testing code used in production and is described in further detail on page 77 of the Report. View the full report [here (opens in a new tab)](https://www.drift.trade/audit) . ### Neodyme[](https://docs.drift.trade/security/audits#neodyme) Scope: protocol-v2 Authored: May 10th 2024 Last Updated: June 27th 2024 View the full report [here (opens in a new tab)](https://cdn.prod.website-files.com/6310e7dee49f0866da8eed4c/6686bbdfe7c6e5a997cc51bc_Neodyme%20-%20Drift%20Security%20Audit.pdf) . ### Ottersec[](https://docs.drift.trade/security/audits#ottersec) Scope: [Metamask Snap "Connect" by Drift (opens in a new tab)](https://github.com/drift-labs/snap-solana) View the full report [here (opens in a new tab)](https://www.drift.trade/connect-by-drift-security-audit-by-ottersec) [🛡️ Drift Safety Module](https://docs.drift.trade/drift-safety-module "🛡️ Drift Safety Module") [Bug Bounty](https://docs.drift.trade/security/bug-bounty "Bug Bounty") --- # Protocol Guard Rails – Drift Protocol ⛑️ Risk and Safety Protocol Guard Rails Protocol Guard Rails ==================== Oracle Validity[](https://docs.drift.trade/risk-and-safety/protocol-guard-rails#oracle-validity) ------------------------------------------------------------------------------------------------- Drift Protocol's dependence on external oracle accounts requires thoughtful consideration of the data point in the streams received. In the program [\[code\] (opens in a new tab)](https://github.com/drift-labs/protocol-v2/blob/e04139e49e41dbbbaecbd5af9f038f6ce194f591/programs/clearing_house/src/math/oracle.rs#L15) , this is encoded as a spectrum from Valid to Invalid, with a few different categories of questionability that depend on the action taken (ordered by severity): * **Invalid** * **TooVolatile** * **TooUncertain** * **InsufficientDataPoints** * **StaleForMargin** * **StaleForAMM** * **Valid** The processing of new data is as follows: * retrieve new data point * sanitize new data point * updates state variables * check the validity of unsanitized new data point v.s. updated state Processing data this way is meant to prevent a single new data point from creating a shock to the state variables (i.e. TWAP). A complete list of block conditions for actions is described. Notes: * The on-chain oracle TWAP calculation will also be shrunk proportional to the duration of the invalid period to avoid erroneous funding payment magnitudes. * Blocking on InsufficientDataPoints can help improve resiliency against oracle manipulation. ### Oracle Divergence[](https://docs.drift.trade/risk-and-safety/protocol-guard-rails#oracle-divergence) For perpetuals markets, there are checks to `validate_market_within_price_band` for the following actions: * fill\_order * settle\_pnl * resolve\_perp\_pnl\_deficit The check validates that the 5-minute oracle twap vs amm reserve price is within ~10% (see `PriceDivergenceGuardRails` for exact parameters). Its important to note that: 1. amm reserve price always update with valid oracle data for amm and; 2. new data points for 5-minute oracle twap are sanitized to be within 10, 20, or 50% of the last twap value (depending on the `ContractTier`) Thus, it may take multiple intervals to bypass these circuit breakers for sufficiently large price moves. For spot markets, there are safety initial margin requirement checks for the following actions: * place\_order * withdraw A user's asset / liabilities when calculating total collateral for initial margin checks for withdraws and placing orders will be the lesser / greater (respectively) of the 5-minute oracle twap and current oracle price. This lowers leverage extended by the protocol to users with positions in volatile markets. ### Exchange & Market Status[](https://docs.drift.trade/risk-and-safety/protocol-guard-rails#exchange--market-status) ExchangeStatus and MarketStatus can be updated to prevent certain actions when specific issues are identified (described [here (opens in a new tab)](https://github.com/drift-labs/protocol-v2/blob/8b46cfc628f317e4f07cd62f111dd73fabff8a96/programs/clearing_house/src/state/state.rs#L35) ). These actions can include: * funding rate updates; * liquidations; * AMM fills; * any fills; and * withdraws [Delisting Process](https://docs.drift.trade/risk-and-safety/delisting-process "Delisting Process") [Risk Parameters](https://docs.drift.trade/risk-and-safety/risk-parameters "Risk Parameters") --- # Bug Bounty – Drift Protocol 🔐 Security Bug Bounty Bug Bounty ========== ### Program Overview[](https://docs.drift.trade/security/bug-bounty#program-overview) This bug bounty is specifically for Drift's smart contract code; client / UI only bugs are omitted. Drift's smart contract is [open-source (opens in a new tab)](https://github.com/drift-labs/protocol-v2) . | **Severity** | **Description** | **Bug Bounty** | | --- | --- | --- | | Critical | Bugs that freeze user funds or drain the contract's holdings or involve the theft of funds without user signatures. | 10% of the value of the hack up to $500,000. | | High | Bugs that could _temporarily_ freeze user funds or incorrectly assign value to user funds. | $10,000 to $50,000 per bug, assessed on a case-by-case basis | | Medium/Low | Bugs that don't threaten user funds | $1,000 to $5,000 per bug, assessed on a case-by-case basis | The severity guidelines are based on [Immunefi's classification system (opens in a new tab)](https://immunefi.com/severity-updated/) . Note that these are simply guidelines for the severity of the bugs. Each bug bounty submission will be evaluated on a case-by-case basis. ### Submission[](https://docs.drift.trade/security/bug-bounty#submission) Please email [hello@drift.trade](mailto:hello@drift.trade) with a detailed description of the attack vector. For critical and moderate bugs, we require a proof of concept done on a privately deployed mainnet contract. We will reach back out in 1 business day with additional questions or the next steps on the bug bounty. ### Bug Bounty Payment[](https://docs.drift.trade/security/bug-bounty#bug-bounty-payment) Bug bounties will be paid in USDC. Alternative payment methods can be used on a case-by-case basis. ### Invalid Bug Bounties[](https://docs.drift.trade/security/bug-bounty#invalid-bug-bounties) The following are out of scope for the bug bounty: * Attacks that the reporter has already exploited themselves, leading to damage * Attacks requiring access to leaked keys/credentials * Attacks requiring access to privileged addresses (governance, admin) * Incorrect data supplied by third-party oracles (This does not exclude oracle manipulation/flash loan attacks) * Lack of liquidity * Third-party, off-chain bot errors (for instance bugs with an arbitrage bot running on the smart contracts) * Best practice critiques * Sybil attacks * Attempted phishing or other social engineering attacks involving Drift contributors or users * Denial of service, or automated testing of services that generate significant traffic. * Any submission violating Immunefi's rules [Audits](https://docs.drift.trade/security/audits "Audits") [Risks](https://docs.drift.trade/security/risks "Risks") --- # Risks – Drift Protocol 🔐 Security Risks Risks ===== All DeFi protocols, including Drift, come with risks, which are important to understand before depositing significant amounts of crypto. Some of the main risks involved in using Drift are outlined here. Further risk parameters are also set out in and [Risk Parameters](https://docs.drift.trade/risk-and-safety/risk-parameters) . **Smart Contract and UI Risk** There is a risk that the smart contract or UI has a bug or exploit for unexpected behaviour resulting in loss of funds. This risk is inherent to all smart contracts and relies upon the discipline of the development community, core contributors, and auditors. **Blockchain Risk** The Solana blockchain remains under development, which creates technological, uncertainty and security risks that Drift has no control over. The cost of transacting on the Solana blockchain is variable and may increase or decrease at any time causing an impact on any activities taking place on the Solana blockchain, which may result in losses, price fluctuations or increased costs. **Oracle Risk** Drift relies on Pyth for their price feeds to power liquidations. There is a risk that these oracles report incorrect prices which can result in wrongful liquidations and loss of all funds. **Levered/Social Loss Risk** In the event of sharp price movements, traders with levered positions can lose more than their collateral value. In the event of the Insurance Fund not being sufficiently capitalised, these losses will be socialised across market participants. **Liquidation Risk** Drift offers both leveraged perpetual swaps and borrow/lend. For perpetual swaps, there is the risk of liquidation when a user's margin ratio poses a stability risk to the exchange. The user's collateral can get liquidated when the value of the user's collateral drops below the user's maintenance margin fraction. **Long/Short Imbalance Risk** Drift's AMM is the counterparty to all trades taken against the AMM. This means that the AMM itself has delta risk, and this risk is magnified when market conditions skew on either side and the imbalance between longs and shorts increases. The AMM has protections in place to prevent the long short imbalance from skewing too heavily to either side. More information on that is here at: [Drift AMM](https://docs.drift.trade/about-v2/drift-amm) . Despite these protections, there is still a risk that the AMM will be exposed to delta risk in periods of significant volatility. **No Off-Setting Loss Risk** The unrealised P&L users can lock in from entering and exiting a trade against the AMM is technically unbounded (e.g. if BTC goes toward infinity). Whilst a user can achieve this unrealised gain, it is important to note that an offsetting loss (or sufficient fees collected) is necessary before the unrealised gain can be settled in full and withdrawable as collateral by the user. Additionally, if the unrealised P&L imbalance exceeds its per-market threshold, those unrealised gains may be discounted by the margining system (initial, not maintenance) to prevent large borrows against it. This discounting would only impact new positions being opened and would not affect a user's liquidation threshold. These rules are systemitised and can be read more in [P&L](https://docs.drift.trade/profit-loss/profit-loss-intro) and [Margin](https://docs.drift.trade/trading/margin) **Untimely Liquidation Risk** In the event of large-scale liquidations or market turmoil, there is a possibility that positions and balances are not able to be liquidated in time and are unable to cover the losses taken out by the liquidated user. The shortfall "or negative balance" is treated as levered losses. In the past, levered losses in the main pool have been filled via top-ups from the Insurance fund. In the event that the Insurance Fund is depleted, there will be a socialized loss in the system. **100% Utilization Risk** When an asset is fully utilized (100% of the supply is lent out), there will be no tokens left in the pool, which means withdrawals and borrows will fail. Users will have to wait until the utilization rate goes down, either through some users repaying their loans or depositing new funds before they can withdraw or borrow. A user is more likely to be affected by this if their deposit represents a large share of the pool, or if the asset has extremely high borrow demand. [Bug Bounty](https://docs.drift.trade/security/bug-bounty "Bug Bounty") [🔤 Glossary](https://docs.drift.trade/glossary "🔤 Glossary") --- # Historical Data Glossary – Drift Protocol ⏳ Historical Data Historical Data Glossary Historical Data Glossary ======================== 🟣 v2[](https://docs.drift.trade/historical-data/historical-data-glossary#-v2) ------------------------------------------------------------------------------- ℹ️ This is extensive list for every API endpoint. Choose the category of historical data you're analysing in the right sidebar for quick access. ➡️ ➡️ ➡️ ### Shared columns[](https://docs.drift.trade/historical-data/historical-data-glossary#shared-columns) Columns in the table below are part of each category: | Column | Unit | Precision | Description | | --- | --- | --- | --- | | ts | int | seconds(since 1970) | Unix timestamp of the event. | | txSig | pubkey | | Transaction signature. | | slot | int | | Slot number of the event. | | user | pubkey | | | | amount | int | | | | programId | pubkey | | Solana program identifier (AMM\* = Drift protocol mainnet). | | marketType | perp/spot | | Type of market where the order was filled ("Spot", "Perpetual"). | | marketIndex | int | | Perpetual contract [market index (opens in a new tab)](https://github.com/drift-labs/protocol-v1/blob/master/sdk/src/constants/markets.ts) | | spotMarketIndex | int | | Index of the spot market. | | perpMarketIndex | int | | Index of the perpetual contract market. | | userAuthority | pubkey | | Public key of the user's authority account (wallet). | | oraclePrice | int | | Oracle price at the time of an event (provided by Pyth/Switchboard). | * * * ### Trades[](https://docs.drift.trade/historical-data/historical-data-glossary#trades) | Column | unit | precision | description | | --- | --- | --- | --- | | fillerReward | int | | Reward received by the filler for filling the order. | | baseAssetAmountFilled | int | | Amount of the base asset filled in the order. | | quoteAssetAmountFilled | int | | Amount of the quote asset filled in the order. | | takerFee | int | | Fee charged to the taker for filling the order. | | makerRebate | int | | Rebate provided to the maker for placing the order. | | referrerReward | int | | Reward received by the referrer for referring the order. | | quoteAssetAmountSurplus | int | | Amount of the quote asset remaining unfilled after the order is completed. | | takerOrderBaseAssetAmount | int | | Total amount of the base asset the taker ordered to buy or sell. | | takerOrderCumulativeBaseAssetAmountFilled | int | | Cumulative amount of the base asset filled for the taker's order. | | takerOrderCumulativeQuoteAssetAmountFilled | int | | Cumulative amount of the quote asset filled for the taker's order. | | makerOrderBaseAssetAmount | int | | Total amount of the base asset the maker ordered to buy or sell. | | makerOrderCumulativeBaseAssetAmountFilled | int | | Cumulative amount of the base asset filled for the maker's order. | | makerOrderCumulativeQuoteAssetAmountFilled | int | | Cumulative amount of the quote asset filled for the maker's order. | | makerFee | int | | Fee charged to the maker for placing the order (if not a maker rebate). | | action | fill | | Action type for the order fill event (e.g., "Fill"). | | actionExplanation | orderExpired/orderFilledWithMatch | | Explanation of the action type. | | filler | pubkey | | Address of the entity that filled the order. | | fillRecordId | int | | Unique identifier for the order fill record. | | taker | pubkey | | Address of the taker who placed the order. | | takerOrderId | int | | Unique identifier for the taker's order. | | takerOrderDirection | long/short | | Direction of the taker's order (e.g., "Buy", "Sell"). | | maker | pubkey | | Address of the maker who placed the opposing order. | | makerOrderId | int | | Unique identifier for the maker's order. | | makerOrderDirection | long/short | | Direction of the maker's order (e.g., "Buy", "Sell"). | | spotFulfillmentMethodFee | int | | Fee associated with the spot fulfillment method used. | ### Market Trades[](https://docs.drift.trade/historical-data/historical-data-glossary#market-trades) | Column | unit | Precision | Description | | --- | --- | --- | --- | | fillerReward | int | | Reward received by the filler for filling the order. | | baseAssetAmountFilled | int | | Amount of the base asset filled in the order. | | quoteAssetAmountFilled | int | | Amount of the quote asset filled in the order. | | takerFee | int | | Fee charged to the taker for filling the order. | | makerRebate | int | | Rebate provided to the maker for placing the order. | | referrerReward | int | | Reward received by the referrer for referring the order. | | quoteAssetAmountSurplus | int | | Amount of the quote asset remaining unfilled after the order. | | takerOrderBaseAssetAmount | int | | Total amount of the base asset the taker ordered to buy or sell. | | takerOrderCumulativeBaseAssetAmountFilled | int | | Cumulative amount of the base asset filled for the taker's order. | | takerOrderCumulativeQuoteAssetAmountFilled | int | | Cumulative amount of the quote asset filled for the taker's order. | | makerOrderBaseAssetAmount | int | | Total amount of the base asset the maker ordered to buy or sell. | | makerOrderCumulativeBaseAssetAmountFilled | int | | Cumulative amount of the base asset filled for the maker's order. | | makerOrderCumulativeQuoteAssetAmountFilled | int | | Cumulative amount of the quote asset filled for the maker's order. | | makerFee | int | | Fee charged to the maker for placing the order (if not a maker rebate). | | action | fill | | Action type for the order fill event (e.g., "Fill"). | | actionExplanation | orderFilledWithMatch/ orderFilledWithMatchJit/ orderFilledWithAmmjit | | Explanation of the action type. | | filler | pubkey | | Address of the entity that filled the order. | | fillRecordId | int | | Unique identifier for the order fill record. | | taker | pubkey | | Address of the taker who placed the order. | | takerOrderId | int | | Unique identifier for the taker's order. | | takerOrderDirection | long/short | | Direction of the taker's order (e.g., "Buy", "Sell"). | | maker | pubkey | | Address of the maker who placed the opposing order. | | makerOrderId | int | | Unique identifier for the maker's order. | | makerOrderDirection | long/short | | Direction of the maker's order (e.g., "Buy", "Sell"). | | spotFulfillmentMethodFee | int | | Fee associated with the spot fulfillment method used. | ### Funding Rates[](https://docs.drift.trade/historical-data/historical-data-glossary#funding-rates) | Column | unit | precision | Description | | --- | --- | --- | --- | | recordId | int | | Unique order fill identifier. | | fundingRate | int | | Perpetual contract funding rate (long/short). | | fundingRateLong | int | | Funding paid by long positions. | | fundingRateShort | int | | Funding paid by short positions. | | cumulativeFundingRateLong | int | | Long positions' cumulative funding. | | cumulativeFundingRateShort | int | | Short positions' cumulative funding. | | oraclePriceTwap | int | | TWAP of oracle price (period). | | markPriceTwap | int | | TWAP of mark price (period). | | periodRevenue | int | | Market revenue for a specific period. | | baseAssetAmountWithAmm | int | | Total base asset in the AMM pool. | | baseAssetAmountWithUnsettledLp | int | | Unsettled base asset with LPs. | ### Funding Payments[](https://docs.drift.trade/historical-data/historical-data-glossary#funding-payments) | Column | unit | precision | description | | --- | --- | --- | --- | | fundingPayment | int | | Amount of funding paid by the user (positive for long, negative for short). | | baseAssetAmount | int | | Amount of the base asset involved in the funding payment. | | userLastCumulativeFunding | int | | User's last cumulative funding rate at the time of the event. | | ammCumulativeFundingLong | int | | AMM's cumulative funding rate for long positions at the time of the event. | | ammCumulativeFundingShort | int | | AMM's cumulative funding rate for short positions at the time of the event. | ### Deposits[](https://docs.drift.trade/historical-data/historical-data-glossary#deposits) | Column | unit | Precision | Description | | --- | --- | --- | --- | | marketDepositBalance | int | | Current total market deposits. | | marketWithdrawBalance | int | | Current total market withdrawals. | | marketCumulativeDepositInterest | int | | Total deposit interest accrued. | | marketCumulativeBorrowInterest | int | | Total borrow interest accrued. | | totalDepositsAfter | int | | Total market deposits after this event. | | totalWithdrawsAfter | int | | Total market withdrawals after this event. | | depositRecordId | int | | Unique identifier for the deposit/withdrawal record. | | direction | deposit/withdrawal | | Deposit or withdrawal. | | explanation (optional) | str | | | ### Liquidations[](https://docs.drift.trade/historical-data/historical-data-glossary#liquidations) | Column | unit | precision | description | | --- | --- | --- | --- | | liquidationType | liquidatePerp/ liquidateSpot/ liquidateBorrowForPerpPnl/ liquidatePerpPnlForDeposit/ perpBankruptcy/ spotBankruptcy | | Liquidation type | | liquidator | pubkey | | Liquidator | | marginRequirement | int | | Minimum collateral required | | totalCollateral | int | | User's total collateral | | marginFreed | int | | Collateral returned to user | | liquidationId | int | | Unique liquidation ID | | bankrupt | bool | | User became bankrupt | | canceledOrderIds | ListContainer | | Array of canceled order IDs during liquidation | | liquidatePerp (marketIndex, oraclePrice, ...) | int | | Liquidation type with additional details. | | liquidateSpot (assetMarketIndex, assetPrice, ...) | int | | Liquidation type with additional details. | | liquidateBorrowForPerpPnl (perpMarketIndex, marketOraclePrice, ...) | int | | Liquidation type with additional details. | | liquidatePerpPnlForDeposit (perpMarketIndex, marketOraclePrice, ...) | int | | Liquidation type with additional details. | | perpBankruptcy (marketIndex, pnl, ...) | int | | Liquidation type with additional details. | | spotBankruptcy (marketIndex, borrowAmount, ...) | int | | Liquidation type with additional details. | ### Settle PNL[](https://docs.drift.trade/historical-data/historical-data-glossary#settle-pnl) | Column | Unit | Precision | Description | | --- | --- | --- | --- | | pnl | int | | User's profit or loss. | | baseAssetAmount | int | | Amount of base asset involved. | | quoteAssetAmountAfter | int | | Amount of quote asset after settlement. | | quoteEntryAmount | int | | Amount of quote asset before settlement. | | settlePrice | int | | Settlement price. | | explanation | none | | | ### LP (BAL)[](https://docs.drift.trade/historical-data/historical-data-glossary#lp-bal) | Column | Unit | Description | | --- | --- | --- | | action | addLiquidity / settleLiquidity | | | nShares | int | Number of perpetual contract shares traded. | | deltaBaseAssetAmount | int | Change in base asset position due to the trade. | | deltaQuoteAssetAmount | int | Change in quote asset position due to the trade. | | pnl | int | Profit or loss from the trade. | ### Insurance Fund[](https://docs.drift.trade/historical-data/historical-data-glossary#insurance-fund) | Column | Unit | Precision | Description | | --- | --- | --- | --- | | vaultAmountBefore | int | | Total amount deposited into the vault before the event. | | insuranceVaultAmountBefore | int | | Total amount in the insurance vault before the event. | | totalIfSharesBefore | int | | Total number of IF shares in circulation before the event. | | totalIfSharesAfter | int | | Total number of IF shares in circulation after the event. | | userIfFactor | int | | User's individual IF factor before the event. | | totalIfFactor | int | | Total IF factor for all users before the event. | ### Insurance Fund Stake[](https://docs.drift.trade/historical-data/historical-data-glossary#insurance-fund-stake) | Column | Unit | Precision | Description | | --- | --- | --- | --- | | action | stakeTransfer | | | | ifSharesBefore | int | | Total IF shares in circulation before staking. | | userIfSharesBefore | int | | User's individual IF share balance before staking. | | totalIfSharesBefore | int | | Total IF factor for all users before staking. | | ifSharesAfter | int | | Total IF shares in circulation after staking. | | userIfSharesAfter | int | | User's individual IF share balance after staking. | | totalIfSharesAfter | int | | Total IF factor for all users after staking. | | insuranceVaultAmountBefore | int | | Total amount in the insurance vault before staking. | 🟪 v1[](https://docs.drift.trade/historical-data/historical-data-glossary#-v1) ------------------------------------------------------------------------------- ### Trades[](https://docs.drift.trade/historical-data/historical-data-glossary#trades-1) | Column | unit | Precision | description | Ext. Link | | --- | --- | --- | --- | --- | | id | int | | | | | programId | publickey | | the on-chain program interacted with (AMM\* == drift protocol mainnet) | | | recordId | int | | sequential count of all trades that ever occured (ensures proper ordering vs by the second timestamp) | | | userAuthority | publickey | | | | | user | publickey | | | | | baseAssetAmount | int | 1e13 | BASE amt of swap (e.g. SOL-PERP) | | | quoteAssetAmount | int | 1e6 | USDC of swap | | | markPriceBefore | int | 1e10 | | | | markPriceAfter | int | 1e10 | | | | fee | int | 1e6 | fee paid to AMM by user for swap | | | liquidation | bool | | was trade a forced liquidation | | | direction | Long \| Short | | did user go Long (buy) or Short (sell) the Base amt | | | blockChainTimeStamp | int | seconds(since 1970) | unix on-chain time stamp | | | serverTimeStamp | int | seconds(since 1970) | exchange history server off-chain time stamp (can be delayed due to outages) | | | marketIndex | int | | market Index in Markets Account that user swapped | [markets (opens in a new tab)](https://github.com/drift-labs/protocol-v1/blob/master/sdk/src/constants/markets.ts) | | oraclePrice | int | 1e10 | oracle price at time of swap (provided by pyth/switchboard) | | [Historical Data v2](https://docs.drift.trade/historical-data/historical-data-v2 "Historical Data v2") [Overview](https://docs.drift.trade/fuel/overview "Overview") --- # Additional Resources and Data – Drift Protocol Additional Resources and Data Additional Resources and Data ============================= **[Protocol Owned Holdings over Time (opens in a new tab)](https://drift-public.s3.eu-central-1.amazonaws.com/Drift+Protocol+Holdings.csv) ** **[Perps Order Breakdown over Time (opens in a new tab)](https://drift-public.s3.eu-central-1.amazonaws.com/Perp+Orders+Breakdown.csv) ** **[Monthly volume across Perps, Spot and Swaps (opens in a new tab)](https://drift-public.s3.eu-central-1.amazonaws.com/Monthly+Volume.csv) ** [🔤 Glossary](https://docs.drift.trade/glossary "🔤 Glossary") [Terms of Use](https://docs.drift.trade/legal-and-regulations/terms-of-use "Terms of Use") --- # Glossary – Drift Protocol 🔤 Glossary Glossary ======== **General** | **Term** | **Definition** | | --- | --- | | Clearing House | margin/accounting engine of the protocol | | AMM | means an Automated Market Maker is Drift's source of constant liquidity that is based on the constant product formula `x*y=k` balancing the reserves. | | Keeper Network | refers to the network of Keeper Bots on Drift that facilitates the exchange of liquidity. For more information, read [Keeper Bots](https://docs.drift.trade/about-v2/keepers) | | JIT | means to Just-In-Time. | | JIT Auction | a "Just-in-Time" Auction refers to the dutch auction mechanism that lets Market Makers provide liquidity to Takers. | | Market Makers / Makers | refers to parties on the platform that provides liquidity to the exchange. Liquidity 'provided' by Market Makers can be 'taken' by Takers. Market Makers includes parties that place orders on Drift with the 'Post-Only' function. This means the order will be placed on the decentralised orderbook and will only add to the liquidity available. Market Makers also include parties that provide liquidity via the JIT mechanism. | | Takers | refer to users on the platform that 'take' liquidity from the exchange. Takers take liquidity made available by Market Makers or Drift's AMM. | | BAL providers | BAL Providers are users who hold BAL Shares in a particular Perpetuals Market and increase the AMM's liquidity. These users receive positions pro-rate:e.g. their share amount of the AMM's constant product invariant (k). Adding/Removing BAL shares increases/decreases the AMM's k | | Longing | means you are speculating on the price of the asset going up. | | Shorting | means you are speculating on the price of the asset going down. | | TWAP | means Time Weighted Average Price which is the average price of the Oracle over a specified period of time. This approximation is calculated on-chain during program interactions with the account. | **Market Info** | **Term** | **Description** | **Example** | | --- | --- | --- | | Index / Oracle Price | is the price of the underlying asset (currently: as reported by Pyth). | $201.01 | | Mark Price | is the price of the relevant market. | $201.05 | | Funding Rate | refers to 1/24 the average premium every hour;if positive, longs pay shorts. if negative, shorts pay longs;see for more details | .0012% | | Open Interest | refers to the total size of all positions (long and short) in the relevant market. | 181 SOL | | 24h Volume | refers to the total volume traded in the past day in the relevant market. | $1.04M | **Position Table** | **Term** | **Description** | **Example** | | --- | --- | --- | | Market | means a base / quote asset pair. | SOL/USD | | Direction | means the position's bet on price change. | LONG,SHORT | | Size | means the position's base asset value. | 2.3555 SOL | | Notional | means the position's quote asset value. | $1,000 | | Entry Price | means the average price paid (cost basis) for acquiring position. | $200 | | Exit Price | means the average price realised if closing entire position. | $200 | | Liquidation Price | means the soft estimate of price where liquidation of the account will occur. | None | | P&L (Profit & Loss) | means the Profit and/or Loss of position;Calculated on difference between EXIT PRICE and ENTRY PRICE. | $0 | | Action | Opens modal for reducing/closing position. | ClosePosition | | **Term** | **Description** | **Example** | | --- | --- | --- | | Total Collateral | means the total available USD value of weighted collateral and P&L for margin trading | 101.01 | | Unrealised P&L | means the sum of P&L available in all open positions that have not been realised (settled) by the user yet. | 1 | | Unrealised Funding P&L | means the unrealised amount collected/paid for funding payments. (will be automatically realised upon next user action) | .01 | | Free Collateral | means the value of collateral that can be used to open new risk-increasing positions. | 0.5 | | Leverage | means Total Notional Position Size / Total Collateral. | 5x | | Margin Ratio | means Total Collateral / Total Notional Position Size. | 20% | | Maintenance Margin Req. | is the margin ratio at which users will liquidate back up to the liquidation buffer. | 5% | | `maintenanceRatio` | maintenanceMarginReq / Total Collateral | | **AMM Specific** | **Term** | **Definition** | | --- | --- | | K | is the curve invariant, currently for constant product;`k = base_asset_reserve * quote_asset_reserve` | | Base Asset Reserve | means the virtual base reserves for a market (SOL reserves). | | Quote Asset Reserve | means the virtual quote reserves for a market (e.g. USDC reserves in a SOL/USDC virtual pool). | | Peg Multiplier | means the magnitude of the quote asset reserve. For instance, one virtual quote asset reserve is a peg multiplier amount of the quote asset. A peg multiplier ensures that the base asset reserve and the quote asset reserve are balanced at the initialisation of the curve while ensuring that the starting price of the pool is equivalent to the oracle price of the base asset at initialisation. | | Reserve Price | in the AMM, is defined as `(quote_asset_reserve * peg_multiplier) / base_asset_reserve`. It is the true reserves price prior to any spread logic. | | Bid Price | is the Price available to sell from the AMM, before slippage. | | Ask Price | is the Price available to buy from the AMM, before slippage. | | Mark Price | means the Market Price. Average of current Bid and Ask Price. | | Oracle Price | means the latest composite price from oracles. Oracle price is interchangeable with index price. | | Repeg | means modifying the peg multiplier which means re-pegging the curve such that the mark price is closer to the oracle price. | | Adjusting K | means modifying the curve's invariant `k` by scaling the base/quote asset reserves. For instance, this modifies the default slippage of a swap. | | Terminal Price | means the mark price if all users atomically closed their positions and no repegs/k adjustments occurred (should be equal to the peg multiplier if all k adjustments were done during a balanced market). | **Users** | **Term** | **Definition** | | --- | --- | | base asset amount | The amount of base currency (e.g. SOL-PERP) held by a single user. | | net user position | Current longs - shorts in a given market. | [Risks](https://docs.drift.trade/security/risks "Risks") [Additional Resources and Data](https://docs.drift.trade/additional-resources-data "Additional Resources and Data") --- # Overview – Drift Protocol 💧 FUEL Overview ![Fuel Droplet](https://docs.drift.trade/assets/fuel-droplet-large.svg) FUEL ==== ✅ **Season 2 of the Fuel campaign has ended as of June 2025. Thank you for your participation!** Overview[](https://docs.drift.trade/fuel/overview#overview) ------------------------------------------------------------ FUEL is Drift’s first on-chain loyalty program for Driftoors designed to recognise those who continue to use Drift and are active participants in its mission. Your activity won’t go unrecognized — whether you’re actively trading perps or staking you can now kick things into high gear with FUEL. The FUEL program has been designed to take into consideration a broad range of activity throughout the Drift ecosystem. Your activity is represented with each FUEL you earn and you’ll be able to accelerate even faster with Activity Boosters. How do I Earn Fuel?[](https://docs.drift.trade/fuel/overview#how-do-i-earn-fuel) --------------------------------------------------------------------------------- Watch your FUEL grow with each click. FUEL earnings are continuously added to your account while performing various actions on Drift, and can be viewed at [app.drift.trade/fuel (opens in a new tab)](http://app.drift.trade/fuel) . The total FUEL earned reflects the activity across all of your subaccounts. The following activities on Drift earn FUEL: | Activity | Base Earn Rate | | --- | --- | | DRIFT Staking | 10 FUEL for every DRIFT staked for 28 days | | Taker Volume | 1 FUEL for every $1 in taker volume | | Maker Volume | 1 FUEL for every $1 in maker volume | Taker and maker FUEL earnings are added to your account immediately as the activity is completed. All earn rates that are time-based, such as DRIFT staking, are also continuously added, but the amount is divided over a 28-day period. Example: if you stake 100 DRIFT, and the earn rate is 10 FUEL per DRIFT staked for 28 days, after one day you will have earned about 35.7 FUEL (10 FUEL / 28 days \* 100 DRIFT). As the FUEL program continues to be rolled out, rewards for other activities like deposits/lending, borrowing, and having open interest may be added in the future. What are Boosters?[](https://docs.drift.trade/fuel/overview#what-are-boosters) ------------------------------------------------------------------------------- Activity boosters provide an accelerated earn rate for different activities. The boosted rate is multiplied with the base earn rate for the activity. Example: if the base earn rate for taker volume is 1 FUEL for every $1, and there's a booster of 5x in SOL-PERP, then the earn rate for SOL-PERP becomes 5 FUEL for every $1 in taker volume as long as the booster is active. All currently active boosters and their rates can be found at: [app.drift.trade/fuel (opens in a new tab)](http://app.drift.trade/fuel) . What can I redeem FUEL for?[](https://docs.drift.trade/fuel/overview#what-can-i-redeem-fuel-for) ------------------------------------------------------------------------------------------------- In the future, you’ll be able to redeem your FUEL for DRIFT. The Drift DAO [passed a proposal (opens in a new tab)](https://app.realms.today/dao/DRIFT/proposal/9s2FsXuKwbcBTZFNhy1jBiLKFYDCz52vBixw9oZfeyaC) for the Season 1 Fuel Campaign. The details are as follows: ### Summary of Season 1 Fuel Campaign[](https://docs.drift.trade/fuel/overview#summary-of-season-1-fuel-campaign) Over the past year, Drift has distributed ~12% of total token supply to reward community members and foster growth as part of the initial TGE in May. Now, with FUEL, Drift is building on that foundation: Up to 7.82% of the total DRIFT supply will be allocated through a milestone-based campaign. Real trading activity will be recognised, wash trading disqualified, and all users will be treated equally via Linear Distribution mechanism (no tiers). Drift is continuing its commitment to community ownership by ensuring the distribution of DRIFT tokens over the coming years, aligning users with the protocol’s long-term vision and success. Our goal is simple: grow Solana DeFi and solidify Drift as the premier home of DeFi on Solana. ### Token Supply[](https://docs.drift.trade/fuel/overview#token-supply) This proposal suggests allocating a maximum of 7.82% of the total Drift token supply for distribution via the FUEL S2 campaign, concluding in June 2025. This 7.82% comes from: 7% from the Community & Ecosystem allocation 0.82% rolled forward from previously unclaimed TGE tokens Currently, 8.2 million DRIFT is set aside for FUEL (per a prior governance vote, details here), originating from unclaimed DRIFT tokens from the first airdrop in May 2024. ### Milestone-Based Amount[](https://docs.drift.trade/fuel/overview#milestone-based-amount) The total DRIFT allocation for FUEL will scale with Drift’s trading volume success. If the community and protocol excel in driving volume, more tokens become available for claiming. ### Milestones[](https://docs.drift.trade/fuel/overview#milestones) Milestone 1: 15B Total Perp Volume Milestone 2: 25B Total Perp Volume Milestone 3: 40B Total Perp Volume Milestone 4: 60B Total Perp Volume Milestone 5: 100B Total Perp Volume ### Milestone Amounts (On top of the existing 8.2M)[](https://docs.drift.trade/fuel/overview#milestone-amounts-on-top-of-the-existing-82m) No Milestones Hit: 28.2M DRIFT (2.82% of total supply) Milestone 1: 38.2M DRIFT (3.82% of total supply) Milestone 2: 48.2M DRIFT (4.82% of total supply) Milestone 3: 58.2M DRIFT (5.82% of total supply) Milestone 4: 68.2M DRIFT (6.82% of total supply) Milestone 5: 78.2M DRIFT (7.82% of total supply) Note: Milestone success is measured by total Perp Market Volume from campaign start (When vote is finalized) through campaign end (June 2025). ### Why These Milestones[](https://docs.drift.trade/fuel/overview#why-these-milestones) Achieving all milestones would place Drift among the top three derivatives platforms in crypto, and number one on Solana. This will demonstrate that the future of DeFi is Solana DeFi. ### Wash Trading Protection[](https://docs.drift.trade/fuel/overview#wash-trading-protection) To ensure organic trading volume, the Drift core team will actively monitor for suspicious activity. Accounts identified as engaging in wash trading or other manipulative behaviors will be flagged for disqualification from FUEL distribution. This ensures fairness for all legitimate participants. ### Linear Distribution[](https://docs.drift.trade/fuel/overview#linear-distribution) This will be a linear distribution. A linear distribution will ensure the commensurate recognition of users who’ve contributed most to Drift’s growth. Linear means no tiers and no minimum or maximum FUEL amounts. It means there will be no need to identify sybils as there will be no advantage to sybils. All Drift users will be considered equal. ### Claim Mechanism & Vest[](https://docs.drift.trade/fuel/overview#claim-mechanism--vest) Most Users: Receive an immediate unlock of their DRIFT upon claiming. Largest Users: A small subset of top holders will be subject to a 9-month vest (no cliff) to maintain strong alignment with the protocol’s long-term growth. This mirrors the TGE structure, where largest holders also had a vesting schedule. ### Timeline[](https://docs.drift.trade/fuel/overview#timeline) Start: ~17 Feb 2025 (post-governance vote) End: ~June 2025 Extending the campaign to June coincides with upcoming liquidity upgrades, ensuring all new and existing users get the best experience possible. * * * Disclaimer: Please be advised that any FUEL acquired through the FUEL program is solely for recognition purposes. Holding any FUEL holds no monetary or intrinsic value and cannot be redeemed for cash or any other form of currency. FUEL is not transferable, assignable, or tradable in any form. Drift reserves the right to modify, suspend, or terminate the Fuel program at any time without prior notice. Your participation in the FUEL program constitutes your acceptance of the above. [Historical Data Glossary](https://docs.drift.trade/historical-data/historical-data-glossary "Historical Data Glossary") [Introduction to Prediction Markets](https://docs.drift.trade/prediction-markets/prediction-markets-intro "Introduction to Prediction Markets") --- # Terms of Use – Drift Protocol Legal and Regulations Terms of Use [Additional Resources and Data](https://docs.drift.trade/additional-resources-data "Additional Resources and Data") [Disclaimer](https://docs.drift.trade/legal-and-regulations/disclaimer "Disclaimer") --- # Privacy Policy – Drift Protocol Legal and Regulations Privacy Policy [Disclaimer](https://docs.drift.trade/legal-and-regulations/disclaimer "Disclaimer") [Competition Terms](https://docs.drift.trade/legal-and-regulations/competition-terms "Competition Terms") --- # Disclaimer – Drift Protocol Legal and Regulations Disclaimer Disclaimer ========== Drift Protocol is a decentralised peer-to-peer protocol that people can use to trade with certain perpetuals, swaps, spot assets and provide passive liquidity to earn yield from overcollateralized borrows. The protocol is made up of free, public, open-source or source-available software including a set of smart contracts that are deployed on various blockchain networks, including, without limitation, the Solana blockchain. Your use of the Drift Protocol and this UI involves various risks, including, but not limited to, risks inherent to cryptographic systems and blockchain-based networks, and losses due to network services, bugs, the fluctuation of prices of tokens and other assets underlying derivatives contracts and swaps. Before using the Drift Protocol, you should review the Documentation available on our Site, the Terms of Use and the Risks to make sure you understand how the Drift Protocol works. Additionally, just as you can access email protocols such as SMTP through multiple email clients, you can access the Drift Protocol through a variety of web or mobile interfaces. You are responsible for doing your own diligence on those interfaces to understand the fees and risks they present. **DRIFT PROTOCOL IS EXPERIMENTAL AND IS PROVIDED TO YOU ON AN "AS IS” AND "AS AVAILABLE" BASIS.** **YOUR PARTICIPATION IN MAINNET IS ENTIRELY VOLUNTARY AND MUST STRICTLY ADHERE TO THE TERMS. BY PARTICIPATING IN MAINNET, YOU ACCEPT AND ACKNOWLEDGE THAT THERE ARE RISKS ASSOCIATED WITH PARTICIPATING INCLUDING, BUT NOT LIMITED TO, LOSS OF ALL FUNDS, THE RISK OF BUGS, ERRORS, TEMPORARY OR PERMANENT UNAVAILABILITY OF UNDERLYING INFRASTRUCTURE, FAILURE OF HARDWARE, SOFTWARE AND INTERNET CONNECTIONS, THE RISK OF MALICIOUS SOFTWARE INTRODUCTION, HARMFUL COMPONENTS AND SECURITY RISKS. YOU ACCEPT AND ACKNOWLEDGE THAT THE COMPANY WILL NOT BE RESPONSIBLE FOR ANY LOSSES, FAILURES, DISRUPTIONS, ERRORS, DISTORTIONS, DEFECTS OR DELAYS YOU MAY EXPERIENCE WHEN PARTICIPATING IN MAINNET, HOWEVER CAUSED.  THE PROTOCOL WILL NOT BE RESPONSIBLE OR LIABLE TO YOU FOR ANY LOSS, AND TAKES NO RESPONSIBILITY FOR, AND WILL NOT BE LIABLE TO YOU FOR YOUR PARTICIPATION IN MAINNET.** **ANY USE WILL BE AT YOUR OWN RISK, AND WITHOUT WARRANTIES BY DRIFT OF ANY KIND.** Although Drift Protocol has developed much of the initial code for the protocol, the protocol does not provide, own, or control Drift Protocol, which is run by smart contracts deployed on the Solana blockchain. By using Drift Protocol, you agree that no developer or entity involved in creating Drift Protocol will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of, Drift Protocol, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, loss of profits, cryptocurrencies, tokens, or anything else of value. By using Drift Protocol, you further agree to waive any loss, damage, liability, claim or demand against Drift Protocol and any entities involved in creating Drift Protocol. Use of the Protocol shall be at your own risk. [Terms of Use](https://docs.drift.trade/legal-and-regulations/terms-of-use "Terms of Use") [Privacy Policy](https://docs.drift.trade/legal-and-regulations/privacy-policy "Privacy Policy") --- # Competition Terms – Drift Protocol Legal and Regulations Competition Terms [Privacy Policy](https://docs.drift.trade/legal-and-regulations/privacy-policy "Privacy Policy") ---