Velocity Exchange Keeper Bots v2

repository·master·Indexed 41 days ago

https://github.com/velocity-exchange/keeper-bots-v2

A suite of automated bots (Filler, Liquidator, JIT Maker) for Drift Protocol v2 designed to maintain market efficiency and participate in protocol auctions on the Drift exchange. Includes configuration for Jito bundle strategies, Pyth Lazer Cranker, and detailed error codes for market operations.

Tokens
15.2K
Snippets
45
Records
61
Agent score
99%

What's inside Velocity Exchange Keeper Bots

  1. How the Filler Bot works

    master

    Filler bots match crossing orders on the exchange for a portion of taker fees. They maintain a copy of the DLOB (Decentralized Limit Order Book) to find orders and attempt to execute triggerable orders.

    Bot Types

    • filler: Standard filler.
    • spotFiller: Spot-specific filler.
    • fillerLite: A lightweight version for perp markets. Can be run on public RPCs for testing, but is less stable.

    Include these names in the enabledBots list in your config.yaml.

  2. How the JIT Maker Bot works

    master

    The JIT (Just-In-Time) maker bot supplies liquidity by participating in JIT auctions for perp markets. It uses the jit-proxy client to update bids and asks to match the current top-level market in the DLOB.

    Implementation Details

    • Risk: Running a JIT maker involves taking on positional risk.
    • Leverage: The sample implementation targets a specific leverage (e.g., TARGET_LEVERAGE_PER_ACCOUNT).
    • Execution: It uses JitterSniper for order execution.
    • Configuration: JIT makers require collateral. You can use forceDeposit in the config or deposit via the SDK/UI beforehand.
    • Subaccount Alignment: Ensure all subaccounts used in botConfigs.subaccounts are also enumerated in global.subaccounts to avoid initialization errors.
    global:
      subaccounts: [0, 1]
    
    botConfigs:
      jitMaker:
        botId: "jitMaker"
        dryRun: false
        subaccounts: [0, 1, 1]
        perpMarketIndicies: [0, 1, 2]
  3. How the Liquidator Bot works

    master

    The liquidator bot monitors spot and perp markets for bankrupt accounts and attempts to liquidate positions according to the protocol's liquidation process.

    Key Configuration Concepts

    • Derisking: By default, the bot derisks. Set disableAutoDerisking: true to disable the derisking loop if you want to manage risk manually.
    • Market Restriction: To restrict which markets are liquidated, use perpMarketIndicies and spotMarketIndicies.
    • Subaccount Mapping: Instead of global indices, you can use perpSubAccountConfig and spotSubAccountConfig to map specific subaccounts to specific market indices. These fields must be JSON strings.
    • Subaccount Requirement: Any subaccount used in botConfigs must also be listed in the global.subaccounts array to ensure the driftClient initializes correctly.
    botConfigs:
      ...
      liquidator:
        ...
        perpSubAccountConfig:
          "0": [0, 1, 2]
          "1": [3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
        spotSubAccountConfig:
          "0": [0, 1, 2]
    
    global:
      subaccounts: [0, 1]
  4. Deposit collateral for bots

    master

    Trading, liquidator, and JIT maker bots require collateral to maintain positions. A user must be initialized before depositing. You can use the CLI helper to deposit a specific amount of USDC, or use the Drift UI.

    # deposit 10,000 USDC
    yarn run dev --force-deposit 10000
  5. Configure the bot via YAML

    master

    You can configure the bot setup using a .yaml file. To run the bot with a specific configuration, use the --config-file flag.

    Configuration Schema Reference

    FieldTypeDescriptionDefault
    globalobjectGlobal configs applied to all running bots-
    global.endpointstringRPC endpoint to use-
    global.wsEndpointstring(optional) Websocket endpoint to usederived from global.endpoint
    global.keeperPrivateKeystring(optional) Private key to pay/sign transactionsKEEPER_PRIVATE_KEY env var
    global.initUserboolSet true to init a fresh userAccountfalse
    global.websocketboolSet true to run bots in websocket mode if compatiblefalse
    global.runOnceboolSet true to run only one iterationfalse
    global.debugboolSet true to enable debug loggingfalse
    global.subaccountslist(optional) Which subaccount IDs to load0
    enabledBotslistList of bots to enable (must match keys in botConfigs)-
    botConfigsobjectConfigs for associated bots
    botConfigs.<bot_type>objectConfig for a specific <bot_type>-
    yarn run dev --config-file=example.config.yaml
  6. Understand the FloatingPerpMakerBot

    master

    The FloatingPerpMakerBot is a market-making bot designed to place limit orders on the DLOB (Dynamic Limit Order Book). It automatically shifts orders based on the oracle price using oraclePriceOffset.

    Key behaviors:

    • Two-sided Market: It attempts to maintain both long and short limit orders.
    • Risk Management: It monitors account positions. As positions approach MAX_POSITION_EXPOSURE (default 10%), the bot skews orders to favor risk-reducing trades (placing them closer to the oracle price) and pushes risk-increasing trades further away.
    • Automatic Updates: It uses a cooldown mechanism (MARKET_UPDATE_COOLDOWN_SLOTS) to prevent excessive updates to the same market.
    • Order Management: If the bot is not quoting exactly two sides of the market (or if the market index is 0), it cancels existing orders and restarts the quoting process.
    // The bot is initialized with a DriftClient, SlotSubscriber, RuntimeSpec, and BaseBotConfig
    const bot = new FloatingPerpMakerBot(clearingHouse, slotSubscriber, runtimeSpec, config);
  7. Liquidator Bot: Error Handling and Throttling

    master

    The bot implements several mechanisms to handle errors and prevent spamming failed transactions:

    1. Simulation Errors: Before sending a transaction, the bot uses buildVersionedTransactionWithSimulatedCus. If simError is present, the error is logged and potentially sent via webhook.
    2. Error Suppression: Certain error codes can be passed to errorCodesToSuppress to prevent noisy logs and webhooks for expected/transient errors.
    3. User Throttling: If a liquidation attempt fails due to a simulation error (and the error is not suppressed), the user's public key is added to throttledUsers with a timestamp. Subsequent attempts for that user are skipped until LIQUIDATE_THROTTLE_BACKOFF has passed.
    4. Bankruptcy Handling: If a user is identified as bankrupt via isUserBankrupt(user), the bot attempts to resolve the bankruptcy via tryResolveBankruptUser before proceeding with liquidations.
  8. Understand UncrossArbBot throttling and maintenance margin logic

    master

    The UncrossArbBot includes safety mechanisms to prevent losing funds or spamming failed transactions:

    1. Throttling Nodes: If a specific maker (bid or ask) repeatedly results in NoArbError (e.g., isErrArb, isErrArbNoAsk, or isErrArbNoBid), the bot will throttle that specific PublicKey_OrderId pair for a THROTTLED_NODE_COOLDOWN (10,000ms).
    2. Maintenance Margin Breach: If transaction logs indicate a maker has breached their maintenance margin (isMakerBreachedMaintenanceMarginLog), the bot attempts to forceCancelOrders for that user to protect the arbitrage attempt.
    3. PnL Settling: The bot periodically runs settlePnls to realize positive PnL. This task is subject to a SETTLE_POSITIVE_PNL_COOLDOWN_MS (60,000ms) to prevent excessive transaction frequency.
  9. LiquidatorBot Overview and Mechanics

    master

    The LiquidatorBot is a specialized bot designed for the Drift V2 Protocol. It functions by taking over a portion of an endangered account's position. Because this process involves taking over positions, the bot requires collateral to operate.

    Key Mechanics:

    • Position Takeover Limit: The bot is constrained by maxPositionTakeoverPctOfCollateral, which defines the maximum percentage of its own free collateral it is willing to spend on any single endangered account.
    • State Management: The bot operates in three states: IDLE, LIQUIDATING, and DERISKING.
    • Derisking: Before attempting liquidations, the bot can perform a derisk operation to close out open positions on its own accounts to ensure safety.
    • Market Support: It supports both Perp (Perpetual) and Spot markets, using specific subaccount configurations to determine which markets to watch and which subaccounts to use for liquidation.
    /**
     * LiquidatorBot implements a simple liquidation bot for the Drift V2 Protocol. 
     * Liquidations work by taking over a portion of the endangered account's position, 
     * so collateral is required in order to run this bot.
     */