Algo Trading with Python
OpenAlgo Python SDK setup, symbols, quotes and history, NumPy and pandas, Matplotlib, Plotly and Streamlit, 100+ openalgo.ta indicators, signals and scanners, a strategy playbook, orders, VectorBT backtests, metrics, optimisation, walk-forward, ML, WebSockets and position sizing.
00Algo trading with Python: atlas and routes
From an empty folder to a monitored live bot on the OpenAlgo Python SDK: setup and data, charts and dashboards, indicators, signals and scanners, a strategy playbook, orders, honest backtesting, machine learning, streaming and position sizing. Condensed from OpenAlgo's free Open Varsity course. Educational, not investment advice.
Algo trading with Python topic atlas#
How to use this sheet#
- New to Python: foundations, then market data. Every later script is "fetch a DataFrame, compute, decide".
- Building a strategy: indicators → signals → playbook → testing, in that order.
- Before any real order: execution, the backtest-trust ladder, position sizing and the go-live checklist at the end.
- Keep OpenAlgo in analyze mode (simulated orders) the whole time you learn.
From idea to live bot#
flowchart TD D["Data: history() and quotes()"] --> I["Indicators: openalgo.ta"] I --> G["Signals: crossover, exrem, shift(1)"] G --> B["Backtest: VectorBT with fees and slippage"] B --> W["Validate: walk-forward, out-of-sample"] W --> Z["Size: risk %, ATR stop, whole lots"] Z --> E["Execute: analyze mode first, then placeorder"] E --> M["Monitor: WebSocket feed, stops, alerts"]
Most ideas should die at the validate step. That is the process working, not failing.
Check yourself 2 questions
Which step comes right after a costed backtest?
Show answer
Validation: walk-forward and out-of-sample tests.
Where should a new bot run before real orders?
Show answer
OpenAlgo's analyze mode (sandbox).
Takeaway Data, indicators, shifted signals, a costed backtest, walk-forward validation, risk-based size, then analyze mode before live.
01Foundations: setup, secrets, the client and Python essentials
OpenAlgo Open Varsity · Algo Trading with Python · chapters 1–2 (getting started, Python essentials)
Set up once#
- Install Python (on Windows tick "Add Python to PATH"); check with
python --version. - Install VS Code and its Python extension.
- Run OpenAlgo locally; the dashboard opens at
http://127.0.0.1:5000. Copy your API key from its API Key page. pip install uv, thenuv init my-trading,cd my-trading,uv add openalgo.- Run scripts with
uv run python file.py: one isolated, reproducible project per idea.
Check yourself 2 questions
Where does the local OpenAlgo dashboard open?
Show answer
http://127.0.0.1:5000.
Which tool does the course use to create the project and add packages?
Show answer
uv (
uv init,uv add openalgo).
Takeaway Python, VS Code, OpenAlgo running locally at 127.0.0.1:5000, an API key, and a uv project with openalgo installed.
Keep secrets out of code#
- Put
OPENALGO_API_KEY,OPENALGO_HOST(and laterOPENALGO_WS_URL) in a.envfile; load it withpython-dotenvand read withos.getenv(). - Add
.envto.gitignore; commit a blank.env.exampleinstead. - Treat the key like an ATM PIN: never hard-code it, paste it in chat or push it to GitHub. Replace any placeholder default before running.
Check yourself 2 questions
How should you treat the API key?
Show answer
Like an ATM PIN: never hard-code it, paste it in chat or push it to GitHub.
What do you commit instead of .env?
Show answer
A blank .env.example.
Takeaway Keys live in a git-ignored .env file loaded with python-dotenv; commit only a blank .env.example.
The client, analyze mode and the safe-response pattern#
import os from dotenv import load_dotenv from openalgo import api, ta load_dotenv() client = api(api_key=os.getenv("OPENALGO_API_KEY"), host=os.getenv("OPENALGO_HOST", "http://127.0.0.1:5000")) # confirm analyze mode is ON while learning print(client.analyzerstatus()["data"]) resp = client.quotes(symbol="SBIN", exchange="NSE") # every reply: status + data (or message) if resp.get("status") == "success": q = resp["data"] pct = (q["ltp"] - q["prev_close"]) / q["prev_close"] * 100 else: print("failed:", resp.get("message"))
- Analyze mode simulates orders; nothing reaches the exchange.
client.analyzertoggle(mode=True)switches it on. Going live should be a deliberate act, never an accident. (The course shows the mode under bothmodeandanalyze_modekeys, so print it once.) - Payloads sit one layer down:
resp["data"]for most calls,resp["results"]for batch calls. Forgetting that layer is the commonest beginner error. client.funds()→availablecash,utiliseddebits,m2mrealized,m2munrealized.client.intervals()lists supported timeframes.- Wrap every live call in
try/exceptso one bad reply can't kill the bot; an unknown symbol returns an HTTP 400 "not found" (check master contracts are downloaded).
Check yourself 2 questions
Why check analyzerstatus() at startup while learning?
Show answer
To confirm orders go to the sandbox, not the live market.
What's the safe-response pattern?
Show answer
Check the response's status is success before reading its data.
Takeaway Create the client from environment variables, confirm analyze mode while learning, and check status before reading data.
Python essentials that carry the course#
| Tool | Trading use |
|---|---|
| List | Watchlists; index from 0, [-1] is the latest |
| Dict | Every SDK reply; nested reads like resp["data"]["ltp"] |
| f-string | f"{sym:10s} {ltp:>10,.2f}" for aligned output |
| for / if / def | Scale one check to many symbols, branch on data, avoid repetition |
| try / except | Keep a bot alive through errors |
| Comprehension | [b - a for a, b in zip(c, c[1:])] day-over-day changes |
Check yourself 2 questions
How do you read the LTP from a quotes reply?
Show answer
resp["data"]["ltp"].Why wrap API calls in try/except in a bot?
Show answer
So one error doesn't crash it.
Takeaway Lists for watchlists, dicts for every SDK reply, f-strings for output, loops and functions to scale, try/except to stay alive.
02Market data: symbols, quotes, history, NumPy and pandas
OpenAlgo Open Varsity · Algo Trading with Python · chapters 3–7 (symbols and exchanges, quotes and depth, historical data, NumPy, pandas)
One symbol format for every broker#
| Instrument | Format | Example |
|---|---|---|
| Equity | Base name | RELIANCE |
| Future | Base + DDMMMYY + FUT | NIFTY30JUN26FUT |
| Option | Base + DDMMMYY + strike + CE/PE | NIFTY30JUN2624000CE |
| Commodity future | Same as futures | GOLDM03JUL26FUT |
| Exchange code | Holds |
|---|---|
NSE / BSE | Stocks |
NFO / BFO | Futures and options |
MCX | Commodities, trading into the evening |
NSE_INDEX | Indices (quote-only): NIFTY, INDIAVIX |
Always pair a symbol with its exchange. Asking for NIFTY on NSE instead of NSE_INDEX, or a future on NSE instead of NFO, are classic misses.
Check yourself 2 questions
Format a NIFTY 24,000 call expiring 30 June 2026.
Show answer
NIFTY30JUN2624000CE.
Which exchange code holds NSE futures and options?
Show answer
NFO.
Takeaway OpenAlgo uses one symbol format across brokers: base, then DDMMMYY, strike and CE/PE for options, FUT for futures.
Discovering instruments and lot sizes#
info = client.symbol(symbol="SBIN", exchange="NSE")["data"] # keys: symbol, name, lotsize, tick_size, instrumenttype, expiry hits = client.search(query="NIFTY FUT", exchange="NFO")["data"] exps = client.expiry(symbol="NIFTY", exchange="NFO", # e.g. "30-JUN-26" instrumenttype="options")["data"] # DataFrame, ~9,700 rows master = client.instruments(exchange="NSE") value = info["lotsize"] * ltp # contract value
- Sample lot sizes: NIFTY 65, BANKNIFTY 30, RELIANCE future 500, GOLDM / CRUDEOIL / SILVERM 1. Ticks: SBIN 0.05, RELIANCE 0.1, BANKNIFTY future 0.2, CRUDEOIL 1.0.
- Exchanges revise lots, so look them up every time; never hard-code. One NIFTY future lot ≈ 65 × 23,810 ≈ ₹15.5 lakh.
- Weekly index options mean one strike has many expiries; the nearest is usually the most active.
Check yourself 2 questions
Which call returns a symbol's lot size and tick size?
Show answer
client.symbol(...).How do you list NIFTY option expiries?
Show answer
client.expiry(symbol="NIFTY", exchange="NFO", instrumenttype="options").
Takeaway symbol(), search() and expiry() return lot size, tick size and expiries, so nothing is hard-coded.
Quotes, multiquotes and depth#
| Call | Returns | Use |
|---|---|---|
quotes(symbol, exchange)["data"] | ltp, open, high, low, prev_close, bid, ask, volume, oi | One snapshot |
multiquotes(symbols=[{...}, ...])["results"] | Per item: symbol, exchange, data | Many symbols, mixed exchanges, one request (use beyond 2–3 symbols) |
depth(symbol, exchange)["data"] | ltp, totalbuyqty, totalsellqty, bids, asks (5 levels of price and quantity) | The order book |
- NSE and BSE cash trade 09:15–15:30 IST; depth is empty and quotes can show zeros when the market is shut, so guard
bids[0]and zero division. Practise depth on MCX in the evening. - Check the spread before trading anything unfamiliar. Imbalance and OI are supporting clues, never triggers on their own.
Check yourself 2 questions
When should you switch from quotes to multiquotes?
Show answer
Beyond 2–3 symbols: one request for many.
Where are multiquotes results found?
Show answer
Under
resp["results"], one item per symbol.
Takeaway quotes for one snapshot, multiquotes for many symbols in one request, depth for the order book.
Historical candles#
from datetime import datetime, timedelta end = datetime.now(); start = end - timedelta(days=120) df = client.history(symbol="TCS", exchange="NSE", interval="D", start_date=start.strftime("%Y-%m-%d"), end_date=end.strftime("%Y-%m-%d")) # DataFrame indexed by timestamp: open high low close volume oi
- Intervals:
1m 3m 5m 10m 15m 30m 60m 1h D. Ten calendar days of TCS: D 7 rows, 1h 49, 15m 175, 5m 525. - Calendar days are not sessions: 7 days gave 6 rows, 30 gave 21, 90 gave 59. Ask for a generous window and count rows.
- Intraday timestamps carry +05:30 IST; the first 5-minute bar is 09:15, the last 15:25.
oiis 0 for stocks. source="db"reads OpenAlgo's local store instead of the broker; wrap it intry/except. Build dates fromdatetimeso scripts never go stale.
Check yourself 2 questions
What does client.history() return?
Show answer
A pandas DataFrame indexed by timestamp.
Which interval code gives daily candles?
Show answer
"D".
Takeaway history() returns a DataFrame indexed by timestamp, with open, high, low, close and volume.
Resample the right way#
OHLCV = {"open": "first", "high": "max", "low": "min", "close": "last", "volume": "sum"} weekly = df.resample("W").agg(OHLCV).dropna() # "ME" = month-end hourly = df5.resample("60min").agg(OHLCV).dropna() df.to_csv("tcs.csv") # reproducible tests df = pd.read_csv("tcs.csv", index_col=0, parse_dates=True)
- Never average OHLC bars. First, max, min, last, sum is the only recipe.
- Resampling only goes up (5m → 1h, never back). Download the smallest interval you will need.
Check yourself 2 questions
Which aggregation does volume use when resampling?
Show answer
Sum.
Why save history to CSV?
Show answer
Reproducible tests on the same data.
Takeaway Resample OHLCV with first, max, min, last and sum; save CSVs for reproducible tests.
NumPy in five moves#
- Arrays:
np.array,np.arange(1, 6)(6 excluded),np.linspace(100, 200, 5); checkshape,ndim,size,dtype(prices arefloat64). - Indexing:
a[-1]latest;a[1:4]is three items;a[-5:]last five; 2Dp[:, -1]last column. - Vectorise:
closes * 1.05,closes * qty: no Python loops over prices. - Aggregate:
mean, max, min, std, median, sum, cumsum;axis=1across rows,axis=0down columns. - Masks:
mask = closes > closes.mean();closes[mask];mask.sum();np.where(cond, 1, 0): the seed of every signal.
Five RELIANCE closes 1305.0 … 1312.7: mean 1309.04, std 6.84, three days above average.
Check yourself 2 questions
Does np.arange(1, 6) include 6?
Show answer
No.
How do you take the last five values?
Show answer
a[-5:].
Takeaway Create arrays, index and slice, vectorise maths, aggregate, and use boolean masks: no loops over prices.
pandas for price series#
| Task | Idiom | Watch out |
|---|---|---|
| Pick a column | df["close"] (Series) vs df[["high","low"]] (DataFrame) | Single vs double brackets |
| Latest / date slice | .iloc[-1], .loc["2026-05-01":] | Keep the timestamp index: it powers dates, resampling and weekdays |
| Rolling window | .rolling(20).mean(), .max(), .min(), .std() | First 19 values are NaN by design |
| Returns and growth | r = close.pct_change(); (1 + r).cumprod() * 100000 | First return is NaN |
| Drawdown | close / close.cummax() - 1; its minimum is max drawdown | The core risk number |
| Group and combine | groupby(df.index.day_name()); pd.concat({"A": a, "B": b}, axis=1).dropna(); ra.corr(rb) | Correlate returns, not prices |
| Summarise | .describe(); annual vol = daily std × √252 | A "best weekday" from a few months is noise |
Check .shape and .head() on every new download before doing any maths.
Check yourself 2 questions
df["close"] versus df[["close"]]?
Show answer
A Series versus a one-column DataFrame.
Why are the first 19 values of rolling(20) NaN?
Show answer
The window isn't full yet.
Takeaway Keep the timestamp index; single brackets give a Series, double a DataFrame; rolling windows start with NaNs.
03Charts and apps: Matplotlib, Plotly and Streamlit
OpenAlgo Open Varsity · Algo Trading with Python · chapters 8–10 (Matplotlib, Plotly, Streamlit)
Matplotlib: precise charts saved to PNG#
fig, ax = plt.subplots(figsize=(9, 4.5)); draw withplot, bar, hist, scatter, fill_between, axhline; finish withplt.savefig(path, dpi=110, bbox_inches="tight")(headless: no window appears).- No weekend gaps: plot against
range(len(df))and label every Nth tick withdf.index.strftime("%d %b"). - Price over volume:
plt.subplots(2, 1, sharex=True, gridspec_kw={"height_ratios": [2, 1]}). - Overlays (SMA/EMA from
openalgo.ta), buy/sell markers (^,v), hand-built candles (wick line + body bar), equity curve with a line at 1.0, drawdown filled to zero, and rebasing to 100 for comparing stocks. - Seaborn for statistics: return histograms, correlation heatmaps (from returns, not prices), seasonality grids.
- Markers sit on the signal bar's close; a backtest must act on the next bar.
Check yourself 2 questions
How do you remove weekend gaps on a price chart?
Show answer
Plot against range(len(df)) and label ticks with dates.
Why use savefig in a headless script?
Show answer
No window can appear; the chart is saved to a file.
Takeaway Use fig, ax with savefig for headless PNGs, and plot against a range to remove weekend gaps.
Plotly: interactive candles#
import plotly.graph_objects as go from plotly.subplots import make_subplots x = df.index.strftime("%d %b") fig = make_subplots(rows=2, cols=1, shared_xaxes=True, row_heights=[0.7, 0.3], vertical_spacing=0.03) fig.add_trace(go.Candlestick(x=x, open=df.open, high=df.high, low=df.low, close=df.close), row=1, col=1) fig.add_trace(go.Bar(x=x, y=df.volume), row=2, col=1) fig.update_xaxes(type="category") # no weekend gaps fig.update_layout(xaxis_rangeslider_visible=False) fig.write_html("chart.html") # interactive, offline
- Figure = chart, trace = one series, layout = axes and titles. Overlays in price units share the price pane; bounded indicators (RSI, MACD) get their own pane, with
add_hlinefor 70/30. - Set
row=andcol=on every trace.write_imageneedskaleidoand loses interactivity.
Check yourself 2 questions
Which Plotly object draws candles?
Show answer
go.Candlestick.How do price and volume share a time axis?
Show answer
make_subplots with shared_xaxes=True.
Takeaway make_subplots with a candlestick row and a volume row gives an interactive, zoomable chart.
Streamlit: a dashboard in one script#
import streamlit as st # seconds for quotes, hours for daily history @st.cache_data(ttl=60) def load(sym, exch): return client.history(symbol=sym, exchange=exch, interval="D", start_date=start, end_date=end) sym = st.text_input("Symbol", value="RELIANCE") exch = st.selectbox("Exchange", ["NSE", "NFO", "MCX"]) df = load(sym, exch) st.metric("Last close", f"{df['close'].iloc[-1]:,.2f}") st.line_chart(df["close"])
- Launch with
streamlit run app.py(notpython); it opens atlocalhost:8501. - The whole script re-runs from the top whenever a widget changes. Write it as if it runs once, and cache every network call, or each slider move refetches history. Plain variables don't persist between runs.
- Building blocks:
st.title,st.metric,st.table,st.line_chart,st.plotly_chart(fig, use_container_width=True); widgetstext_input,selectbox,slider. A watchlist board is onemultiquotescall; a scanner is a loop ofhistory+ta.rsi.
Check yourself 2 questions
What TTL suits quotes versus daily history?
Show answer
Seconds for quotes, hours for daily history.
What decorator caches data loads?
Show answer
@st.cache_data.
Takeaway Streamlit turns a script into a dashboard; cache data with a TTL matched to how fast it changes.
04Indicators with openalgo.ta: trend, momentum, volatility, volume, oscillators and utilities
OpenAlgo Open Varsity · Algo Trading with Python · chapters 11–16 (trend, momentum, volatility, volume, oscillators, statistical, hybrid and utility)
Know the return type before you index#
| Returns | Functions | Read the latest with |
|---|---|---|
| pandas Series | sma, ema, wma, hma, vwma, kama, rsi, cci, williams_r, crsi, bop, atr, natr, bbpercent, bbwidth, hv, obv, adl, cmf, mfi, force_index, emv, vwap, rvol, vroc, cmo, trix, dpo, chop, linreg, lrslope, psar | .iloc[-1] |
| Tuple of Series | macd (3), bbands / keltner / donchian / ma_envelopes (3), supertrend (2), ichimoku (5), alligator (3), stochastic (2), fisher (2), chandelier_exit (2), ppo (3), stochrsi (2), tsi (2), adx (3), dmi (2), aroon (2), pivot_points (7), fractals (2) | Unpack first: m, s, h = ta.macd(c) |
| NumPy array | crossover, crossunder, highest, lowest, exrem, flip, valuewhen, rising, falling, roc | [-1], or wrap: pd.Series(arr, index=df.index) |
Mixing these up (calling .iloc on an array, unpacking a Series, assigning a tuple to one name) is the most common indicator bug. Import with from openalgo import ta.
Check yourself 2 questions
What does ta.macd return?
Show answer
A tuple of three Series: MACD, signal, histogram.
How do you read the latest value of a Series indicator?
Show answer
.iloc[-1].
Takeaway Some indicators return a Series, others a tuple of Series; check before indexing.
Trend tools#
| Call | Read |
|---|---|
sma, ema, wma, hma(close, n) | Price above the average = uptrend. Less lag means more whipsaws (HMA hugs price) |
vwma(close, volume, n) | Volume-weighted; needs volume |
kama(close) | Adapts: fast in clean trends, slow in chop |
supertrend(h, l, c, period=10, multiplier=3.0) | (line, direction): −1 = uptrend, +1 = downtrend |
ichimoku(h, l, c) | Above the cloud bullish, below bearish, inside: stand aside |
psar(high, low, 0.02, 0.2) | Dot below price bullish; doubles as a trailing stop. Takes high/low, not close |
ma_envelopes(close, 20, 2.5) | Fixed-% band: how stretched price is |
alligator(close) | Lips > teeth > jaw = trending up; tangled = range |
Periods: 9/20 for trading, 50/100/200 for the big picture; the 200-day is the classic bull/bear line. Trend filter: poll price > EMA50, Supertrend up and price > PSAR, and lean long only when 2 of 3 agree.
Check yourself 2 questions
Supertrend direction −1 means what in openalgo.ta?
Show answer
Uptrend.
What's KAMA's advantage?
Show answer
It adapts: fast in clean trends, slow in chop.
Takeaway Moving averages, KAMA and Supertrend: less lag means more whipsaws.
Momentum tools#
| Call | Zones |
|---|---|
rsi(close, 14) | > 70 overbought, < 30 oversold, 50 = bull/bear line |
macd(close) | (macd, signal, hist): MACD above signal bullish; histogram = building or fading |
stochastic(h, l, c, 14, 3) | (%K, %D): > 80 / < 20 |
cci(h, l, c, 20) | Unbounded: > +100 strong up, < −100 strong down |
williams_r(h, l, c, 14) | 0 to −100: above −20 overbought, below −80 oversold |
fisher(high, low, 9) | (fisher, trigger): cross after an extreme beyond ±1.5 |
crsi(close) | Short-term mean reversion: < 10 / > 90 |
bop(o, h, l, c) | −1 to +1: who won the bar |
Zones are context, not triggers: overbought can stay overbought in a strong trend. Divergence (price higher high, RSI lower high) is a warning; wait for confirmation.
Check yourself 2 questions
RSI zones?
Show answer
Above 70 overbought, below 30 oversold, 50 as the bull/bear line.
CCI above +100 means?
Show answer
Strong upward momentum (CCI is unbounded).
Takeaway RSI, MACD, stochastic, CCI and Williams %R each have their own zones.
Volatility tools#
| Call | Use |
|---|---|
atr(h, l, c, 14) | Unit of risk in price: stop = price − 2 × ATR |
natr(h, l, c, 14) | ATR as % of price: compare and size across assets |
bbands(close, 20, 2.0) | SMA ± 2σ; a band touch flags a stretch, not a reversal |
bbpercent / bbwidth(close) | Where in the band (0–1); squeeze when width ≤ 1.1 × its 60-day low |
keltner(h, l, c) | EMA ± ATR; Bollinger inside Keltner = compression |
donchian(high, low, 20) | N-bar high/low breakout levels (55 = Turtle) |
chandelier_exit(h, l, c, 22, 3.0) | (long stop, short stop) trailing from the extreme |
hv(close, 20) | Annualised %; HV20 above HV60 = expanding |
RELIANCE: ATR(14) 27.52 → stop 1,250.97 from 1,306, risk ₹55 a share; NATR 2.11%. Volatility gives size and range, never direction, and it mean-reverts: calm follows storms.
Check yourself 2 questions
A 2-ATR stop formula?
Show answer
Price − 2 × ATR.
When does the course call a squeeze?
Show answer
When bandwidth is at or below 1.1× its 60-day low.
Takeaway ATR is the unit of risk, NATR compares across assets, Bollinger bands flag stretch and squeezes.
Volume tools#
| Call | Read |
|---|---|
obv(close, volume), adl(h, l, c, v) | Cumulative: read the slope and divergences, not the level |
cmf(h, l, c, v, 20) | −1 to +1; beyond ±0.20 strong |
mfi(h, l, c, v, 14) | Volume-weighted RSI: > 80 / < 20, best in ranges |
force_index(c, v, 13) | Fresh zero-line cross = possible shift |
emv(h, l, v, 14) | How easily price moved per unit of volume |
vwap(h, l, c, v) | Session-anchored; intraday candles only |
rvol(volume, 20) | > 1.5 breakouts more trustworthy; < 0.7 quiet |
vroc(volume, 12) | ±50% surge or fade in participation |
Workflow: price event → participation (RVOL, VROC) → money flow (OBV/ADL, CMF) → act when they agree. Index spot has no real volume; use index futures on NFO.
Check yourself 2 questions
What do you read on OBV?
Show answer
Slope and divergences, not the level.
CMF of +0.25 suggests what?
Show answer
Strong buying pressure (beyond +0.20).
Takeaway OBV and A/D are cumulative (read slope and divergence); CMF beyond ±0.20 is strong; MFI is a volume-weighted RSI.
Oscillators: check the regime first#
| Call | Read |
|---|---|
chop(h, l, c, 14) | > 61.8 choppy (use range tools), < 38.2 trending (use trend tools) |
cmo(close, 14) | ±50 extremes |
ultimate_oscillator(h, l, c) | 7/14/28 blend: 70 / 30 |
stochrsi(close) | 80 / 20; whipsaws in trends |
aroon_oscillator(h, l, 14) | Near ±100 = fresh trend, near 0 = none |
roc(close, 12), trix(close, 15), awesome_oscillator(h, l), ppo, tsi | Unbounded: zero-line side and crosses confirm trend strength; PPO compares across symbols |
dpo(close, 20) | Exposes cycles; not a direction signal |
"Never trade an oscillator blind to the regime." Bounded oscillators suit ranges; unbounded ones confirm trends. roc returns a NumPy array.
Check yourself 2 questions
CHOP reads 65. Which tools?
Show answer
Range tools: it's choppy.
Aroon oscillator near ±100 means?
Show answer
A fresh trend.
Takeaway Choppiness above 61.8 means range tools, below 38.2 means trend tools.
Statistical and hybrid tools#
| Call | Tells you |
|---|---|
linreg, lrslope(close, 20), tsf | Regression fair value, its slope (> 0 up), one-bar projection |
correlation(a, b, n), beta(stock, mkt, 60) | Pair strength; market sensitivity (1 tracks the index) |
variance, median | Swing size; spike-resistant centre |
adx(h, l, c, 14) | (+DI, −DI, ADX): ADX > 25 strong, < 20 weak; larger DI gives direction |
aroon(h, l, 14) | (up, down) 0–100 |
pivot_points(h, l, c) | pivot, r1, s1, r2, s2, r3, s3 |
fractals(h, l, 2) | Swing-high and swing-low flags |
Align date ranges before beta or correlation, and sanity-check odd outputs (the course flags a suspiciously low beta in one run).
Check yourself 2 questions
A beta of 1 means what?
Show answer
The stock tracks the index.
ADX above what value means a strong trend?
Show answer
25.
Takeaway Linear regression, correlation, beta and ADX describe fair value, relationships, market sensitivity and trend strength.
Utility functions: from indicator to event#
| Call | Does |
|---|---|
crossover(a, b) / crossunder | True only on the bar of the cross |
highest(x, n) / lowest | Rolling max/min: breakout levels |
exrem(primary, secondary) | Drops repeat signals until the other side fires |
flip(on, off) | 1 from entry until exit: an in-position flag |
valuewhen(cond, x, 1) | Value of x at the latest true bar, e.g. entry price |
rising(x, n) / falling | Higher or lower than n bars ago |
- Combine arrays with
&,|,~and parentheses, neverand/or. highest(high, 20)[-1]already includes today, so a breakout test against it can never fire. Compare with[-2].
Check yourself 2 questions
What does exrem do?
Show answer
Drops repeat signals until the opposite side fires, so buys and sells alternate.
What does crossover return True on?
Show answer
Only the bar where the cross happens.
Takeaway crossover marks the bar of the cross, exrem removes repeats, flip builds an in-position flag.
05Signals and scanning
OpenAlgo Open Varsity · Algo Trading with Python · chapters 17–18 (from indicators to signals, scanning and screeners)
The signal pipeline#
- Fetch history.
- Compute indicators.
- Write raw conditions:
(close > ema50) & (rsi > 50). - Find turning points with
crossover/crossunder. - De-duplicate with
exremso buys and sells alternate. - Shift one bar:
.shift(1). - Hand
entriesandexits(boolean Series) to the backtester.
A signal is one True/False answer per bar, aligned to timestamps, not a single decision.
Check yourself 2 questions
Why shift signals one bar?
Show answer
To avoid look-ahead: you can act only after the bar that created the signal.
What form do entries and exits take for the backtester?
Show answer
Boolean Series.
Takeaway Fetch, compute, write conditions, find crosses, de-duplicate with exrem, shift one bar, hand to the backtester.
EMA crossover, done properly#
c = df["close"] fast, slow = ta.ema(c, 20), ta.ema(c, 50) S = lambda a: pd.Series(a, index=c.index) buy = S(ta.crossover(fast, slow)) sell = S(ta.crossunder(fast, slow)) buy, sell = S(ta.exrem(buy, sell)), S(ta.exrem(sell, buy)) entries = buy.shift(1).fillna(False) # act on the NEXT bar exits = sell.shift(1).fillna(False) inpos = S(ta.flip(buy, sell)) # 1 while holding entry_px = S(ta.valuewhen(buy, c, 1)) # price at the last buy
RSI example: raw buys 7 → 2 and raw sells 47 → 3 after exrem. Without it you stack repeated buys before any sell.
Check yourself 2 questions
Why wrap ta outputs in pd.Series with the close index?
Show answer
So signals align with dates for shifting and backtesting.
What's the final step before passing entries on?
Show answer
.shift(1).fillna(False).
Takeaway Crossover and crossunder, exrem both ways, then shift(1).fillna(False) for entries.
Look-ahead: the silent backtest killer#
- A signal computed from today's close only exists after the close. Trading on that same close assumes you knew the future.
- Fix:
signal.shift(1)for crossovers, RSI levels and breakouts alike; compare breakouts with the previous bar's level. - Remove the shift and an untradeable backtest becomes a flattering one. The same applies to charts: markers sit on the signal bar's close.
Main card on honest backtesting: Quant trading → Also in this sheet · Technical · Quant trading · AmiBroker AFL.
Check yourself 2 questions
How do you fix look-ahead for a breakout?
Show answer
Compare with the previous bar's level and shift the signal one bar.
What does removing the shift do to a backtest?
Show answer
Makes an untradeable backtest look flattering.
Takeaway A signal from today's close exists only after the close; trading that close assumes you knew the future.
Scanner = universe + loop + rule#
rows = [] for s in universe: try: df = client.history(symbol=s, exchange="NSE", interval="D", start_date=start, end_date=end) except Exception: continue if not isinstance(df, pd.DataFrame) or df.empty: continue # one bad symbol must not kill the scan c, h, v = df["close"], df["high"], df["volume"] rows.append({"symbol": s, "rsi": float(ta.rsi(c, 14).iloc[-1]), "above_ema50": c.iloc[-1] > ta.ema(c, 50).iloc[-1], "breakout": c.iloc[-1] > np.asarray(ta.highest(h, 20))[-2], "rvol": v.iloc[-1] / v.rolling(20).mean().iloc[-1], "ret20": c.iloc[-1] / c.iloc[-21] - 1}) board = pd.DataFrame(rows).sort_values("ret20", ascending=False).reset_index(drop=True) board.index += 1 # 1-based ranks
Filters: RSI < 30 or > 70, close above EMA50, 20-day breakout against yesterday's high, RVOL > 1.5. For a live snapshot of many names, one multiquotes() call beats a loop; loop history() only when you need time-series indicators. The same loop works for NFO and MCX (whose futures symbols carry the expiry).
Check yourself 2 questions
Why wrap each symbol's fetch in try/except?
Show answer
One bad symbol must not kill the whole scan.
What do you check before using a fetched frame?
Show answer
That it's a DataFrame and not empty.
Takeaway A scanner loops a universe through one rule, skipping symbols that error or return empty data.
06Strategy playbook: equity, intraday, pairs, momentum, seasonal and options
OpenAlgo Open Varsity · Algo Trading with Python · chapters 19–24 (cash and equity, intraday, pairs and stat arb, momentum and volatility, seasonal, options)
Cash and equity strategies#
| Strategy | Rules | Course run |
|---|---|---|
| Golden cross | Enter on 50-SMA crossing above 200-SMA, exit on the death cross; trade only in a bullish regime | Needs ≈ 400 calendar days of data or it silently does nothing; RELIANCE regime was bearish (SMA50 1,347 vs SMA200 1,421) |
| EMA 20/50 crossover | Enter on the 20 crossing above the 50, exit on the reverse | ICICIBANK −15.5% vs buy-and-hold −7.8% |
| Momentum rotation | Rank 12 NSE stocks by 60-bar return, hold the top 3, re-rank monthly | Leaders LT +24.8%, AXISBANK +16.0%; laggard INFY −16.4% |
| Donchian 20 breakout | Enter above the prior bar's 20-day high, exit below the prior 20-day low | LT −3.8% vs buy-and-hold +15.8% |
Delivery trades use product="CNC"; guard orders with a regime check so the bot stays flat in downtrends. Cost-free previews are a smell test: if a rule can't beat buy-and-hold, its complexity isn't earning its keep.
Check yourself 2 questions
Why can a golden-cross strategy silently do nothing?
Show answer
It needs about 400 calendar days of data for the 200-day average.
What does the regime filter do?
Show answer
Allows trades only in a bullish regime.
Takeaway Golden cross, EMA crossover and similar cash strategies need enough history and a regime filter.
Intraday strategies#
| Strategy | Rules |
|---|---|
| Opening range breakout | Range = 09:15–09:29 high/low; enter on a later close beyond it, ≈ 09:30–15:15. 15 vs 30 minutes trades speed for fewer fakeouts |
| VWAP reversion | Buy when stretched below session VWAP by a threshold (0.40% in the course); range days only, with a trend filter to switch it off |
| EMA 9/21 on 5-minute | Cross up / cross down; wrap the arrays in Series |
| Time exit | No new entries and force flat after a cutoff (15:10 in the course) |
- ≈ 75 five-minute bars per NSE session; split days with
df.groupby(df.index.normalize())and windows withbetween_time("09:15", "09:29"). - Equity MIS orders are rejected after ≈ 15:15; MCX runs into the evening. Never carry MIS into the close.
- NIFTY future, 5-minute 9/21, VectorBT with fees 0.03%: −2.08%, 32 trades, 28.1% wins. Costs dominate intraday.
Check yourself 2 questions
Opening range in the course?
Show answer
The 9:15–9:29 high and low; enter on a later close beyond it.
When should VWAP reversion be switched off?
Show answer
On trending days; it suits range days.
Takeaway Opening range breakout, VWAP reversion and intraday EMA trades each need time windows and the right market type.
Pairs and statistical arbitrage#
- ICICIBANK / HDFCBANK: return correlation 0.601, β 0.597, latest z 1.26, but rolling 30-day correlation fell as low as −0.097. Monitor it and stand aside when it breaks.
- Correlate returns, not prices; size legs by β, not one-for-one; count both legs' costs, borrow fees and squeeze risk. Spreads can stay dislocated longer than capital lasts.
- The course's single-leg backtest: −3.18% over 6 trades. Cointegration is covered in the Statistical Arbitrage sheet.
Main card on cointegration: Stat arb → Also in Quant trading · Stat arb.
Check yourself 2 questions
z above +2: which legs?
Show answer
Sell A, buy B.
Why was the ICICI/HDFC pair shaky despite 0.6 correlation?
Show answer
Rolling 30-day correlation fell to negative at times.
Takeaway Trade z-score extremes of a hedged spread, exit near zero, and only when correlation stays healthy.
Momentum and volatility trading#
| Tool | Rule |
|---|---|
| Cross-sectional momentum | Rank by 60-day return, hold the top 3; skipping the latest week ("12-1") is a refinement |
| ATR breakout | Close > previous close + 1 × ATR (1.5 × on GOLDM); shift inputs a bar |
| Bollinger squeeze | Bandwidth in the bottom 20% of its 60-day range: timing, not direction |
| Regime filter | Long only when close > 200-day SMA |
| Volatility targeting | Size = 15% target ÷ realised vol (20-day std × √252), capped at 3× |
SBIN realised vol 15.4% → size 0.97× ≈ 190 shares on ₹2 lakh. Momentum + regime backtest on ICICIBANK: −9.76%, 8 trades, max drawdown −11.3%. Judge momentum on a rebalanced basket, not one stock over one year.
Check yourself 2 questions
What does '12-1' momentum skip?
Show answer
The most recent period (the latest week or month).
Does a Bollinger squeeze give direction?
Show answer
No, only timing.
Takeaway Rank by 60-day return and hold the top names; ATR breakouts and Bollinger squeezes time entries.
Seasonal and calendar effects#
| Effect (NIFTY, ≈ 610 sessions) | Result |
|---|---|
| Day of week | Wed +0.189%, Tue −0.064%; ≈ 120 samples each |
| Month | Apr +4.06% (start of the Indian financial year), Jan −1.84% |
| Turn of month (last 2 + first 3 days) | −0.053% vs +0.042% otherwise: folklore not supported |
| Expiry Tuesday | −0.064% vs +0.041%, 49.2% up days |
"Long only on Mondays and Wednesdays" grew 100 → 130.1 vs 109.6 for buy-and-hold, but the days were picked on the same data, so it proves nothing. Measure on returns, always print counts, check the year × month heatmap for outlier-driven averages, and discover the expiry weekday at runtime with client.expiry().
Check yourself 2 questions
Was the turn-of-month effect supported?
Show answer
No: slightly negative versus positive otherwise.
Best month in the sample?
Show answer
April (about +4%).
Takeaway Calendar effects in about 610 sessions were small and mostly folklore; samples of about 120 days are thin.
Options through the SDK#
| Call | Returns / does |
|---|---|
expiry(symbol, "NFO", instrumenttype="options") | Expiry list as DD-MON-YY |
optionchain(underlying, exchange, expiry_date, strike_count) | underlying_ltp, atm_strike, chain[] with per-side LTP and labels |
optionsymbol(underlying, exchange, expiry_date, offset, option_type) | Resolves ATM, ITMn, OTMn to a symbol and lot size |
optiongreeks(symbol, exchange, interest_rate, underlying_symbol, underlying_exchange) | Days to expiry, IV, delta, gamma, theta, vega |
syntheticfuture(underlying, exchange, expiry_date) | Synthetic future price, ATM strike, spot |
optionsorder(...) / optionsmultiorder(..., legs=[...]) | Single leg by offset; multi-leg with overall status plus per-leg results |
- Order endpoints want
DDMMMYY: convert withstrftime("%d%b%y").upper(). Discover the nearest expiry at runtime and resolve strikes by offset instead of hard-coding. - Live run: NIFTY 23,824.1, ATM 23,800, call 173.35, put 159.45; ATM call delta 0.517, theta −12.1, vega 13.0, IV 12.78%; synthetic future 23,813.9 (basis −10.2).
- Coded examples: long call and put, bull call spread (buy ATM, sell OTM3), long straddle, protective put. Quantity must be a lot multiple; use NRML to carry; check analyze mode first and every leg's status, not just the overall one.
Check yourself 2 questions
What does optionsymbol resolve?
Show answer
Option symbols from offsets like ATM, ITMn or OTMn.
What does optionchain return?
Show answer
The underlying LTP, ATM strike and a chain with per-side prices.
Takeaway expiry, optionchain and optionsymbol resolve expiries, the ATM strike and offsets such as ITM2 or OTM3.
07Execution: placing and managing orders
OpenAlgo Open Varsity · Algo Trading with Python · chapter 25 (placing and managing orders)
Order parameters#
| Field | Values |
|---|---|
action | BUY / SELL |
product | CNC delivery · MIS intraday, auto squared off · NRML F&O carried overnight |
price_type | MARKET: no price · LIMIT: price · SL: price + trigger_price · SL-M: trigger_price |
r = client.placeorder( strategy="ema_x", symbol="SBIN", exchange="NSE", action="BUY", price_type="LIMIT", product="CNC", quantity=1, price=810.0) print(r["status"], r.get("orderid"))
Spelling trap: price_type in placeorder, placesmartorder and splitorder, but pricetype inside basket legs. Match the product to the holding period.
Check yourself 2 questions
Which product is auto squared off intraday?
Show answer
MIS.
Which price type needs only a trigger price?
Show answer
SL-M.
Takeaway Action, product (CNC, MIS, NRML), price type (MARKET, LIMIT, SL, SL-M), with price or trigger as needed.
Order methods#
| Call | Does |
|---|---|
placeorder | One order |
placesmartorder(..., position_size=) | Trades only the difference to an absolute target; 0 flattens |
basketorder(orders=[...]) | Many orders at once; per-leg results |
splitorder(..., quantity, splitsize) | Chunks a large order (5 by 2 → 2, 2, 1) under the exchange freeze quantity |
modifyorder(order_id, ...) | Re-send full details for an open order; can't flip BUY to SELL |
cancelorder(order_id, strategy) | Cancel one |
cancelallorder(strategy) | Cancel every pending order |
closeposition(strategy) | Market-close everything, no confirmation: an emergency tool |
Check yourself 2 questions
placesmartorder with position_size=0 does what?
Show answer
Flattens the position.
Why use splitorder?
Show answer
To chunk an order above the exchange freeze quantity.
Takeaway placeorder for one, placesmartorder for a target position, basketorder for many, splitorder above freeze limits.
Which order call?#
Check yourself 2 questions
You want to reach exactly 100 shares regardless of what you hold. Which call?
Show answer
placesmartorder with position_size=100.
After a basket order, what must you check?
Show answer
Every leg's status.
Takeaway Target a position → smart order; many legs → basket; above freeze → split; otherwise placeorder.
Reading the books#
| Call | data shape | Useful fields |
|---|---|---|
orderbook() | Dict: orders list + statistics | order_status; totals of completed, open, rejected |
tradebook() | List of fills | action, symbol, average_price |
positionbook() | List | symbol, quantity, ltp, pnl; open = quantity != 0 |
funds() | Dict | availablecash, M2M realised and unrealised |
- Shapes differ (dict vs list): print each once before writing code against it.
- NSE cash closes 15:30 and MIS is rejected after the broker's square-off time; MCX is the evening practice ground.
- Never wire
closeposition()to a hair-trigger.
Check yourself 2 questions
How do you find open positions in positionbook?
Show answer
Rows with quantity not equal to 0.
Where's available cash?
Show answer
funds()→ availablecash.
Takeaway orderbook, tradebook, positionbook and funds show orders, fills, open positions and cash.
08Testing: backtests, metrics, optimisation and walk-forward
OpenAlgo Open Varsity · Algo Trading with Python · chapters 26–29 (backtesting and VectorBT, performance metrics, optimisation, walk-forward)
Backtest by hand first#
fast, slow = c.ewm(span=10).mean(), c.ewm(span=30).mean() signal = (fast > slow).astype(int) pos = signal.shift(1).fillna(0) # yesterday's decision ret = c.pct_change().fillna(0) equity = 100000 * (1 + pos * ret).cumprod() bh = 100000 * (1 + ret).cumprod() # always compare
SBIN 10/30 EMA, no costs: +12.71% vs buy-and-hold +28.75%. Positive is not the same as good.
Check yourself 2 questions
Why use signal.shift(1) as the position?
Show answer
Today you hold what yesterday's signal decided.
What benchmark should every backtest show?
Show answer
Buy-and-hold.
Takeaway Position = yesterday's signal; equity = cumulative product of 1 + position × return; always compare with buy-and-hold.
VectorBT with costs#
import vectorbt as vbt entries = (fast > slow) & (fast.shift(1) <= slow.shift(1)) exits = (fast < slow) & (fast.shift(1) >= slow.shift(1)) pf = vbt.Portfolio.from_signals( c, entries, exits, init_cash=100000, fees=0.001, slippage=0.0005, freq="1D", direction="longonly") pf.total_return(); pf.trades.count() pf.max_drawdown(); pf.stats()
- SBIN with costs: +10.87%, 6 trades, ≈ ₹1,136 fees, max drawdown ≈ 19.7%, 20% wins, Sharpe ≈ 0.75. Going both ways (
direction="both"): −6.25%. - Same settings on GOLDM 20/50: −11.43% vs −3.05% buy-and-hold, −32% drawdown. Results don't transfer between instruments.
Check yourself 2 questions
Fees and slippage used in the course example?
Show answer
0.1% fees and 0.05% slippage.
Why include costs before comparing strategies?
Show answer
They often change which strategy wins.
Takeaway from_signals with fees and slippage; costs often flip the winner.
Performance metrics#
| Metric | Formula | Read | RELIANCE run |
|---|---|---|---|
| Total return | final ÷ initial − 1 | Ignores time: compare equal-length tests only | −7.24% |
| CAGR | (1+r).prod() ** (252/n) − 1 | The fair yardstick across lengths | −9.57% |
| Sharpe | mean ÷ std of daily returns × √252 | < 0 losing · ≈ 1 good · 2 excellent · 3+ suspicious | −0.66 |
| Sortino | Like Sharpe, downside volatility only | Usually a bit above Sharpe | −0.88 |
| Max drawdown | min of equity ÷ running peak − 1 | A 50% loss needs +100% to recover | −13.8% |
| Calmar | CAGR ÷ |max drawdown| | Return per unit of worst pain | −0.69 |
| Win rate | Winning trades ÷ trades | Meaningless alone | 25% of 4 |
| Profit factor | Gross profit ÷ gross loss | Must exceed 1 | 0.32 |
| Benchmark edge | Strategy − NIFTY buy-and-hold | The question that matters | −2.63% |
VectorBT exposes these on pf (annualized_return, sharpe_ratio, sortino_ratio, calmar_ratio, trades.win_rate, trades.profit_factor); QuantStats builds full tearsheets (qs.reports.metrics(rets, benchmark=bench)). Judge a strategy by its worst night, not only its destination.
Check yourself 2 questions
Why prefer CAGR to total return when comparing tests?
Show answer
Total return ignores time; CAGR is fair across lengths.
A backtest Sharpe of 3.5: what should you think?
Show answer
Suspicious: likely overfit or flawed.
Takeaway Use CAGR across lengths, Sharpe and Sortino for risk-adjusted return, and treat a Sharpe above 3 as suspicious.
Optimisation: plateaus beat peaks#
- Grid = small lists →
itertools.product→ drop invalid pairs (fast ≥ slow) → one backtest per combo → rank. Every extra value multiplies work and false winners. - Vectorise: 2D entries/exits with a
MultiIndexof (fast, slow), onefrom_signalscall,pf.sharpe_ratio().idxmax(), then.unstack("slow")for a heatmap. - Broad green plateau = robust; a lone green cell beating its neighbours by a mile, or a winner with very few trades, is luck.
- RELIANCE 16-combo grid: best 5/40 at +3.10% with 0.1% fees. Adding realistic costs dropped 5/30 from 4.23% to 1.76% and changed the winner; on GOLDM most combos lost. Re-optimise per instrument, with costs, then validate out of sample.
Check yourself 2 questions
Why prefer a plateau to a peak?
Show answer
Neighbouring parameters also work, so it's less likely to be luck.
What does each extra grid value multiply?
Show answer
Work and false winners.
Takeaway Small grids, invalid combos dropped, and a broad plateau of good parameters beats one sharp peak.
Walk-forward: the only number that counts#
- Split by time, never shuffle: first ≈ 70% in-sample, last ≈ 30% out-of-sample.
- Tune on in-sample only; pick the best Sharpe.
- Run that one winner on the unseen slice.
- Roll it: tune 250 bars, test the next 100, slide by 100, repeat; log picks and results.
- Check parameter stability, the in/out gap and trade counts.
RELIANCE, 610 bars (427 / 183): EMA 30/60 won in-sample at +15.90% (Sharpe 0.71) and lost −4.57% out of sample; rolling windows: −3.30%, −6.07%, −4.15%. Expect honest results from simple ideas to look like this, and deflate any winner picked from many tries.
Check yourself 2 questions
Should you shuffle data before splitting?
Show answer
Never; split by time.
Typical in-sample versus out-of-sample split?
Show answer
About 70% / 30%.
Takeaway Split by time, tune in-sample, test the winner on unseen data, and roll forward.
Can I trust this backtest?#
Main card on honest backtesting: Quant trading → Also in this sheet · Technical · Quant trading · AmiBroker AFL.
Check yourself 2 questions
First check on any promising backtest?
Show answer
Are signals shifted one bar so trades use only past data?
The strategy doesn't beat buy-and-hold on CAGR. Verdict?
Show answer
Not worth the complexity.
Takeaway Shifted signals, realistic costs, beating the benchmark, out-of-sample stability and enough trades.
09Going live: machine learning, streaming and position sizing
OpenAlgo Open Varsity · Algo Trading with Python · chapters 30–32 (ML, neural nets and a complete bot, WebSockets, risk and position sizing)
Machine learning: workflow over model#
- Features: RSI, ATR, distance from EMA, recent returns;
dropna()the warm-up rows. - Label: next bar up,
(c.shift(-1) > c).astype(int). The bar to beat is the base rate: always guessing the majority class. - Split by time (
train_test_split(..., shuffle=False)) and fit any scaler on the training set only; then walk-forward (train 300, test 100, slide). - Models: logistic regression, random forest (depth 4, 100–150 trees), a small neural net
MLPClassifier((16, 8))with scaled inputs. Bigger nets fit noise faster.
| RELIANCE test set | Accuracy |
|---|---|
| Naive baseline | 54.4% |
| Logistic regression | 47.0% |
| Random forest | 47.7% |
| Neural net | 49.0% |
None beat the baseline, and walk-forward averaged ≈ 49.5%. Expect coin-flip accuracy; feature importance is a hint, not proof.
Check yourself 2 questions
What's the bar a classifier must beat?
Show answer
The base rate: always guessing the majority class.
Where should the scaler be fit?
Show answer
On the training set only.
Takeaway Features without look-ahead, a next-bar label, a time-ordered split, scalers fit on training only, and beating the base rate.
Anatomy of the capstone bot#
- Fetch daily history.
- Engineer features and the label.
- Train, then predict the latest row.
- Act: BUY 1 (MARKET, CNC) on an up signal;
placesmartorder(position_size=0)to flatten on a down signal. - Alert via Telegram inside
try/exceptso a missing link can't crash it. - Schedule after the close with cron, Task Scheduler or OpenAlgo's strategy host.
Gaps to fill before real money: a proper loop, risk checks, sizing (below) and real logging. Run in analyze mode, small, with a human watching.
Check yourself 2 questions
How does the bot exit on a down signal?
Show answer
placesmartorder with position_size=0.
Why wrap the Telegram alert in try/except?
Show answer
So a missing link can't crash the bot.
Takeaway Fetch, engineer, train, predict the latest row, act via smart orders, alert safely, and schedule after the close.
WebSockets: stream to watch, REST to act#
flowchart TD
C["connect() once"] --> SUB["subscribe_ltp / quote / depth"]
SUB --> CB["Callback: read tick, update state, decide; keep it fast"]
CB --> X{{"Stop, target or trail hit?"}}
X -->|no| CB
X -->|yes| R["Send the exit through REST placeorder"]
R --> U["unsubscribe, then disconnect()"]
classDef dec fill:__DF__,stroke:__DS__,color:__FG__
class X decCheck yourself 2 questions
Should orders go through the WebSocket?
Show answer
No. Stream to watch, REST to act.
What must the callback be?
Show answer
Fast: read the tick, update state, decide.
Takeaway Stream ticks through a fast callback, send exits through REST, then unsubscribe and disconnect.
Streaming details#
- Client:
api(api_key, host, ws_url); local feedws://127.0.0.1:8765, productionwss://…/wsviaOPENALGO_WS_URL. - Instruments:
[{"exchange": "NSE", "symbol": "RELIANCE"}]; callbackdef cb(message)readsmessage["data"]["ltp"]. - Modes: LTP (lightest), Quote (OHLC and volume), Depth (order book).
- Callbacks run on a background thread: no downloads or heavy maths inside. Keep trade state (entry, stop, target) in long-lived variables or a class.
- The server pings about every 30 s and the client reconnects and re-subscribes on drops.
Check yourself 2 questions
Which streaming mode is lightest?
Show answer
LTP.
Which mode gives the order book?
Show answer
Depth.
Takeaway Three modes (LTP, Quote, Depth); the local feed is ws://127.0.0.1:8765; callbacks run on another thread.
Position sizing by rupee risk#
- RELIANCE entry 1,400, stop 1,372 → ₹28 risk a share: on ₹5 lakh at 1% (₹5,000) that is 178 shares (our illustration).
- NIFTY entry 25,900, stop 25,750 → ₹150 a unit; with ₹5,000 at risk that is 33 units, which rounds down to zero lots of 65: the trade is too big for the account.
- Heat example: RELIANCE 40 × 28 + INFY 30 × 30 + TATASTEEL 200 × 4 = ₹2,820. Correlated positions are one bigger bet; size them together.
- Survival maths: with a 55% win rate, risking 2% a trade survives losing streaks that 20% cannot; a 50% loss needs +100%. Don't raise size after a winning run, and don't let a tight stop create an oversized position.
- Pull capital from
funds()["data"]["availablecash"]and price fromquotes(); wrap it all in oneposition_size()helper.
Main card on position sizing: Risk management → Also in Technical · OV technicals · Futures · Options basics · Options strategies · Stock basics · AmiBroker AFL.
Check yourself 2 questions
How do you round F&O quantity?
Show answer
Down to whole lots: (qty // lot_size) × lot_size.
Maximum total heat in the course?
Show answer
About 6% of capital.
Takeaway Qty = floor(1% of capital ÷ stop distance); F&O rounds down to whole lots; keep total heat at or below 6%.
10My setup: a personal live-trading runbook
SEBI circular "Safer participation of retail investors in algorithmic trading" (4 Feb 2025) and the exchange and broker implementation notes, mandatory from 1 April 2026; broker charge pages; OpenAlgo documentation (analyze mode). Written generically: substitute your own broker, host and numbers.
Costs per strategy on your broker#
Fill this table once from your broker's charges page and your own contract notes, then use the round-trip figure in every backtest for that strategy.
| Strategy type | Product | Main charges on a round trip | Write down |
|---|---|---|---|
| Intraday equity | MIS | Brokerage both legs, STT 0.025% on the sell side, exchange and SEBI fees, stamp duty on the buy, GST on brokerage and fees | Cost in basis points of turnover |
| Positional or swing equity | CNC (delivery) | STT 0.1% on both buy and sell, stamp duty, DP charge per scrip sold, usually low or zero brokerage | Cost per trade plus the DP charge |
| Index futures | NRML or MIS | Brokerage both legs, STT 0.05% on the sell side, exchange fees, stamp duty, GST | Cost per lot round trip |
| Option buying | NRML or MIS | Flat brokerage per order often dominates; STT 0.15% of premium on the sell side; exercise of an in-the-money option attracts STT on intrinsic value | Cost as a share of the premium paid |
| Option selling | NRML | Same charges, plus the margin blocked (and any pledging haircut) as the real capital cost | Cost per lot and return on margin |
Then compare: round-trip cost ÷ average edge per trade. If costs eat more than about a third of the backtested edge, slippage on a bad day will take the rest. Rates above are the 2026 STT schedule; the "Numbers that expire" card lists when they were last checked.
Check yourself 2 questions
What STT applies to intraday equity, and on which side?
Show answer
0.025% on the sell side.
When is a strategy's cost too high?
Show answer
When round-trip cost eats more than about a third of the backtested edge per trade.
Takeaway Build a round-trip cost per strategy from your broker's charges and contract notes, then compare it with the average edge per trade.
Static IP and algo ID: compliance steps#
- Get a static IP from your internet provider or a cloud server. Under the retail-algo framework, API orders are accepted only from a whitelisted static IP; requests from anywhere else are rejected.
- Register it in your broker's developer console against your API app (brokers typically allow one or two addresses). If the address changes, update it there before the next session, or orders will fail.
- Log in with two-factor authentication every trading day. API sessions reset daily; a bot cannot keep yesterday's token alive, so build a morning login step.
- Stay under 10 orders per second per exchange segment, or register the strategy through your broker; registered algos get an exchange algo ID tagged on every order so each order traces back to its strategy.
- Use only empanelled platforms. Third-party algo providers must be approved by and connected through your broker; you can't connect a script straight to the exchange.
- Expect market-order protection: brokers may convert market orders to protected (limit-capped) orders, so handle partial fills.
Check yourself 2 questions
What happens to API orders from a non-whitelisted IP?
Show answer
They are rejected.
What triggers registration and an exchange algo ID?
Show answer
Reaching 10 orders per second per exchange segment.
Takeaway Whitelisted static IP, daily 2FA login, under 10 orders per second per segment or a registered algo ID, and only broker-empanelled platforms.
Sandbox to live: a staged runbook#
| Stage | Run it how | Move on when |
|---|---|---|
| 1. Analyze mode | OpenAlgo's simulated orders, live data, full bot loop | Two weeks with no unhandled errors, every order path exercised |
| 2. Shadow | Bot logs the orders it would place; you compare with what the market did | Simulated fills and costs are close to the backtest's assumptions |
| 3. Smallest size | One lot or the smallest quantity, real money, you watching | Live P&L per trade is within the backtest's expected range after real costs |
| 4. Planned size | Step up in stages, not one jump | Drawdown stays inside the limit you set before going live |
Kill switch: write down, before stage 3, the daily loss, error count or drawdown that stops the bot and flattens positions, and test that switch in stage 1.
Check yourself 2 questions
When should the kill switch be defined and tested?
Show answer
Defined before the first real-money stage, tested in analyze mode.
What lets you move from smallest size to planned size?
Show answer
Live P&L per trade within the backtest's expected range after real costs, and drawdown inside your preset limit.
Takeaway Analyze mode, shadow, smallest real size, then planned size in steps, with a kill switch written and tested before real money.
My setup: daily operating routine#
- Before the open: confirm the server is up and its static IP unchanged, log in with 2FA, check funds and margin, and confirm the bot's open positions match the broker's.
- During the session: alerts on rejected orders, disconnects and the loss limit; a human can reach the kill switch from a phone.
- Before the cutoff: intraday strategies stop new entries early and flatten before the broker's MIS square-off.
- After the close: reconcile the bot's log with the tradebook, note any mismatch, and back up logs.
- Weekly: compare live results with the backtest's expected range; monthly, recompute costs from contract notes.
Check yourself 2 questions
What must match before the open?
Show answer
The bot's open positions and the broker's positions (plus server IP, funds and margin).
What happens after the close?
Show answer
Reconcile the bot's log with the tradebook and back up logs.
Takeaway Pre-open checks and 2FA login, alerts in session, flatten before the MIS cutoff, reconcile after the close.
11Checklists and quick reference
Read this before the first real-money order.
Go-live checklist#
- Keys live in
.env, never in code or Git. - Every call checks
statusand survives errors. - Signals are shifted one bar; breakouts use the prior bar's level.
- The backtest has realistic fees and slippage and beats the benchmark.
- It holds out of sample with stable parameters and enough trades.
- Size comes from rupee risk, rounded down to whole lots; total heat is capped.
- Intraday code stops entries before the MIS cutoff and forces flat.
- Multi-leg orders check every leg's status.
- Weeks of analyze-mode running, logs and alerts, then small live size with a human watching.
Check yourself 2 questions
Where must keys live before going live?
Show answer
In .env, never in code or Git.
Name two backtest conditions on the checklist.
Show answer
Any two of: shifted signals, realistic fees and slippage, beats the benchmark, holds out of sample with stable parameters and enough trades.
Takeaway Keys in .env, errors survived, signals shifted, costed benchmark-beating backtest, out-of-sample stability, risk-based size, analyze mode first.
Idioms to keep#
Check yourself 2 questions
Annual volatility from daily returns?
Show answer
Daily std × √252.
Breakout check without look-ahead?
Show answer
close[-1] > highest(high, n)[-2].
Takeaway resp['data'], pct_change, cumprod equity, cummax drawdown, OHLCV resample, crossover Series, annualised vol.
About this sheet#
This sheet condenses the free course Algo Trading with Python from OpenAlgo Open Varsity (32 chapters, 9 modules, built on the OpenAlgo Python SDK) into reference cards in our own words. Numbers are from the course's own runs on mid-2026 data and will differ when you run them. Code is short illustrative idiom, not copied listings. Each section links back to its chapters. Educational, not investment advice.
Numbers that expire#
Every figure on this sheet that a regulator, exchange or budget can change, with when it last changed. Last checked 15 Nov 2026; verify before trading.
| What | Current value | As of |
|---|---|---|
| NIFTY lot size | 65 (was 75) | from the Jan 2026 expiries · source |
| Index option expiry day | NSE: Tuesday (weekly NIFTY, monthly last Tuesday) · BSE: Thursday | since Sep 2025 · source |
| Retail algo framework | Mandatory from 1 Apr 2026: whitelisted static IP, daily 2FA, algo ID for strategies at 10+ orders per second per segment | SEBI circular 4 Feb 2025, deadline 1 Apr 2026 · source |