Grid Search System for Strategy Parameter Optimization

We design and develop full-cycle blockchain solutions: from smart contract architecture to launching DeFi protocols, NFT marketplaces and crypto exchanges. Security audits, tokenomics, integration with existing infrastructure.
Showing 1 of 1All 1305 services
Grid Search System for Strategy Parameter Optimization
Medium
~3-5 days
Frequently Asked Questions

Blockchain Development Services

Blockchain Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1358
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1251
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    957
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_logo-advance_0.webp
    B2B Advance company logo design
    646
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929

Grid Search System for Strategy Parameter Optimization

You have developed a strategy based on moving averages. Periods 5/15 give one return, 7/21 another. Which to choose? Manual brute force — 50 combinations, each backtest a minute — over an hour. What if you have five parameters? 10^5 combinations — a year of work. We solve this with grid search in 10 minutes, guaranteeing the global optimum within the parameter space and saving up to 80% time.

How Grid Search Solves Parameter Selection

The system exhaustively searches all combinations of parameters within your specified ranges. For each combination, it runs a backtest and ranks results by your chosen metric — for example, Sharpe ratio or annual return. You get not just the best parameters, but a full table of all combinations for deeper analysis. This helps assess stability and avoid overfitting.

Basic Implementation and Example

import itertools
from multiprocessing import Pool
import pandas as pd
from typing import Callable, Any

def grid_search(
    backtest_fn: Callable[[dict], dict],
    param_grid: dict[str, list],
    n_jobs: int = -1,
    metric: str = 'sharpe_ratio',
) -> pd.DataFrame:
    param_names = list(param_grid.keys())
    param_values = list(param_grid.values())
    all_combinations = list(itertools.product(*param_values))
    print(f"Total combinations: {len(all_combinations)}")
    print(f"Estimated time: ~{len(all_combinations) * 0.5:.0f} seconds")

    def run_single(params_tuple) -> dict:
        params = dict(zip(param_names, params_tuple))
        try:
            metrics = backtest_fn(params)
            return {**params, **metrics}
        except Exception as e:
            return {**params, 'error': str(e), metric: float('-inf')}

    if n_jobs == 1:
        results = [run_single(combo) for combo in all_combinations]
    else:
        with Pool(processes=n_jobs if n_jobs > 0 else None) as pool:
            results = pool.map(run_single, all_combinations)

    df = pd.DataFrame(results)
    df = df[df.get('error').isna()] if 'error' in df.columns else df
    return df.sort_values(metric, ascending=False)
import pandas as pd
from functools import partial

ohlcv = load_historical_data('BTC/USDT', '2023-01-01', '2024-01-01')

def backtest_ema_crossover(params: dict) -> dict:
    backtester = Backtester(commission=0.001, slippage=0.0005)
    result = backtester.run(
        strategy_class=EMACrossoverStrategy,
        params=params,
        data=ohlcv,
        initial_cash=100_000,
    )
    return {
        'sharpe_ratio': result.metrics.sharpe_ratio,
        'annual_return': result.metrics.annual_return_pct,
        'max_drawdown': result.metrics.max_drawdown_pct,
        'win_rate': result.metrics.win_rate,
        'total_trades': result.metrics.total_trades,
    }

param_grid = {
    'fast_period': [5, 7, 9, 12],
    'slow_period': [15, 21, 30, 50],
    'rsi_threshold': [25, 30, 35, 40],
    'stop_loss_pct': [0.02, 0.03, 0.05],
}
results = grid_search(backtest_ema_crossover, param_grid, n_jobs=8, metric='sharpe_ratio')
print(results.head(10)[['fast_period', 'slow_period', 'rsi_threshold', 'stop_loss_pct', 'sharpe_ratio', 'annual_return']])

Analyzing Results and Visualization

Grid search results can be analyzed with heatmaps. Below is a function for visualizing the dependency of a metric on two parameters.

import matplotlib.pyplot as plt
import seaborn as sns

