A grid strategy rests buy limits at fixed steps below the price and sells each lot back one step above, so it profits from back-and-forth movement and loses when price trends away. Dollar-cost averaging buys a fixed amount on a schedule regardless of price. Backtest a grid with real limit fills, a cap on how many lots it can accumulate and a period with a long fall; test DCA against a lump-sum purchase on the same history.
How a grid makes and loses money
- Each round trip earns one step, less the spread and fees, whenever price drops a level and comes back.
- A falling market fills buy after buy. The grid holds more lots, each at a higher price than the market, with an unrealised loss that grows with every level.
- A rising market leaves it flat. Once all lots are sold, the grid earns nothing while price trends up.
So a grid's backtest result depends mostly on whether the period ranged or trended. Test it on a stretch with a long fall, and look at the maximum number of lots held and the drawdown at that point, not only the profit.
What a grid backtest must get right
- Limit fills. A buy limit should fill only when price trades through it. A backtest that fills on a touch of the bar's low gives a grid fills it would not have had. See market or limit orders.
- Several fills in one bar. In a fast move, price can cross several levels inside one bar. Fills should follow the order price actually took through the bar.
- Fees per round trip. A tight grid makes many small trades, so its edge per trade is close to the cost per trade.
- A cap. Without a maximum number of lots, the grid's position in a crash is unbounded.
How DCA should be tested
Dollar-cost averaging is a buying schedule rather than a trading signal. The fair comparison is the same money invested at once on the first day: lump sum wins in rising markets, DCA in falling ones. Report both on the same history and the same costs.
How Reamer Research handles it
In Reamer Research, a sell limit whose quantity is smaller than the position closes that part and leaves the rest, so each grid lot can be sold on its own. Buy limits fill when the simulated ask trades through them, on a seeded tick path inside each bar. This configured object keeps one buy one step below and one sell one step above, and moves them when price changes level:
import math
import reamer_research as rr
class Grid:
def __init__(self, step=0.25, lot=10, max_lots=6):
self.step, self.lot, self.max_lots = step, lot, max_lots
self.lookback, self.placed = 2, None
def on_bar(self, d):
price, held = d.close[-1], d.position()
level = math.floor(price / self.step) * self.step # the grid line below
if (level, held) == self.placed and d.open_orders():
return None # orders still right
self.placed = (level, held)
orders = [rr.cancel_all()]
if held < self.max_lots * self.lot:
orders.append(rr.buy_limit(level, self.lot))
if held > 0:
orders.append(rr.sell_limit(level + 2 * self.step, min(self.lot, held)))
return rr.orders(*orders)
result = rr.backtest(Grid(step=0.25, lot=10), 'data/SPY_5min.bin',
spread=0.01, commission_per_unit=0.005)
print(result.closed_trades_count, 'round trips, net', round(result.net_pnl, 2),
'max drawdown', round(result.equity_drawdown_maximal, 2))
The buy rests on the grid line below the price and the sell on the line above the next one, so a lot bought on the way down is sold once price climbs back a step or more. closed_trades lists each partial close as its own trade. The visual trade diagnostics tool (open_viewer=True) shows the resting buy and sell levels around each trade.
DCA is a function strategy that buys on the first bar of each week, beside a buy-and-hold run for comparison:
from datetime import datetime, timezone
import reamer_research as rr
AMOUNT = 1000 # dollars a week
def week(ts):
return datetime.fromtimestamp(ts, timezone.utc).isocalendar()[:2]
def dca(d):
if d.close[0] == 0 or week(d.ts) == week(d[d.tickers[0]].ts[-2]):
return None # not the week's first bar
return rr.buy_market(round(AMOUNT / d.close[-1], 4))
def lump_sum(d):
if d.position() == 0:
return rr.buy_market(round(4 * AMOUNT / d.close[-1], 4))
for name, rule in [('DCA', dca), ('lump sum', lump_sum)]:
r = rr.backtest(rule, 'data/SPY_5min.bin', lookback=2, initial_capital=10_000,
spread=0.01, commission_per_unit=0.005)
print(name, round(r.net_pnl, 2))
Each run ends with its position still open, and net_pnl values it at the last price. Either rule could also be written as a class, or as an object configured with its step or amount.
Limits to know
- Spot holdings only. The grid and DCA here hold a position in one instrument; funding rates on perpetual futures, often used for crypto grids, would be added the way FX swap is.
- Evaluation Mode runs 30 days or 50,000 bars of one ticker. Enough to watch a grid fill and unwind on your own data; years of DCA need a licence.
A $20 month includes the full kit, so you can test your own grid steps and schedules and cancel if it does not fit.