Sitemap

Grid Search for Optimizing Liquidity in Raydium: A Deep Dive

6 min readApr 17, 2025

--

TLDR

What is Grid Search?

Imagine you’re trying to find the perfect recipe for a smoothie. You test different amounts of fruit, yogurt, and juice until you get the tastiest mix. Grid search works like that, but for financial strategies. In Raydium, it’s likely used to test different settings for placing limit orders on OpenBook, like how much to trade at each price level, to make trading smooth and profitable.

How Does Raydium Use It?

Raydium places buy and sell orders at specific prices (using Fibonacci ratios) to provide liquidity. Grid search probably helps find the best combination of order sizes and price points to ensure there’s enough liquidity for both small and big trades without wasting resources. It tests many options and picks the one that works best.

Why It Matters

By optimizing these settings, Raydium keeps trading costs low and ensures big trades don’t mess up prices. It’s like setting up a lemonade stand with just the right amount of stock to serve everyone without running out or overstocking.

Going In Depth

Grid search is a systematic optimization technique used to find the best combination of parameters for a model or strategy by testing all possible combinations within predefined ranges.

In the context of Raydium, a leading decentralized finance (DeFi) protocol on Solana, grid search is likely employed to optimize liquidity provision, particularly in its Fibonacci-based liquidity distribution strategy. This approach involves placing limit orders at Fibonacci-derived price levels on OpenBook (formerly Serum) to balance tight spreads for small trades and deep liquidity for larger ones. This analysis explores the grid search algorithm, its formulas, its use in traditional finance, and how it’s applied in Raydium, with Mermaid.js diagrams for clarity.

Background and Importance

Raydium’s hybrid model combines Automated Market Maker (AMM) pools with OpenBook’s central limit order book (CLOB), enabling efficient trading and liquidity provision.

The Fibonacci liquidity distribution strategy, detailed in the Raydium AMM GitHub, places limit orders at price levels derived from Fibonacci ratios (e.g., 23.6%, 38.2%) to optimize liquidity depth. Grid search, as a parameter optimization method, likely fine-tunes parameters like order sizes, price level spacing, or the number of Fibonacci levels to maximize trading efficiency and liquidity coverage. Understanding grid search is crucial for developers and researchers aiming to enhance DeFi protocols like Raydium.

Placement of Fibonacci Liquidity

Refer to my previous deep dive on Rayium to understand in depth the mechanism of Raydium.

Grid Search in Traditional Finance

While grid search is not a standard term in traditional finance, the concept of systematically testing parameter combinations is widely used in optimization problems, including:

  • Portfolio Optimization: Testing different asset allocations to maximize the Sharpe ratio or minimize risk.
  • Liquidity Management: Adjusting cash reserve ratios or investment thresholds to balance liquidity and returns.
  • Trading Strategies: Optimizing parameters like stop-loss levels or moving average periods in algorithmic trading.

For example, a hedge fund might test various portfolio weights to find the combination that maximizes returns while maintaining sufficient liquidity for redemptions. Grid search, as described in Algotradinglib Grid Search, is particularly common in algorithmic trading for hyperparameter tuning, such as optimizing the parameters of a trading strategy to improve metrics like the Sharpe ratio or Sortino ratio.

The grid search process typically follows these steps:

  1. Define the parameter grid: Determine the range and increments for each parameter that you want to optimise in the trading strategy. For example, if you have a moving average crossover strategy, you may want to optimise the lengths of the moving averages.
  2. Generate parameter combinations: Create all possible combinations of parameter values from the defined parameter grid. This results in a set of parameter configurations that need to be tested.
  3. Backtest and evaluate: Apply each parameter configuration to historical market data and conduct backtesting to evaluate the performance of the trading strategy for each combination. Performance metrics such as profitability, risk-adjusted returns, drawdowns, and other relevant measures are typically considered.
  4. Select the best parameter configuration: Analyse the results of the backtests and identify the parameter configuration that yields the best performance based on your chosen evaluation criteria. This could involve comparing metrics such as total returns, maximum drawdown, or risk-adjusted measures like the Sharpe ratio.

Grid Search Algorithm and Formulas