def plot_parameter_heatmap(results: pd.DataFrame, param1: str, param2: str, metric: str):
    pivot = results.pivot_table(
        values=metric,
        index=param1,
        columns=param2,
        aggfunc='max',
    )
    plt.figure(figsize=(10, 8))
    sns.heatmap(pivot, annot=True, fmt='.2f', cmap='RdYlGn', center=0)
    plt.title(f'{metric} by {param1} and {param2}')
    plt.tight_layout()
    plt.savefig(f'heatmap_{param1}_{param2}.png', dpi=150)

Heatmaps help quickly identify zones of optimal values. If high Sharpe ratio appears only in a narrow region, it signals possible overfitting. We recommend examining the top 5 combinations and checking their stability on an out-of-sample set.

What's Included in the Grid Search Development

Stage Result
Strategy Analysis Define parameters, ranges, and target metric. Identify hyperparameters requiring tuning.
Architecture Design Design the system considering your backtester and tech stack (Python, NumPy, Foundry, etc.).
Implementation Write code with parallel computing, logging, visualization. Integrate standard overfitting protections.
Testing Validate on historical data, compare to baseline, run stress tests.
Documentation & Training Deliver source code, setup instructions, a 2-hour team session. Provide 2 weeks of support.

Protecting Against Overfitting

Overfitting is the main danger when optimizing parameters. We apply several techniques:

  • Data splitting: 70% train for optimization, 15% validation to check top 5 combos, 15% test for final confirmation.
  • Minimum trade count: Discard combinations with fewer than 30 trades — statistical insignificance.
  • Stability check: Ensure that small parameter changes (e.g., fast_period from 9 to 10) do not cause sharp metric drops.
def split_data_temporal(data: pd.DataFrame, train_pct=0.7, val_pct=0.15):
    n = len(data)
    train_end = int(n * train_pct)
    val_end = int(n * (train_pct + val_pct))
    return data[:train_end], data[train_end:val_end], data[val_end:]

train, validation, test = split_data_temporal(ohlcv)
results = grid_search(lambda p: backtest_fn(p, train), param_grid)

# Top 5 parameters tested on validation
top_params = results.head(5)
for _, row in top_params.iterrows():
    val_result = backtest_fn(row.to_dict(), validation)
    print(f"Params: {row.to_dict()}, Val Sharpe: {val_result['sharpe_ratio']:.2f}")

# Final test on test set — one time, with chosen parameters

We also include cross-validation for stability: split history into several periods and verify that optimal parameters work across different market conditions. This reduces the risk of unexpected performance drops in live trading.

Why Grid Search Over Other Methods?

Method Global Optimum Guarantee Speed with 3–4 params Speed with 5+ params Implementation Simplicity
Grid search Yes (within grid) High Low High
Bayesian optimization No Medium High Medium
Genetic algorithm No Medium High Low

Grid search is simpler and more reliable than Bayesian optimization when the number of parameters is up to 4. For strategies with 2–4 parameters, it's the optimal choice. For 5+ parameters, we recommend switching to Bayesian optimization. As Wikipedia states, grid search is an exhaustive method guaranteeing the best combination within the defined grid.

Process, Timeline, and Pricing

  1. Analytics — we study your strategy, define parameters, ranges, and optimization metric. Identify hyperparameters that need tuning.
  2. Design — develop the grid search architecture, optimized for your backtester and stack (Python, Foundry, etc.).
  3. Implementation — write code with parallel computing, logging, and visualization.
  4. Testing — validate on historical data, compare with baseline, apply overfitting protection.
  5. Deployment — deliver the system, documentation, and team training (1–2 hours).

Timeline: 3 to 10 days depending on strategy complexity and number of parameters. Pricing: calculated individually — exact cost determined after analyzing your task.

Order a custom grid search system — we'll implement it tailored to your strategy. Get a consultation: contact us to evaluate your task.

Why exchange development requires deep domain expertise

We develop exchanges — not 'chart sites,' but matching engines that process thousands of orders per second without delay, route liquidity between pools, and guarantee that no user gains access to others' funds. Teams that start with the UI and postpone the engine 'for later' end up rewriting everything in six months in 90% of cases.

