Building a grid trading bot is a useful exercise even if you never deploy one for serious money. The challenges, order management, state recovery, partial fills, exchange API quirks, are foundational for any algorithmic trading project. This article walks through implementing a working grid bot for LMEX in Python, from order placement to recovery logic.
A complete grid trading bot has five main components:
1. **Configuration**: grid parameters (range, spacing, capital per level)
2. **Order placement**: initial grid setup and order management
3. **Fill handler**: react to fills by placing opposite-side orders
4. **State persistence**: track open orders, filled levels, total inventory
5. **Recovery logic**: handle restarts and reconnections without losing state
The configuration is simple. The other four are where most bots fail.
A reasonable starting configuration for BTC-PERP:
This creates a 20-level grid from \$55k to \$65k with \$500 worth of BTC at each level. Spacing is \$526 per level.
Place buy orders below current price, sell orders above. Skip the level closest to current price (no point in placing a stop right where you are):
The `postOnly: True` flag is critical. It ensures the orders provide liquidity rather than take it, earning maker rebates and avoiding accidental crosses.
When an order fills, place the opposite-side order at the adjacent level:
This is the core of grid trading. Buy fills → sell orders one level up. Sell fills → buy orders one level down.
Without persistent state, a restart wipes out your knowledge of which orders are placed and at what levels. Use a simple SQLite database:
This gives you crash recovery, on restart, read open orders from the database and resume tracking them.
When the bot restarts after a crash or planned restart, reconcile local state with exchange reality:
This reconciliation step runs every time the bot starts. It's the difference between a bot that recovers cleanly from a 5-minute outage and a bot that needs manual intervention.
This skeleton is incomplete. A production bot also needs:
**WebSocket order updates.** Instead of polling REST for fills, subscribe to the order update stream. Lower latency, lower API rate usage.
**Inventory tracking.** Sum position across all filled buys minus all filled sells. Use this for risk management.
**Range monitoring.** When price moves outside the grid, the bot should pause and alert. Continuing to trade with price outside the grid produces poor results.
**Kill switch.** Triggered by drawdown threshold, volatility spike, or manual override. Cancels all orders immediately.
**Logging.** Every order placement, fill, and decision logged with timestamps. Without good logs, debugging is impossible.
These together add another 500-1000 lines of code beyond the skeleton above.
Run the bot in paper-trading mode for at least 2 weeks before any real money:
1. Implement using LMEX's testnet first
2. Verify orders place and cancel correctly
3. Manually simulate fills to test the fill handler
4. Test recovery by killing the bot mid-operation
5. Run in live conditions but at minimum order size for another week
6. Only then scale up to real position sizes
Most grid bot failures happen in week 1 of live operation. Survive that, you've validated most of the logic.
Q: What's the minimum capital to run a grid bot meaningfully?
Around \$5,000-10,000. Below that, transaction costs and minimum order sizes eat too much. Above \$50,000, grid bots can be very capital-efficient.
Q: Should I use REST or WebSocket for order placement?
REST is simpler. WebSocket is faster and uses less rate limit. For a 20-level grid, REST is fine. For 100+ level grids with frequent updates, switch to WebSocket.
Q: How do I handle the bot crashing?
Persistent state in SQLite (or similar), reconciliation logic on startup, alerts when the bot detects state inconsistency. Plan for crashes; they happen.
Q: Can I run multiple grids on different pairs simultaneously?
Yes, recommended. Different pairs trend differently, so a portfolio of grids smooths the combined return. Just be aware of correlation during stress events.