CSCheatsheets
Open Varsity · Intermediate

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.

12sections
58cards
5diagrams
0%known

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.

How to use this sheet#

  1. New to Python: foundations, then market data. Every later script is "fetch a DataFrame, compute, decide".
  2. Building a strategy: indicators → signals → playbook → testing, in that order.
  3. Before any real order: execution, the backtest-trust ladder, position sizing and the go-live checklist at the end.
  4. Keep OpenAlgo in analyze mode (simulated orders) the whole time you learn.
Educational, not investment advice. Condensed in our own words from OpenAlgo Open Varsity: Algo Trading with Python. Code here is short illustrative idiom in the course's style, not a copy; SDK field names can change between versions, so print a response once before relying on its shape.

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
  1. Which step comes right after a costed backtest?

    Show answer

    Validation: walk-forward and out-of-sample tests.

  2. 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#

  1. Install Python (on Windows tick "Add Python to PATH"); check with python --version.
  2. Install VS Code and its Python extension.
  3. Run OpenAlgo locally; the dashboard opens at http://127.0.0.1:5000. Copy your API key from its API Key page.
  4. pip install uv, then uv init my-trading, cd my-trading, uv add openalgo.
  5. Run scripts with uv run python file.py: one isolated, reproducible project per idea.
Check yourself 2 questions
  1. Where does the local OpenAlgo dashboard open?

    Show answer

    http://127.0.0.1:5000.

  2. 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 later OPENALGO_WS_URL) in a .env file; load it with python-dotenv and read with os.getenv().
  • Add .env to .gitignore; commit a blank .env.example instead.
  • 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
  1. 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.

  2. 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 both mode and analyze_mode keys, 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/except so 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
  1. Why check analyzerstatus() at startup while learning?

    Show answer

    To confirm orders go to the sandbox, not the live market.

  2. 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#

ToolTrading use
ListWatchlists; index from 0, [-1] is the latest
DictEvery SDK reply; nested reads like resp["data"]["ltp"]
f-stringf"{sym:10s} {ltp:>10,.2f}" for aligned output
for / if / defScale one check to many symbols, branch on data, avoid repetition
try / exceptKeep a bot alive through errors
Comprehension[b - a for a, b in zip(c, c[1:])] day-over-day changes
P&L = (exit − entry) × qty (reverse for shorts)long 1300 → 1345 × 50 = +₹2,250short 1300 → 1280 × 50 = +₹1,000SBIN 750 @ 812.4, LTP 818 → +₹4,200
Check yourself 2 questions
  1. How do you read the LTP from a quotes reply?

    Show answer

    resp["data"]["ltp"].

  2. 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#

InstrumentFormatExample
EquityBase nameRELIANCE
FutureBase + DDMMMYY + FUTNIFTY30JUN26FUT
OptionBase + DDMMMYY + strike + CE/PENIFTY30JUN2624000CE
Commodity futureSame as futuresGOLDM03JUL26FUT
Exchange codeHolds
NSE / BSEStocks
NFO / BFOFutures and options
MCXCommodities, trading into the evening
NSE_INDEXIndices (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
  1. Format a NIFTY 24,000 call expiring 30 June 2026.

    Show answer

    NIFTY30JUN2624000CE.

  2. 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
  1. Which call returns a symbol's lot size and tick size?

    Show answer

    client.symbol(...).

  2. 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#

CallReturnsUse
quotes(symbol, exchange)["data"]ltp, open, high, low, prev_close, bid, ask, volume, oiOne snapshot
multiquotes(symbols=[{...}, ...])["results"]Per item: symbol, exchange, dataMany 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
change % = (ltp − prev_close) / prev_close × 100spread = best ask − best bid (GOLDM: 22 points ≈ 0.015%)buy pressure % = buy qty / (buy + sell) × 100range position % = (ltp − low) / (high − low) × 100
  • 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
  1. When should you switch from quotes to multiquotes?

    Show answer

    Beyond 2–3 symbols: one request for many.

  2. 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. oi is 0 for stocks.
  • source="db" reads OpenAlgo's local store instead of the broker; wrap it in try/except. Build dates from datetime so scripts never go stale.
Check yourself 2 questions
  1. What does client.history() return?

    Show answer

    A pandas DataFrame indexed by timestamp.

  2. 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
  1. Which aggregation does volume use when resampling?

    Show answer

    Sum.

  2. 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); check shape, ndim, size, dtype (prices are float64).
  • Indexing: a[-1] latest; a[1:4] is three items; a[-5:] last five; 2D p[:, -1] last column.
  • Vectorise: closes * 1.05, closes * qty: no Python loops over prices.
  • Aggregate: mean, max, min, std, median, sum, cumsum; axis=1 across rows, axis=0 down 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
  1. Does np.arange(1, 6) include 6?

    Show answer

    No.

  2. 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#

