CPR + AI + ALGO

CPR Algo Trading: How to Use Daily and Weekly CPR with AI for Nifty 50 and Commodity Trading

A practical guide for Trading Direction students and small traders: turn Daily CPR and Weekly CPR into clear rules, let AI and an API handle the repetitive work, and keep risk under your control.

AH

By Anil Hanegave, Founder of Trading Direction. Professional trader, investor and trading educator with 9+ years of market experience, a published trading author, and 21,000+ students trained.

Quick Answer

CPR algo trading means converting your Central Pivot Range rules into code or a no-code flow so a system can calculate levels, check conditions and place orders through a broker API. Use Weekly CPR for the bigger directional bias and Daily CPR for entries, stop loss and targets. There is no single best indicator for algo trading, but CPR for levels, VWAP for intraday bias and ATR for stop loss and position size make a clean, testable combination.

Definition

CPR (Central Pivot Range) is a price zone built from the previous period's high, low and close, made of the Pivot, Top Central (TC) and Bottom Central (BC). Algo trading is placing trades automatically using pre-defined rules instead of manual clicks.

Why CPR suits automation

A computer can only follow rules that are exact. Many indicators need judgement, like "the trend looks strong" or "this candle looks bullish". CPR does not. The levels come from a fixed formula, the width is a number, and the position of price relative to the range is a yes or no question.

That is why students who already understand Narrow CPR and CPR-based price action have a real advantage when they move towards automation. You are not building a strategy from scratch. You are writing down, in precise language, what you already do on the chart.

AI helps with the rest: calculating levels every day, scanning many stocks, writing the first draft of code, running tests and reviewing your trades. It does not replace your rules or your risk control.

Daily CPR and Weekly CPR: formula and code

Daily CPR uses the previous day's high, low and close. Weekly CPR uses the previous week's high, low and close. The formula is identical.

  • Pivot (P) = (High + Low + Close) / 3
  • Bottom Central (BC) = (High + Low) / 2
  • Top Central (TC) = (2 x Pivot) - BC
  • CPR width % = (Top of range - Bottom of range) / Pivot x 100

When the close is below the midpoint of the day's range, TC can come out lower than BC. Algo code should always take the higher of the two as the top and the lower as the bottom, so the logic never breaks.

Here is a small calculation function in Python that any algo or AI assistant can build on. It is for learning, not a ready-to-trade system.

def cpr(high, low, close): pivot = (high + low + close) / 3 bc = (high + low) / 2 tc = (2 * pivot) - bc top, bottom = max(tc, bc), min(tc, bc) width_pct = (top - bottom) / pivot * 100 return {"pivot": pivot, "top": top, "bottom": bottom, "width_pct": width_pct} # Daily CPR -> pass previous day's high, low, close # Weekly CPR -> pass previous week's high, low, close

How to combine Weekly CPR and Daily CPR

Use Weekly CPR to decide which side you are allowed to trade, and Daily CPR to decide when to enter. This keeps an automated system from fighting the larger move.

ConditionMeaningWhat the system can do
Price above Weekly CPRBigger-picture bias is bullishAllow long setups only
Price below Weekly CPRBigger-picture bias is bearishAllow short setups only
Price inside Weekly CPRNo clear directionStay out or reduce size
Daily CPR narrowMarket may be preparing for a larger moveAllow breakout-type entries
Daily CPR wideRange-bound day is more likelySkip breakouts, or trade only with a separate tested range rule
Daily CPR inside Weekly CPRLevels overlap, confluence zoneTreat the zone as important support or resistance, wait for a clean break

In code, each row of this table becomes one "if" condition. That is the whole idea of CPR algo trading: a chart habit becomes a rule the system can check in milliseconds.

Nifty 50 example: a rule set you can test

The numbers below are hypothetical, used only to show the calculation. They are not real market levels or a trade recommendation.

