DEV Community

dead1786
dead1786

Posted on

Grid Trading Bot: Earn While the Market Goes Sideways

How to profit from cryptocurrency price oscillation with zero directional bias.


The Problem with Directional Trading

Most traders try to predict if prices go up or down. They're wrong about half the time.

Grid trading doesn't care about direction. It profits from movement itself — every oscillation within a price range triggers a buy-low-sell-high cycle automatically.

How Grid Trading Works

Imagine BTC is trading between $80,000 and $90,000. You set up a grid:

$90,000  ──── sell ────
$89,000  ──── sell ────
$88,000  ──── sell ────
$87,000  ──── sell ────  ← price here
$86,000  ──── buy  ────
$85,000  ──── buy  ────
$84,000  ──── buy  ────
$83,000  ──── buy  ────
$80,000  ──── buy  ────
Enter fullscreen mode Exit fullscreen mode
  • Below current price: limit buy orders
  • Above current price: limit sell orders
  • When a buy fills: immediately place a sell one grid above
  • When a sell fills: immediately place a buy one grid below

Every completed buy→sell cycle earns one grid's worth of profit. The more the price bounces, the more you earn.

The Math

With $200 invested in a 15-grid BTC setup ($80K-$92K range):

Grid spacing:  $800 per grid
Per-grid profit: $800 / $86,000 = 0.93%
After fees:     0.93% - 0.18% = 0.75% net per cycle
Dollar profit:  $13.3 × 0.75% = $0.10 per cycle

In a ranging market (3-5 grids trigger daily):
Daily:  $0.30 - $0.50
Monthly: $9 - $15 (4.5% - 7.5% monthly return)
Enter fullscreen mode Exit fullscreen mode

Compare this to a savings account at 2% per year.

Setting Up on OKX

OKX has a built-in grid trading bot. You can also use their API:

import hmac
import hashlib
import base64
import json
import time
import urllib.request

API_KEY = "your_key"
SECRET = "your_secret"
PASSPHRASE = "your_passphrase"
BASE_URL = "https://www.okx.com"


def sign_request(timestamp, method, path, body=""):
    message = timestamp + method + path + body
    signature = hmac.new(
        SECRET.encode(), message.encode(), hashlib.sha256
    )
    return base64.b64encode(signature.digest()).decode()


def create_grid_bot(symbol, lower, upper, grid_count, investment):
    """Create a spot grid trading bot on OKX."""
    path = "/api/v5/tradingBot/grid/order-algo"
    body = json.dumps({
        "instId": symbol,          # e.g., "BTC-USDT"
        "algoOrdType": "grid",     # spot grid
        "maxPx": str(upper),       # upper price bound
        "minPx": str(lower),       # lower price bound
        "gridNum": str(grid_count),
        "quoteSz": str(investment), # USDT to invest
        "runType": "1",            # 1 = auto
    })

    timestamp = datetime.utcnow().isoformat(timespec="milliseconds") + "Z"
    signature = sign_request(timestamp, "POST", path, body)

    headers = {
        "OK-ACCESS-KEY": API_KEY,
        "OK-ACCESS-SIGN": signature,
        "OK-ACCESS-TIMESTAMP": timestamp,
        "OK-ACCESS-PASSPHRASE": PASSPHRASE,
        "Content-Type": "application/json",
    }

    req = urllib.request.Request(BASE_URL + path, data=body.encode(), headers=headers)
    resp = urllib.request.urlopen(req, timeout=10)
    return json.loads(resp.read())
Enter fullscreen mode Exit fullscreen mode

Optimal Parameters

The key parameters and how to choose them:

1. Price Range (Upper/Lower Bound)

  • Look at the 30-day high and low
  • Add 5-10% padding on each side
  • Too narrow = price breaks out, grid stops working
  • Too wide = each grid earns too little

2. Grid Count

  • More grids = more frequent trades, smaller profit per trade
  • Fewer grids = less frequent, larger profit per trade
  • Rule of thumb: each grid's profit should be at least 3x the trading fee
  • For OKX (0.1% taker fee): minimum grid spread > 0.6%

3. Investment Amount

  • Minimum ~$10 on OKX
  • $100-300 is a practical starting point
  • Capital is split equally across all grids

Quick Formula

def calculate_grid(capital, current_price, volatility_30d):
    """Calculate optimal grid parameters."""
    # Range: 1.5x of 30-day volatility
    range_size = current_price * volatility_30d * 1.5
    upper = current_price + range_size / 2
    lower = current_price - range_size / 2

    # Grid count: ensure profit > 3x fees
    fee_rate = 0.001  # 0.1%
    min_spread = fee_rate * 2 * 3  # 0.6%
    max_grids = int(range_size / (current_price * min_spread))
    grid_count = min(max_grids, int(capital / 5))  # min $5 per grid

    return {
        "upper": round(upper),
        "lower": round(lower),
        "grids": grid_count,
        "per_grid": round(capital / grid_count, 2),
    }

# Example: $200, BTC at $84K, 12% monthly volatility
print(calculate_grid(200, 84000, 0.12))
# {'upper': 89040, 'lower': 78960, 'grids': 16, 'per_grid': 12.5}
Enter fullscreen mode Exit fullscreen mode

Risks

Grid trading is not risk-free:

  1. Price breaks below lower bound → you're holding assets at a loss (same as buying the dip)
  2. Price breaks above upper bound → you sold everything and miss the pump
  3. Prolonged downtrend → grid keeps buying as price falls, accumulating losses
  4. Low volatility → no trades trigger, capital sits idle

Risk Management

  • Set a stop-loss at 3-5% below the lower bound
  • Don't use more than 20% of your portfolio
  • Choose established coins (BTC, ETH) over volatile altcoins
  • Monitor and adjust the range monthly

Grid Trading vs Funding Rate Arbitrage

Grid Trading Funding Rate Arb
Risk Medium (directional exposure) Low (delta-neutral)
Return 3-8% monthly (ranging market) 1-2% monthly (stable)
Best when Market oscillates Market is bullish (positive funding)
Capital needed $100+ $1,000+ for meaningful returns

They complement each other perfectly. Run both: grid for active income during ranging markets, funding arb for passive income during trends.

Getting Started

  1. Open an OKX account and deposit USDT
  2. Start small — $100 is enough to test
  3. Pick BTC-USDT — most liquid, most predictable range
  4. Set conservative parameters — use the formula above
  5. Monitor weekly — adjust range if market shifts significantly

The grid runs 24/7. You check it once a week. That's it.


Follow live grid + arbitrage performance: Telegram - @PERMAFROSTK

Built with Permafrost AI — an open-source AI brain framework.

Top comments (0)