TaskIdiomWatch out
Pick a columndf["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 growthr = close.pct_change(); (1 + r).cumprod() * 100000First return is NaN
Drawdownclose / close.cummax() - 1; its minimum is max drawdownThe core risk number
Group and combinegroupby(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 × √252A "best weekday" from a few months is noise

Check .shape and .head() on every new download before doing any maths.

Check yourself 2 questions
  1. df["close"] versus df[["close"]]?

    Show answer

    A Series versus a one-column DataFrame.

  2. 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 with plot, bar, hist, scatter, fill_between, axhline; finish with plt.savefig(path, dpi=110, bbox_inches="tight") (headless: no window appears).
  • No weekend gaps: plot against range(len(df)) and label every Nth tick with df.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
  1. How do you remove weekend gaps on a price chart?

    Show answer

    Plot against range(len(df)) and label ticks with dates.

  2. 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_hline for 70/30.
  • Set row= and col= on every trace. write_image needs kaleido and loses interactivity.
Check yourself 2 questions
  1. Which Plotly object draws candles?

    Show answer

    go.Candlestick.

  2. 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 (not python); it opens at localhost: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); widgets text_input, selectbox, slider. A watchlist board is one multiquotes call; a scanner is a loop of history + ta.rsi.
Check yourself 2 questions
  1. What TTL suits quotes versus daily history?

    Show answer

    Seconds for quotes, hours for daily history.

  2. 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#

ReturnsFunctionsRead the latest with
pandas Seriessma, 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 Seriesmacd (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 arraycrossover, 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
  1. What does ta.macd return?

    Show answer

    A tuple of three Series: MACD, signal, histogram.

  2. 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#

CallRead
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
  1. Supertrend direction −1 means what in openalgo.ta?

    Show answer

    Uptrend.

  2. 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#

CallZones
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
  1. RSI zones?

    Show answer

    Above 70 overbought, below 30 oversold, 50 as the bull/bear line.

  2. 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#

CallUse
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
  1. A 2-ATR stop formula?

    Show answer

    Price − 2 × ATR.

  2. 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#

CallRead
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
  1. What do you read on OBV?

    Show answer

    Slope and divergences, not the level.

  2. 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#

CallRead
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, tsiUnbounded: 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
  1. CHOP reads 65. Which tools?

    Show answer

    Range tools: it's choppy.

  2. 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#

CallTells you
linreg, lrslope(close, 20), tsfRegression 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, medianSwing 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
  1. A beta of 1 means what?

    Show answer

    The stock tracks the index.

  2. 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#

CallDoes
crossover(a, b) / crossunderTrue only on the bar of the cross
highest(x, n) / lowestRolling 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) / fallingHigher or lower than n bars ago
  • Combine arrays with &, |, ~ and parentheses, never and/or.
  • highest(high, 20)[-1] already includes today, so a breakout test against it can never fire. Compare with [-2].
Check yourself 2 questions
  1. What does exrem do?

    Show answer

    Drops repeat signals until the opposite side fires, so buys and sells alternate.

  2. 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#

  1. Fetch history.
  2. Compute indicators.
  3. Write raw conditions: (close > ema50) & (rsi > 50).
  4. Find turning points with crossover / crossunder.
  5. De-duplicate with exrem so buys and sells alternate.
  6. Shift one bar: .shift(1).
  7. Hand entries and exits (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
  1. Why shift signals one bar?

    Show answer

    To avoid look-ahead: you can act only after the bar that created the signal.

  2. 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
  1. Why wrap ta outputs in pd.Series with the close index?

    Show answer

    So signals align with dates for shifting and backtesting.

  2. 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
  1. How do you fix look-ahead for a breakout?

    Show answer

    Compare with the previous bar's level and shift the signal one bar.

  2. 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
  1. Why wrap each symbol's fetch in try/except?

    Show answer

    One bad symbol must not kill the whole scan.

  2. 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#

StrategyRulesCourse run
Golden crossEnter on 50-SMA crossing above 200-SMA, exit on the death cross; trade only in a bullish regimeNeeds ≈ 400 calendar days of data or it silently does nothing; RELIANCE regime was bearish (SMA50 1,347 vs SMA200 1,421)
EMA 20/50 crossoverEnter on the 20 crossing above the 50, exit on the reverseICICIBANK −15.5% vs buy-and-hold −7.8%
Momentum rotationRank 12 NSE stocks by 60-bar return, hold the top 3, re-rank monthlyLeaders LT +24.8%, AXISBANK +16.0%; laggard INFY −16.4%
Donchian 20 breakoutEnter above the prior bar's 20-day high, exit below the prior 20-day lowLT −3.8% vs buy-and-hold +15.8%
position = flip(buy, sell) · strat = pct_change × position.shift(1) · curve = (1 + strat).cumprod()

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
  1. Why can a golden-cross strategy silently do nothing?

    Show answer

    It needs about 400 calendar days of data for the 200-day average.

  2. 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#

StrategyRules
Opening range breakoutRange = 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 reversionBuy 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-minuteCross up / cross down; wrap the arrays in Series
Time exitNo 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 with between_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
  1. Opening range in the course?

    Show answer

    The 9:15–9:29 high and low; enter on a later close beyond it.

  2. 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#

spread = A / B or A − β·B (β from np.polyfit(B, A, 1))z = (spread − 30-day mean) / 30-day stdz > +2 → sell A, buy B · z < −2 → buy A, sell Bexit when |z| < 0.5 · trade only if return corr ≥ ≈ 0.6
  • 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
  1. z above +2: which legs?

    Show answer

    Sell A, buy B.

  2. 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#

ToolRule
Cross-sectional momentumRank by 60-day return, hold the top 3; skipping the latest week ("12-1") is a refinement
ATR breakoutClose > previous close + 1 × ATR (1.5 × on GOLDM); shift inputs a bar
Bollinger squeezeBandwidth in the bottom 20% of its 60-day range: timing, not direction
Regime filterLong only when close > 200-day SMA
Volatility targetingSize = 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
  1. What does '12-1' momentum skip?

    Show answer

    The most recent period (the latest week or month).

  2. 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 weekWed +0.189%, Tue −0.064%; ≈ 120 samples each
MonthApr +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
  1. Was the turn-of-month effect supported?

    Show answer

    No: slightly negative versus positive otherwise.

  2. 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#

CallReturns / 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 with strftime("%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
  1. What does optionsymbol resolve?

    Show answer

    Option symbols from offsets like ATM, ITMn or OTMn.

  2. 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#

FieldValues
actionBUY / SELL
productCNC delivery · MIS intraday, auto squared off · NRML F&O carried overnight
price_typeMARKET: 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
  1. Which product is auto squared off intraday?

    Show answer

    MIS.

  2. 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#

CallDoes
placeorderOne 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
  1. placesmartorder with position_size=0 does what?

    Show answer

    Flattens the position.

  2. 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?#

You know what you want to trade
1Do you want to reach a target position, not add to one?
yes
placesmartorderposition_size is the absolute target; 0 flattens
no
2Several symbols or option legs at once?
yes
basketorder or optionsmultiorderthen check every leg's status
no
3Is the quantity above the exchange freeze limit?
yes
splitorderchild orders of splitsize each
no
placeorderwith the right price_type and product
Check yourself 2 questions
  1. You want to reach exactly 100 shares regardless of what you hold. Which call?

    Show answer

    placesmartorder with position_size=100.

  2. 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#

Calldata shapeUseful fields
orderbook()Dict: orders list + statisticsorder_status; totals of completed, open, rejected
tradebook()List of fillsaction, symbol, average_price
positionbook()Listsymbol, quantity, ltp, pnl; open = quantity != 0
funds()Dictavailablecash, 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
  1. How do you find open positions in positionbook?

    Show answer

    Rows with quantity not equal to 0.

  2. 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
  1. Why use signal.shift(1) as the position?

    Show answer

    Today you hold what yesterday's signal decided.

  2. 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
  1. Fees and slippage used in the course example?

    Show answer

    0.1% fees and 0.05% slippage.

  2. 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#

MetricFormulaReadRELIANCE run
Total returnfinal ÷ initial − 1Ignores time: compare equal-length tests only−7.24%
CAGR(1+r).prod() ** (252/n) − 1The fair yardstick across lengths−9.57%
Sharpemean ÷ std of daily returns × √252< 0 losing · ≈ 1 good · 2 excellent · 3+ suspicious−0.66
SortinoLike Sharpe, downside volatility onlyUsually a bit above Sharpe−0.88
Max drawdownmin of equity ÷ running peak − 1A 50% loss needs +100% to recover−13.8%
CalmarCAGR ÷ |max drawdown|Return per unit of worst pain−0.69
Win rateWinning trades ÷ tradesMeaningless alone25% of 4
Profit factorGross profit ÷ gross lossMust exceed 10.32
Benchmark edgeStrategy − NIFTY buy-and-holdThe 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
  1. Why prefer CAGR to total return when comparing tests?

    Show answer

    Total return ignores time; CAGR is fair across lengths.

  2. 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 MultiIndex of (fast, slow), one from_signals call, 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
  1. Why prefer a plateau to a peak?

    Show answer

    Neighbouring parameters also work, so it's less likely to be luck.

  2. 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#

  1. Split by time, never shuffle: first ≈ 70% in-sample, last ≈ 30% out-of-sample.
  2. Tune on in-sample only; pick the best Sharpe.
  3. Run that one winner on the unseen slice.
  4. Roll it: tune 250 bars, test the next 100, slide by 100, repeat; log picks and results.
  5. 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
  1. Should you shuffle data before splitting?

    Show answer

    Never; split by time.

  2. 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?#

A backtest that looks promising
1Are signals shifted one bar so trades use only past data?
no
Fix look-ahead firstshift(1), and compare breakouts with the prior bar
yes
2Are realistic fees and slippage included?
no
Add realistic coststhey often flip the winner
yes
3Does it beat buy-and-hold or NIFTY on CAGR and drawdown?
no
Drop it or rethinkcomplexity must earn its keep
yes
4Does it hold out of sample, with stable parameters and enough trades?
no
Treat it as overfita lucky peak, not an edge
yes
Paper trade in analyze modethen go small, with a human watching

Main card on honest backtesting: Quant trading → Also in this sheet · Technical · Quant trading · AmiBroker AFL.

Check yourself 2 questions
  1. First check on any promising backtest?

    Show answer

    Are signals shifted one bar so trades use only past data?

  2. 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 setAccuracy
Naive baseline54.4%
Logistic regression47.0%
Random forest47.7%
Neural net49.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
  1. What's the bar a classifier must beat?

    Show answer

    The base rate: always guessing the majority class.

  2. 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#

  1. Fetch daily history.
  2. Engineer features and the label.
  3. Train, then predict the latest row.
  4. Act: BUY 1 (MARKET, CNC) on an up signal; placesmartorder(position_size=0) to flatten on a down signal.
  5. Alert via Telegram inside try/except so a missing link can't crash it.
  6. 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
  1. How does the bot exit on a down signal?

    Show answer

    placesmartorder with position_size=0.

  2. 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 dec
Check yourself 2 questions
  1. Should orders go through the WebSocket?

    Show answer

    No. Stream to watch, REST to act.

  2. 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 feed ws://127.0.0.1:8765, production wss://…/ws via OPENALGO_WS_URL.
  • Instruments: [{"exchange": "NSE", "symbol": "RELIANCE"}]; callback def cb(message) reads message["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.
entry 6000 · stop 5970 · target 6060 → risk : reward 1 : 2trailing: stop = max(stop, high_since_entry − 25)
Check yourself 2 questions
  1. Which streaming mode is lightest?

    Show answer

    LTP.

  2. 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#

risk budget = capital × 1%qty = floor(risk budget ÷ (entry − stop)) round DOWN, guard zero distanceATR stop = entry − 2 × ATR(14) → qty = budget ÷ (2 × ATR)F&O: units = (qty // lot_size) × lot_size whole lots onlyheat = Σ qty × (entry − stop) over open trades ≤ 6% of capital
  • 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 from quotes(); wrap it all in one position_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
  1. How do you round F&O quantity?

    Show answer

    Down to whole lots: (qty // lot_size) × lot_size.

  2. 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 typeProductMain charges on a round tripWrite down
Intraday equityMISBrokerage both legs, STT 0.025% on the sell side, exchange and SEBI fees, stamp duty on the buy, GST on brokerage and feesCost in basis points of turnover
Positional or swing equityCNC (delivery)STT 0.1% on both buy and sell, stamp duty, DP charge per scrip sold, usually low or zero brokerageCost per trade plus the DP charge
Index futuresNRML or MISBrokerage both legs, STT 0.05% on the sell side, exchange fees, stamp duty, GSTCost per lot round trip
Option buyingNRML or MISFlat 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 valueCost as a share of the premium paid
Option sellingNRMLSame charges, plus the margin blocked (and any pledging haircut) as the real capital costCost 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
  1. What STT applies to intraday equity, and on which side?

    Show answer

    0.025% on the sell side.

  2. 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#

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. Expect market-order protection: brokers may convert market orders to protected (limit-capped) orders, so handle partial fills.
Never publish your server address, keys or broker domain in notes, code or screenshots; keep them in a local, private config.
Check yourself 2 questions
  1. What happens to API orders from a non-whitelisted IP?

    Show answer

    They are rejected.

  2. 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#

StageRun it howMove on when
1. Analyze modeOpenAlgo's simulated orders, live data, full bot loopTwo weeks with no unhandled errors, every order path exercised
2. ShadowBot logs the orders it would place; you compare with what the market didSimulated fills and costs are close to the backtest's assumptions
3. Smallest sizeOne lot or the smallest quantity, real money, you watchingLive P&L per trade is within the backtest's expected range after real costs
4. Planned sizeStep up in stages, not one jumpDrawdown 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
  1. When should the kill switch be defined and tested?

    Show answer

    Defined before the first real-money stage, tested in analyze mode.

  2. 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
  1. What must match before the open?

    Show answer

    The bot's open positions and the broker's positions (plus server IP, funds and margin).

  2. 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#

  1. Keys live in .env, never in code or Git.
  2. Every call checks status and survives errors.
  3. Signals are shifted one bar; breakouts use the prior bar's level.
  4. The backtest has realistic fees and slippage and beats the benchmark.
  5. It holds out of sample with stable parameters and enough trades.
  6. Size comes from rupee risk, rounded down to whole lots; total heat is capped.
  7. Intraday code stops entries before the MIS cutoff and forces flat.
  8. Multi-leg orders check every leg's status.
  9. Weeks of analyze-mode running, logs and alerts, then small live size with a human watching.
Check yourself 2 questions
  1. Where must keys live before going live?

    Show answer

    In .env, never in code or Git.

  2. 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#

resp["data"] · resp["results"] (batch)r = close.pct_change()equity = (1 + pos.shift(1) * r).cumprod()drawdown = equity / equity.cummax() − 1OHLCV resample: first, max, min, last, sumsignal = pd.Series(ta.crossover(f, s), index=df.index)breakout: close[-1] > highest(high, n)[-2]annual vol = daily std × √252Sharpe = mean / std × √252expiry for orders: strftime("%d%b%y").upper()
Check yourself 2 questions
  1. Annual volatility from daily returns?

    Show answer

    Daily std × √252.

  2. 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.

WhatCurrent valueAs of
NIFTY lot size65 (was 75)from the Jan 2026 expiries · source
Index option expiry dayNSE: Tuesday (weekly NIFTY, monthly last Tuesday) · BSE: Thursdaysince Sep 2025 · source
Retail algo frameworkMandatory from 1 Apr 2026: whitelisted static IP, daily 2FA, algo ID for strategies at 10+ orders per second per segmentSEBI circular 4 Feb 2025, deadline 1 Apr 2026 · source
No cards match. Try fewer or different words, or press Esc to clear.