ItemPrevious day (Daily CPR)Previous week (Weekly CPR)
High / Low / Close25,200 / 24,900 / 25,10025,400 / 24,700 / 25,150
Pivot25,066.6725,083.33
BC25,050.0025,050.00
TC25,083.3325,116.67
Width33.33 points (about 0.13%)66.67 points (about 0.27%)

Here the Daily CPR sits inside the Weekly CPR, and the Daily CPR is narrow. A discretionary trader would say: "important zone, watch for a breakout." An algo needs that converted into exact rules.

A sample rule set for Nifty 50 (for testing, not advice)

  1. Bias filter: If Nifty trades above Weekly TC, allow longs only. Below Weekly BC, allow shorts only. Inside Weekly CPR, no trade.
  2. Setup filter: Daily CPR width must be below your tested narrow threshold (find it by backtesting, not by guessing).
  3. Entry: A 15-minute candle closes above Daily TC (long) or below Daily BC (short), with price on the correct side of VWAP.
  4. Stop loss: Opposite side of the Daily CPR, or an ATR-based stop, whichever you have tested as better.
  5. Target: Nearest pivot resistance or support level, or a fixed risk-reward such as 1:2.
  6. Time rule: Close all trades before the end of the session.
  7. Daily limits: Maximum number of trades and a maximum daily loss, after which the system stops.

Position sizing: Quantity depends on the stop distance and the lot size, so check the current Nifty lot size on the NSE contract specifications. Risk per lot = stop loss in points x lot size. If one lot already risks more than your per-trade limit (for example 1% of capital), the setup does not fit your account size, and a smaller or defined-risk structure is the safer route.

Screening Nifty 50 stocks with CPR

Scanning all 50 stocks for narrow Daily CPR and a clear Weekly CPR bias is boring manual work. It is ideal work for automation. A script can pull previous data, run the cpr() function for each stock, rank them by width, and give you a short list before the market opens. You still do the final check on the chart.

Commodity example: MCX Crude Oil

Commodities need one extra decision that many beginners miss: what counts as a "day"? MCX crude oil trades into the late evening, so you must fix the session window you use for the previous high, low and close, and keep it the same in every backtest and in live trading.

Hypothetical example for the calculation only:

ItemPrevious session (Daily CPR)
High / Low / Close6,020 / 5,940 / 5,990
Pivot5,983.33
BC / TC5,980.00 / 5,986.67
Width6.67 points (about 0.11%), a narrow CPR

The same logic applies: Weekly CPR for bias, Daily CPR for the trigger, a stop below or above the range, and a target from the next pivot level. But commodities behave differently from Nifty in three ways that your rules should respect.

  • Event risk is in the evening. Weekly crude inventory data and US central bank decisions land during Indian evening hours, and price can jump. A rule that says "no new entry for a fixed window around major events" protects a small account.
  • Lot size and margin differ. Check the contract specification, and consider whether a mini contract lets you keep risk per trade within your limit.
  • Gold, silver and natural gas each have their own volatility. Never copy CPR width thresholds from Nifty. Backtest each instrument separately.

Best indicator for algo trading

There is no single best indicator for algo trading. A good algo uses one indicator for each job: levels, direction, volatility and confirmation. Stacking five indicators that all measure trend just makes the system look complicated without adding information.

IndicatorJob in an algoHow to use it with CPRWatch out for
CPR (Daily and Weekly)Key levels and biasBias from Weekly CPR, entry zone from Daily CPRNeeds a fixed session definition, especially in commodities
VWAPIntraday fair value and directionTake longs only above VWAP, shorts only belowResets every day, so it is not useful for swing rules
ATRVolatility, stop loss and position sizeSet stop distance and skip trades when the stop is too wide for your riskNot a direction signal
VolumeConfirmation of a breakoutRequire higher volume on the breakout candleVolume data quality differs by instrument
ADXTrend strength filterSkip breakouts when trend strength is very weakLags, so it can miss the start of a move
RSIMomentum contextUse as a filter, not as a standalone buy or sell triggerCan stay overbought or oversold for long in a trend

