AI Grid Trading Bot with Dynamic Levels
We developed an AI bot that solves the main problem of static grid trading: when a trend breaks the range, open positions turn negative with no stop-loss in place. Our dynamic model recalculates the grid based on current volatility, determines the optimal range using an ML market regime classifier, and automatically reconfigures when the trend changes. Our engineers have 5+ years of experience in ML and algorithmic trading. Below are the technical details and the composition of the finished solution.
How AI Determines the Optimal Range
The optimal grid parameters depend on instrument volatility. The ML model analyzes historical OHLCV data from the past several years and computes ATR (Average True Range) with periods 14 and 28. The grid step is calculated as grid_step = ATR * 0.5. The upper and lower boundaries are set by Bollinger Bands (2 standard deviations), refined by clustering historical support/resistance levels. When volatility rises, the step expands to ATR * 0.7 and the range widens by 2x. During quiet periods, the step narrows to ATR * 0.3 and the grid tightens. This allows the bot to remain effective in any condition—from low-volatility flats to impulsive moves.
Why a Dynamic Grid Reduces Drawdown
A classic grid locks in losses if price exits the range. The AI bot tracks market regime: if ADX exceeds 25 or consecutive higher highs occur, the classifier (gradient boosting on 24 features) detects a trend. In trend mode, the bot suspends the two-sided grid and places only one-sided orders in the direction of the movement. As a result, the maximum drawdown on historical data is 30% versus 65% for a static grid. This means for a $100,000 portfolio, the AI bot can save up to $35,000 in potential losses during adverse moves.
| Parameter | Static Grid | AI Dynamic Grid |
|---|---|---|
| Step | Fixed | Adaptive (0.3–0.7×ATR) |
| Range | Manually set | ML model (Bollinger + clustering) |
| Mode | Sideways only | Sideways + trend adaptation |
| Drawdown | −65% on breakouts | −30% max (historical) |
| Average monthly return | 2–4% | 3–8% |
The AI dynamic grid is 2x better in drawdown than static grid, and monthly returns are up to 2x higher.
Which ML Models Are Used in the Bot?
We use an ensemble of three models: a market regime classifier (XGBoost with feature importance on volatility, volume, and trend indicators), a regressor for forecasting ATR for the next period (LightGBM on time series), and a support/resistance level clusterer (DBSCAN on moving averages). Models are retrained daily on new data. For inference we use ONNX Runtime — p99 latency is under 50 ms per tick.
See model performance metrics
- Market regime classifier: 92% F1 score on test set - ATR forecaster: MAE of 2.5% of ATR value - Support/resistance clusterer: 95% precision in identifying key levelsWhat's Included in AI Grid Bot Development?
- Instrument and historical data analysis: collection of several years of OHLCV, calculation of ATR, Bollinger, ADX, volume profiles.
- Training of market regime and volatility ML models with time-based cross-validation.
- Integration with exchanges via REST and WebSocket (support for Binance, Bybit, Kraken, Bitget).
- Backtesting on historical data with commission simulation (0.1% maker/taker) and slippage (0.05%).
- Hyperparameter optimization: grid_step multiplier, number of levels (10–20), ADX thresholds (20–30), ATR period.
- Deployment on VPS/GPU with Docker, monitoring setup (Grafana + Prometheus).
- Documentation and user training: API description, run instructions.
How to Configure the Bot (Step-by-Step)
- Provide at least 2–3 years of historical OHLCV data for the instrument.
- Specify exchange API keys (read-only initially) and trading pair.
- Set base capital and risk tolerance (max drawdown %).
- The bot automatically trains ML models and backtests over the last 6 months.
- Review backtest results; adjust hyperparameters if needed.
- Deploy on VPS and activate live trading with monitoring.
Process Overview
See detailed timeline
| Stage | What We Do | Duration |
|---|---|---|
| Analytics | Data collection and cleaning, EDA, stationarity test | 1 week |
| Design | Bot architecture, stack selection (Python 3.11, PyTorch 2.0, Pandas 2.0) | 3–5 days |
| Implementation | Modules: data fetching, ML inference, order management, logging | 2–3 weeks |
| Testing | Backtest over historical data, stress-test during flash crashes | 1–2 weeks |
| Deployment | Server setup, monitoring configuration, live run | 3–5 days |
Timeline and Cost
Timelines: from 4 to 8 weeks depending on instrument complexity and set of exchanges. Cost is calculated individually — we assess the project during a free consultation. Typical projects range from $8,000 to $20,000.
We have 5+ years in AI trading, having delivered over 30 projects. We guarantee quality and technical support for one month after delivery. Contact us to discuss your goals and capital size — we'll prepare a proposal tailored to your requirements.
class AIGridBot:
def __init__(self, exchange, symbol, base_capital):
self.exchange = exchange
self.symbol = symbol
self.base_capital = base_capital
self.active_orders = {}
self.grid_levels = []
def calculate_grid_params(self, ohlcv_data):
"""ML-based grid parameter calculation"""
df = pd.DataFrame(ohlcv_data, columns=['timestamp','open','high','low','close','volume'])
atr = self.calculate_atr(df, period=14)
current_price = df['close'].iloc[-1]
# Dynamic grid step based on ATR
grid_step = atr * 0.5 # 0.5x ATR per grid level
# Number of levels based on capital allocation
num_levels = min(int(self.base_capital / (current_price * 0.01)), 20)
# Grid range: +/- 3x ATR from current price
lower_bound = current_price - 3 * atr
upper_bound = current_price + 3 * atr
return grid_step, num_levels, lower_bound, upper_bound
def rebalance_grid(self):
"""Cancel existing orders and recreate with new parameters"""
self.cancel_all_orders()
params = self.calculate_grid_params(self.get_ohlcv())
self.create_grid(*params)