Grid search involves exhaustively evaluating all combinations of parameters within specified ranges to find the optimal set based on a performance metric. Below is a detailed breakdown of the algorithm and its mathematical foundation.

Algorithm Steps

Grid Search Algo
  1. Identify Parameters:
  • Select parameters to optimize, e.g., order size, number of Fibonacci levels, or price level spacing.

Example: In Raydium, parameters might include:

  • ( S ): Order size (e.g., 10 SOL, 20 SOL, 30 SOL).
  • ( N ): Number of Fibonacci levels (e.g., 2, 3, 4).
  • ( D ): Price deviation multiplier (e.g., 1x, 1.5x, 2x for Fibonacci ratios).

2. Define Ranges:

  • Specify possible values for each parameter.

Example:

  • ( S ): [10, 20, 30] SOL
  • ( N ): [2, 3, 4].
  • ( D ): [1, 1.5, 2]

3. Create the Grid:

  • Generate all possible combinations of parameter values.
  • Total combinations = ( |S| \times |N| \times |D| = 3 \times 3 \times 3 = 27 ).
  • Example combination: ((S=10, N=2, D=1)).

4. Evaluate Each Combination:

  • For each combination, simulate the strategy’s performance using historical or simulated market data.
  • Compute a performance metric, such as:
  • Liquidity Depth: Total value of orders available at various price levels.
  • Spread Cost: Average bid-ask spread for trades.
  • Slippage Impact: Price impact of large trades.
Evaluating the liquidity depth

5. Select the Best Combination:

  • Choose the combination that maximizes the performance metric or meets a threshold (e.g., minimum liquidity depth with lowest spread cost).

Mathematical Foundation

For each combination, the algorithm would:

  1. Simulate placing orders at the specified Fibonacci levels (e.g., 23.6%, 38.2%, etc.)
  2. Calculate key metrics like liquidity depth and spread cost
  3. Select the combination with the highest liquidity depth while maintaining an acceptable spread cost

The optimal parameter combination balances the tradeoff between market coverage (using more levels and larger sizes) and capital efficiency (minimizing unused liquidity).

Implementation in Smart Contract

  • math.rs: Computes Fibonacci ratios (e.g., 23.6%, 38.2%) and applies them to the current price.
  • processor.rs: Tests combinations of order sizes and levels, simulating their impact on liquidity and trading costs.
  • MonitorStep: Dynamically adjusts the order grid based on market conditions, potentially using grid search results to update parameters.

Why you should use grid searching

  1. Systematic exploration: Grid searching systematically explores parameter combinations to analyse their impact on trading strategy performance.
  2. Performance optimization: It helps identify optimal parameter configurations that maximise returns and align with trading goals.
  3. Efficiency and time-saving: Grid searching automates testing multiple parameter configurations, saving time and effort compared to manual adjustments.
  4. Robustness: It enhances the robustness of trading strategies by fine-tuning parameters and improving their effectiveness.

Limitations and Alternatives

  • Computational Cost: Grid search tests all combinations, which can be slow for many parameters (e.g., ( 10⁶ ) combinations for 6 parameters with 10 values each).
  • Curse of Dimensionality: As parameters increase, the grid grows exponentially.

Alternatives:

  • Random Search: Samples random combinations, often faster (MachineLearningMastery Random Search).
  • Bayesian Optimization: Uses probabilistic models to focus on promising combinations (Keylabs Bayesian Optimization).
  • Genetic Algorithms: Evolves parameter sets over generations (ScienceDirect Genetic Algorithms).

Conclusion

Grid search is a robust method for optimizing liquidity in Raydium by testing combinations of parameters like order sizes and Fibonacci levels to maximize liquidity depth and minimize trading costs. While computationally intensive, it ensures thorough exploration of the parameter space, making it ideal for fine-tuning DeFi strategies. Developers can explore Raydium’s implementation in the Raydium AMM GitHub and consider alternatives like Bayesian optimization for larger-scale problems.

Key Citations

--

--

Yong kang Chia
Yong kang Chia

Written by Yong kang Chia

Blockchain Developer. Chainlink Ex Spartan Group Articles moving to chiayong.com/articles

No responses yet