My suggestion for a first system: CPR for levels, VWAP for bias, ATR for risk. Three tools, three clear jobs, easy to backtest, easy to debug. Add volume or ADX only if testing proves they improve the result.

How AI helps small traders automate

AI helps a small trader by doing the repetitive, error-prone work: calculating levels, scanning instruments, drafting code, testing rules and reviewing trades. It does not give you an edge by itself. The edge still comes from your rules and your risk control.

MarketData Daily andWeekly CPR AI Scanand Filter Your Rulesand Risk Order viaBroker API Journaland Review You own the rules and the risk. AI and the API do the repetitive work.
A simple CPR automation pipeline for a small trader.

Where AI is genuinely useful

  • Turning rules into code. Describe your CPR rules in plain English and an AI assistant can draft the first version of the script. You then read it line by line and test it. Never run code you do not understand with real money.
  • Daily level calculation and scanning. Calculate Daily and Weekly CPR for Nifty 50 stocks, index and commodities every morning and rank by width and bias.
  • Backtesting and parameter checks. Test how your narrow CPR threshold behaves across different months and market conditions, and look at drawdown, not just profit.
  • Journal analysis. Feed in your trade log and let AI find patterns: which time, which CPR width, which day loses most.
  • Alerts. Get a message when price approaches a Weekly CPR level instead of watching the screen all day.

Where AI is not enough

AI can write code with mistakes, invent logic that sounds right, and overfit a backtest to past data. It also cannot feel the loss of a bad week. Test every system in paper or very small size first, and keep a manual kill switch.

Zerodha API and AlgoBaba: two ways to automate

A small trader usually automates in one of two ways: writing code against a broker API, or using a no-code platform. Both send orders through your broker account. Here is how they compare, using Zerodha's API and AlgoBaba as examples.

Zerodha API (Kite Connect)No-code platform such as AlgoBaba
ApproachYou write or generate the code yourselfYou set rules through a visual or template-based interface
Best forTraders comfortable with basic Python, or willing to learn with AI helpTraders who want automation without coding
FlexibilityHigh: custom CPR calculation, scanners, filtersDepends on the options the platform offers
Typical useFetch data, compute Daily and Weekly CPR, place and manage ordersApply a rule set and let the platform place orders in your linked broker account
Main riskBugs in your own codeLimits of the platform and its broker support

Before you choose either, confirm the current pricing, features, supported segments and broker links directly with Zerodha and with the platform. These details change, and the information here is general education, not a product review.

The Indian compliance checklist

SEBI's retail algo framework changes how API trading works. The exact details are set by your broker and the exchange, and can be updated, so read your broker's latest notice. In general, expect the following.

  1. Broker-approved API access only. Automated orders should go through your broker's official API or an approved platform.
  2. Static IP. Brokers generally require a registered static IP for API orders. A normal home connection that changes IP will not work.
  3. Authentication and daily login. Expect OAuth, two-factor authentication and API sessions that end daily.
  4. Order-rate threshold. Most small retail strategies stay far below the threshold where separate registration is needed, but check your broker's rule.
  5. Kill switch. Keep a way to stop the system instantly, both in your code and through your broker.
  6. Be careful with "guaranteed profit" algos. Anyone selling fixed returns from an algo is a red flag.

If you want to build your CPR foundation before automating, start with the structured CPR Brahmastra Webinar. A system automates your understanding, so the understanding must come first.

Risk rules and when not to trade

Automation makes good rules faster and bad rules faster too. Build the no-trade rules into the system, because the system will not hesitate the way you would.

SituationSuggested system rule
Price inside Weekly CPRNo new trade
Daily CPR very wideSkip breakout entries
Major event day (budget, policy decisions, big global data)Pause or reduce size
Large gap at the openWait for the first candles to settle before any entry
Daily loss limit reachedStop all trading for the day
Data feed or API errorStop and alert you, never retry blindly
Stop too wide for your risk per tradeSkip the trade

