In Read Your Backtest Drawdown and the Equity Curve we read the result of the ICICIBANK trend, breakout and ADX strategy, which finished with a net profit of Rs 62,044.89 and a max drawdown of 24.83 percent. This part uses the same signals on a fresh run with openalgo 2.4.1, shows how the charges are built, and how position sizing changes the result.
In this series
1. Your First Backtest with the OpenAlgo Python SDK: EMA Crossover.
2. Build Smarter Backtest Signals with OpenAlgo Indicators.
3. Read Your Backtest Drawdown and the Equity Curve.
4. Add Realistic Costs and Position Sizing to Your OpenAlgo Backtest (this article).
5. Six-Stock Trend Portfolio Backtest with the OpenAlgo SDK.
Same strategy, same data
The rules do not change from Part 3. Long only, ICICIBANK daily bars from 1 January 2021 to 23 November 2026, Rs 1,00,000 starting capital, daily bars from your own OpenAlgo server (source="db"). The product is CNC (delivery), because this is a multi-day trend strategy, not an intraday one. Every figure below comes from a fresh run on openalgo 2.4.1, so run pip install -U openalgo if you want the same defaults.
import os
import openalgo.backtest as bt
from openalgo import api, ta
from openalgo.backtest import costs
client = api(api_key=os.getenv("OPENALGO_API_KEY", "your_api_key"),
host=os.getenv("OPENALGO_HOST", "http://127.0.0.1:5000"))
def trend_breakout(bars):
ema20 = ta.ema(bars["close"], 20)
ema50 = ta.ema(bars["close"], 50)
_, _, adx = ta.adx(bars["high"], bars["low"], bars["close"], period=14)
up20, _, _ = ta.donchian(bars["high"], bars["low"], period=20)
entries = (ema20 > ema50) & (bars["close"] > up20.shift(1)) & (adx > 20)
exits = ema20 < ema50
return entries, exits
The default all-in result on this run is a net of Rs 61,361.34, a max drawdown of 24.89 percent, nine closed trades and one still open. That is a little below the Part 3 figure, because the SDK default now also charges delivery brokerage. The run still uses the engine’s default position sizing, which puts almost the whole account into each trade.
Three cost models, stated up front
The backtest engine itemises six charges on every Indian fill: brokerage, STT, the exchange transaction charge (including the IPFT levy), the SEBI fee, stamp duty and GST. A depository participant (DP) fee is added on each delivery sell. Rates come from dated schedules, so a trade is charged at the rates in force on its trade date, not at today’s rates alone.
We compare three models. The signals, the dates, the capital and the position sizing stay the same (all-in), so the only thing that changes is the cost and slippage assumption.
- Zero costs.
costs=Noneandslippage=0. The engine warns that this overstates net profit. It is a baseline, not a claim about real trading. - SDK default costs. Omit
costsandslippageto use the built-in defaults: the dated statutory schedule, the standard brokerage preset (for delivery, 2.5 percent of traded value capped at Rs 20 per executed order), a DP fee of Rs 13 plus GST, and 2 bps of slippage on large and mid-cap equity, with a minimum of 1 tick. - Realistic costs. The same statutory schedule and the same DP fee, plus two more conservative choices, all stated before the run. Delivery brokerage is 0.03 percent of traded value, capped at Rs 20 per executed order. Slippage is 5 bps per fill, again with a minimum of 1 tick.
The current delivery rates in the schedule that starts on 1 April 2026 are: STT of 0.10 percent on the buy and 0.10 percent on the sell, an exchange transaction charge of 0.00297 percent plus an IPFT levy of 0.00010 percent, a SEBI fee of 0.00010 percent, stamp duty of 0.015 percent on buys only, and GST of 18 percent on brokerage, exchange charges and the SEBI fee. The engine flags that some early-2021 delivery rates, and the latest 2026 schedule, are not fully verified, so charges may be slightly off.
REALISTIC_COSTS = costs.CostModel(costs.custom(
delivery=("percent", 0.03, 20),
intraday=("percent", 0.03, 20),
futures=("percent", 0.03, 20),
options=20,
dp_fee=13,
name="discount_capped",
))
REALISTIC_SLIP = bt.slippage.bps(5)
def run(order_args=None, **backtest_args):
Strategy = bt.from_signals(trend_breakout, "ICICIBANK", "NSE", "D",
product="CNC", **(order_args or {}))
return bt.backtest(Strategy, client, start="2021-01-01", end="2026-11-23",
capital=100_000, source="db", **backtest_args)
zero = run(costs=None, slippage=0)
default = run()
realistic = run(costs=REALISTIC_COSTS, slippage=REALISTIC_SLIP)
print(zero.summary())
print(default.summary())
print(realistic.summary())
Zero : Net profit Rs 66,256.80, return 66.26%, max drawdown -24.53%, 9 trades
Default : Net profit Rs 61,361.34, return 61.36%, max drawdown -24.89%, 9 trades
Realistic: Net profit Rs 60,356.53, return 60.36%, max drawdown -24.99%, 9 trades
All three stay profitable. Default charges and 2 bps of slippage take Rs 4,895.46 off the zero-cost net. The realistic model, mainly through the higher 5 bps of slippage, takes another Rs 1,004.81. Max drawdown only inches from 24.53 percent to 24.99 percent, because this strategy’s worst fall is a price move, not a bill for charges.
The three equity curves keep the same shape. They fan out after the big 2024 run, when the account is larger and each fill carries more value. Net profit is gross profit minus the charges the account actually paid. Slippage is already inside the fill prices, so it shows up in gross profit rather than as a second subtraction.
| Component | Zero costs | SDK default | Realistic |
|---|---|---|---|
| Brokerage | 0.00 | 380.00 | 380.00 |
| STT | 0.00 | 2,343.97 | 2,332.67 |
| Exchange charges | 0.00 | 76.08 | 75.72 |
| SEBI fee | 0.00 | 2.29 | 2.28 |
| Stamp duty | 0.00 | 182.75 | 181.98 |
| GST | 0.00 | 82.41 | 82.34 |
| DP charge | 0.00 | 138.06 | 138.06 |
| Charges paid | 0.00 | 3,207.81 | 3,197.42 |
| Modelled slippage | 0.00 | 505.25 | 1,160.80 |
| Net profit | 66,256.80 | 61,361.34 | 60,356.53 |
STT is the large statutory line, as you would expect on delivery trades. The DP charge is Rs 15.34 (Rs 13 plus 18 percent GST) on each of the nine closed sells, which adds up to Rs 138.06 in both charged runs; the open trade has not sold yet, so it does not pay one. On this delivery run every executed order hit the Rs 20 brokerage cap under both charged models, 19 orders in all, which is why brokerage is a round Rs 380 in both columns. The realistic model is stricter on slippage, and that is where most of the extra drag appears. Charges paid is the account’s total after contract-note rounding to the paisa, so it can differ from the sum of the unrounded lines by a few rupees.
Three position sizing methods under realistic costs
The cost comparison above used the engine default, which is all-in: about one times equity, less estimated charges, with a 2 percent cash buffer so a gap to the next open is less likely to reject the order. Now we keep the realistic cost model fixed and change only the position sizing.
The three methods, stated before the runs:
- All-in. The engine default, as above.
- 50 percent of equity.
bt.size.percent(50)sizes at the decision close with no cash buffer. Half the account stays in cash. - Fixed risk of 1 percent of equity.
bt.size.fixed_risk(1)needs a stop distance, so each entry also carriesstop=bt.atr(2, period=14), a stop two times the 14-day ATR below the fill. That stop can exit a trade before the EMA-20/EMA-50 exit, so this run is allowed to differ in trade count as well as in size.
kw = dict(costs=REALISTIC_COSTS, slippage=REALISTIC_SLIP)
all_in = run(**kw)
pct50 = run({"size": bt.size.percent(50)}, **kw)
risk1 = run({"size": bt.size.fixed_risk(1), "stop": bt.atr(2, period=14)}, **kw)
print(all_in.summary())
print(pct50.summary())
print(risk1.summary())
All-in : Net profit Rs 60,356.53, return 60.36%, max drawdown -24.99%, 9 trades (56% won)
50% equity : Net profit Rs 28,784.03, return 28.78%, max drawdown -14.27%, 9 trades (56% won)
1% risk : Net profit Rs 5,188.81, return 5.19%, max drawdown -5.19%, 12 trades (33% won)
What position sizing does to profit and drawdown
All three remain profitable after realistic costs. The first lesson from this position sizing comparison is scale. Cutting the position to half of equity almost halves both the profit and the pain: net profit falls from Rs 60,356.53 to Rs 28,784.03, and max drawdown from 24.99 percent (Rs 33,353.35) to 14.27 percent (Rs 16,714.33). The Calmar ratio barely moves, 0.33 to 0.31, which is what you would expect when you scale the same nine trades.
Fixed-risk sizing is a different trade list, not a scaled copy. The 2-ATR stop closed 6 of the 12 completed trades, and the EMA exit closed the other 6. The first 2021 trade, which all-in rode for months, was stopped in a few weeks. The large 2023 to 2025 winner was split in two: a stopped-out loss in January 2024, then a later re-entry that still made money, but on only 21 shares instead of the 115 the all-in run held through the whole move. Position sizes ran from 17 to 36 shares, against 105 to 179 when all-in and 44 to 91 at 50 percent of equity. The result is a much quieter account, a net of Rs 5,188.81, a max drawdown of 5.19 percent, a win rate of 33 percent, and a Calmar ratio of 0.17.
Nine or twelve closed trades is a story, not a sample. The engine still refuses to judge overfitting, because its checks want 30 closed trades.
What to look at first, every time
- The cost model, written down before the run. Zero-cost equity is a useful baseline. It is not the result you would have lived with.
- Charges against slippage. On this delivery run, STT dominated the statutory bill. Raising slippage from 2 bps to 5 bps moved the fill prices by more than the extra brokerage did.
- Position sizing against drawdown, not only against net profit. Half-sized trades cut the worst fall almost in half and left the shape of the equity curve intact. Fixed-risk sizing cut the fall further, but only by changing the exits as well as the size.
- The trade count. A sizer that needs a stop is allowed to change how often you are in the market. Compare it with that in mind.
The full position sizing script
You can copy the complete script below, or download the zip. It needs a running OpenAlgo server, openalgo 2.4.1 to match these defaults, and daily bars already on that server. Set OPENALGO_API_KEY first, then run it. The figures in this article came from this exact script.
# Realistic costs and position sizing on an ICICIBANK trend backtest.
# OpenAlgo Python SDK. Figures in the article were run on openalgo 2.4.1.
# Rules fixed before the run: EMA 20 above EMA 50 (trend), close above the
# prior 20-day Donchian high (breakout), ADX(14) above 20 (strength).
# Exit: EMA 20 below EMA 50. Product is CNC (delivery).
# Set OPENALGO_API_KEY in your environment. Never paste the key into code you share.
# Optionally set OPENALGO_HOST (default http://127.0.0.1:5000).
import os
import openalgo.backtest as bt
from openalgo import api, ta
from openalgo.backtest import costs
client = api(
api_key=os.getenv("OPENALGO_API_KEY", "your_api_key"),
host=os.getenv("OPENALGO_HOST", "http://127.0.0.1:5000"),
)
SYMBOL, EXCHANGE = "ICICIBANK", "NSE"
START, END, CAPITAL = "2021-01-01", "2026-11-23", 100_000
def trend_breakout(bars):
ema20 = ta.ema(bars["close"], 20)
ema50 = ta.ema(bars["close"], 50)
_, _, adx = ta.adx(bars["high"], bars["low"], bars["close"], period=14)
up20, _, _ = ta.donchian(bars["high"], bars["low"], period=20)
entries = (ema20 > ema50) & (bars["close"] > up20.shift(1)) & (adx > 20)
exits = ema20 < ema50
return entries, exits
REALISTIC_COSTS = costs.CostModel(costs.custom(
delivery=("percent", 0.03, 20),
intraday=("percent", 0.03, 20),
futures=("percent", 0.03, 20),
options=20,
dp_fee=13,
name="discount_capped",
))
REALISTIC_SLIP = bt.slippage.bps(5)
def run(order_args=None, **backtest_args):
Strategy = bt.from_signals(
trend_breakout, SYMBOL, EXCHANGE, "D",
product="CNC", **(order_args or {}),
)
return bt.backtest(
Strategy, client, start=START, end=END,
capital=CAPITAL, source="db", **backtest_args,
)
def cost_totals(result):
frame = result.costs
names = ("brokerage", "stt", "exchange_txn", "sebi_fee",
"stamp_duty", "gst", "dp_charge", "charged")
if frame is None or len(frame) == 0:
return {name: 0.0 for name in names}
out = {}
for name in names:
out[name] = float(frame[name].sum()) if name in frame.columns else 0.0
return out
def slippage_total(result):
trades = result.trades
if "slippage_rupees" not in trades.columns:
return 0.0
return float(trades["slippage_rupees"].fillna(0).sum())
def report(name, result):
m = result.metrics
charges = cost_totals(result)
slip = slippage_total(result)
print(name)
print(result.summary())
print(f"Gross P&L : Rs {result.gross_pnl['total']:,.2f}")
print(f"Charges paid : Rs {charges['charged']:,.2f}")
print(f" brokerage : Rs {charges['brokerage']:,.2f}")
print(f" STT : Rs {charges['stt']:,.2f}")
print(f" exchange : Rs {charges['exchange_txn']:,.2f}")
print(f" SEBI fee : Rs {charges['sebi_fee']:,.2f}")
print(f" stamp duty : Rs {charges['stamp_duty']:,.2f}")
print(f" GST : Rs {charges['gst']:,.2f}")
print(f" DP charge : Rs {charges['dp_charge']:,.2f}")
print(f"Slippage : Rs {slip:,.2f}")
print(f"Max DD amount : Rs {m['max_drawdown_amount']:,.2f}")
print(f"CAGR / Calmar : {m['cagr']:.2%} / {m['calmar']:.2f}")
print()
return result
if __name__ == "__main__":
report("zero / all-in", run(costs=None, slippage=0))
report("default / all-in", run())
kw = dict(costs=REALISTIC_COSTS, slippage=REALISTIC_SLIP)
report("realistic / all-in", run(**kw))
report(
"realistic / 50 percent of equity",
run({"size": bt.size.percent(50)}, **kw),
)
report(
"realistic / 1 percent risk to 2-ATR stop",
run({"size": bt.size.fixed_risk(1), "stop": bt.atr(2, period=14)}, **kw),
)
What comes next in this series
You now have a result you can read, a cost model you can state, and a position sizing choice you can defend. In Six-Stock Trend Portfolio Backtest with the OpenAlgo SDK we take the same engine to six stocks on one account.
Learn by watching: free videos every week
Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.