Order Book vs AMM: where most projects break

Centralized exchanges (CEX) are built around an order book + matching engine. Decentralized exchanges (DEX) either also use an order book (dYdX on StarkEx, Serum/OpenBook on Solana) or an AMM with concentrated liquidity (Uniswap v3/v4, Curve, Balancer). A classic mistake when developing a CEX is implementing the matching engine on top of a relational database with transactions for each match. PostgreSQL handles ~500 RPS without special effort, but at peak loads of 5,000–10,000 orders per second, it turns into a deadlock nightmare. The correct architecture: in-memory order book (Redis Sorted Sets or custom C++/Rust structure), asynchronous writing of matches to PostgreSQL via a queue (Kafka/RabbitMQ), and a separate settlement service that finally updates balances.

For DEX, the most painful problem is sandwich attacks and MEV. A pool with a plain xy=k AMM without slippage protection becomes a target for MEV bots within hours of launch. Uniswap v2 lost hundreds of millions of dollars in user liquidity. Solutions: integration with Flashbots Protect, a commit-reveal scheme for orders, or switching to TWAMM (Time-Weighted AMM) for large trades.

Concentrated liquidity and impermanent loss

Uniswap v3 introduced concentrated liquidity – LPs choose a price range in which to provide liquidity. Capital efficiency increased 4,000x compared to v2 for stable pairs. But implementing this mechanism correctly is non-trivial. The Uniswap v3 liquidity contract uses tick-based accounting: the price space is divided into discrete ticks (tick = log₁.0001(price)), each tick stores accumulated fee growth and liquidity delta. When creating a position, the lower and upper ticks are computed, and the contract recalculates all active positions at each swap. Storage layout is critical here – incorrect variable packing in slots easily adds 40–60% to swap gas cost.

We implemented a Uniswap v3 fork for a client on Polygon with a custom fee tier system. The initial version consumed 180k gas for a swap across 2 ticks. After slot packing of variables in Tick.Info and inlining several internal calls, it dropped to 112k gas. This reduced gas costs by 38% and saved the client substantial costs on fees monthly. The techniques applied are described in the Uniswap v3 Whitepaper and confirmed by our audit experience.

How a matching engine delivers performance

A production-ready matching engine is built according to the following scheme:

  • Order ingestion layer – WebSocket gateway (Go or Rust), accepts orders, validates signature, checks balance via Redis, queues them. Latency at this level must be <1ms.
  • Matching core – single-threaded event loop (eliminates race conditions without mutexes). In memory, we hold two Sorted Sets for each trading instrument: bids and asks. FIFO matching for limit orders, immediate-or-cancel for market orders. Throughput with a proper Rust implementation – 500k–1M matches per second on a single core.
  • Settlement service – reads matches from Kafka, atomically updates balances in PostgreSQL (UPDATE accounts SET balance = balance - $1 WHERE id = $2 AND balance >= $1). Optimistic locking via row versioning.
  • Withdrawal pipeline – separate service with cold/hot wallet architecture. The hot wallet holds 5–10% of total deposits, the rest is cold storage with multi-sig (Gnosis Safe or custom HSM). Automatic withdrawals only from hot wallet, large amounts require manual authorization.
Component Technology Latency / Throughput
Order gateway Go + WebSocket <1ms p99
Matching engine Rust (in-memory) 500k+ orders/sec
Balance store Redis (write-through) <0.5ms
Settlement DB PostgreSQL 14+ ~50k TPS with partitioning
Event streaming Apache Kafka 1M+ events/sec
Blockchain node Geth / Solana validator depends on chain

How our exchange development process ensures reliability

Smart contracts and gas optimization

For EVM-based DEX (Ethereum, Arbitrum, Optimism, Polygon), the entire critical path lives in Solidity. Main contracts: Pool, Factory, Router, PositionManager (for v3-like), and Quoter for off-chain calculations. Typical mistakes we see in audits:

Reentrancy via callback. Uniswap v3 uses flash swap with a callback (uniswapV3SwapCallback). If your router lacks a nonReentrant guard and you don't check msg.sender == pool, the contract gets drained via a nested call. This is not hypothetical – several v3 forks lost funds this way.

Oracle manipulation in AMM. If your contract uses the spot price from the pool for collateral calculation, it is front-runnable. Correct: TWAP over 30+ minutes (Uniswap v3 OracleLib) or an external oracle (Chainlink).

Unbounded loops in liquidity range. If a swap crosses many ticks in a row (price impact 80%+), gas may exceed the block limit. Need MAX_TICKS_CROSSED with partial fill and returning the remainder.

For Solana DEX (Anchor framework, Rust), the architecture is fundamentally different: account-based model, Program Derived Addresses (PDA) instead of storage, Cross-Program Invocations instead of internal calls. Solana's throughput (~3,000–4,000 TPS vs 15–30 on Ethereum mainnet) allows building on-chain order books – exactly what Phoenix DEX does.

Liquidity bootstrapping and aggregator integration

Launching a pool is not enough – you need to ensure liquidity at launch. Practical mechanisms:

  • Liquidity Bootstrapping Pool (LBP) – initial price is high, asset weights dynamically shift, creating selling pressure and even token distribution. Implemented in Balancer v2.
  • Initial Liquidity Offering via Uniswap v3 – adding liquidity in a narrow range around the initial price, then gradually expanding as volume grows. Requires active liquidity management or integration with Arrakis/Gamma.
  • Integration with 1inch, Paraswap, Li.Fi – aggregators bring traffic but require standard compliance: the pool must have correct getAmountsOut, support ERC-20 approval/permit, and not have custom transfer hooks that break the aggregator's routing.

Development process and deliverables

Analytics and design begin with choosing the architectural model: CEX with custodial storage, non-custodial DEX, or hybrid (off-chain order book + on-chain settlement, like dYdX v3). This decision determines everything – regulatory load, tech stack, team.

Development proceeds in layers: first smart contracts with full Foundry coverage (fuzzing, invariant testing), then backend services, then integration layer, and finally frontend. Testing includes fork testing on mainnet via Foundry – we reproduce real liquidity conditions, not synthetic ones.

Audit is mandatory before mainnet deployment. For DEX contracts, minimally one firm with manual review (Trail of Bits, Spearbit, Code4rena contest). For CEX custody, audit of key storage processes. We guarantee all contracts undergo formal verification and fuzzing testing (Echidna, Foundry invariant).

Estimated timelines

Exchange type Timeframe
DEX (AMM, xy=k) 3 to 5 months
DEX with concentrated liquidity (v3-like) 6 to 10 months
CEX (matching engine + custody + trading UI) 8 to 14 months
Integration with existing protocol 4 to 8 weeks

Cost is calculated individually after a technical briefing: chain selection, throughput requirements, custodial model. Our certified engineers with 10+ years of experience will help you choose the optimal architecture and avoid common pitfalls. Contact our team for a detailed proposal.

Pitfalls to avoid at launch

  • Forgetting the price oracle in AMM. Spot price can be manipulated with a flash loan in one transaction. If your lending protocol uses the spot price from its own pool, that's a bug.
  • Hot wallet without limits. A CEX without daily limits on automatic withdrawals is an invitation for attackers. Compromising one key should lose at most 10% of total funds.
  • Absence of circuit breaker. A 40% price drop in 5 minutes should halt automatic liquidations or withdrawals until manual review. Without this, a cascading liquidation spiral destroys all TVL.
  • Incorrect decimal handling. USDC uses 6 decimals, WBTC – 8, most tokens – 18. Mixing without normalization leads to either precision loss or overflow. Solidity has no float; we work with fixed-point using FullMath (mulDiv with overflow protection).

Want to avoid these problems? Get a consultation — we will select the architecture for your project and provide exact timelines. Order exchange development with quality guarantee and ongoing support.