More on risk, position sizing and CPR on the Trading Direction blog.

Common mistakes

Mistake 1: Automating before the manual edge is proven

Fix: Trade the rules manually in small size for a few weeks, and keep a journal. Automate only what has been tested.

Mistake 2: Copying thresholds across markets

Fix: A narrow CPR on Nifty is not narrow on crude oil or a mid-cap stock. Test each instrument on its own.

Mistake 3: Overfitting the backtest

Fix: If you tuned ten parameters to get a beautiful curve, it probably will not repeat. Keep rules simple and test on data the system has never seen.

Mistake 4: Ignoring costs

Fix: Include brokerage, taxes and slippage in every backtest. A strategy that trades often can look profitable on paper and lose after costs.

Mistake 5: Trusting AI-written code blindly

Fix: Read it, test it with paper or minimum size, and add limits for maximum orders, maximum loss and trading hours.

FAQ

Can CPR be used for algo trading?

Yes. CPR is based on a fixed formula and gives exact levels and a measurable width, which makes it easy to convert into rules. Test the rules on historical data and trade them in small size first.

What is the best indicator for algo trading?

There is no single best one. A practical combination is CPR for levels, VWAP for intraday bias and ATR for stop loss and position size, with volume or ADX added only if testing shows a benefit.

How do Weekly CPR and Daily CPR work together?

Weekly CPR gives the broader bias: long only above it, short only below it, and no trade inside it. Daily CPR gives the entry zone, stop loss and target for the day.

How can a small trader start algo trading in India?

Write your CPR rules clearly, test them manually and in a backtest, then automate through your broker's official API, such as Zerodha's Kite Connect, or an approved no-code platform. Check your broker's current requirements for static IP and login first.

Is algo trading legal for retail traders in India?

Retail algo trading is allowed, but it is regulated. Orders must go through broker-approved APIs or platforms under SEBI and exchange rules. Confirm current requirements with your broker before you start.

Can AI predict the market or guarantee profits?

No. AI can speed up calculation, scanning, coding, testing and review, but it cannot remove market risk or guarantee results. Your rules and risk management decide the outcome.

Practical Takeaway

  • Use Weekly CPR for bias and Daily CPR for entries, stops and targets.
  • Start with three tools: CPR for levels, VWAP for bias, ATR for risk.
  • Define your session window clearly, especially for MCX commodities.
  • Let AI handle calculation, scanning, code drafts and journal review, but read and test everything yourself.
  • Automate through an official broker API or an approved platform, with static IP, daily limits and a kill switch.
  • Prove the rules manually first. Automation multiplies whatever you give it.

Get the CPR foundation right before you automate

Clear CPR rules are the base of any CPR algo. Learn the structured method step by step, or read the books for deeper practice.

CPR Brahmastra Webinar Trading Books
Educational disclaimer: This article is for education and general information only. It is not investment advice, a recommendation to buy or sell any security or commodity contract, or an endorsement of any broker, API or platform. All price levels in the examples are hypothetical. Trading in stocks, futures, options and commodities involves substantial risk of loss, and backtested results do not guarantee future performance. Regulations, broker requirements and platform features change, so verify current details with your broker and consult a SEBI-registered investment adviser before making financial decisions.

#CPRAlgoTrading #AlgoTradingIndia #DailyCPR #WeeklyCPR #Nifty50 #MCXCrudeOil #ZerodhaAPI #TradingAutomation #TradingDirection

WA Group 🏹 Live Webinar, Sun

Popular Blogs

Recent Posts

Narrow CPR Stocks for Today: How to Read the List and Actually Trade It Aug 14, 2026
Option Position Size Calculator: Sizing Trades by 3% and 4% Risk Aug 14, 2026
Stop-Loss Calculator: Options, Stock & Commodity Trading Aug 14, 2026
Reward to Risk Ratio Calculator: Know Your Numbers Before You Enter Aug 14, 2026

Explore More

📢 Share this Article