Skip to content

DoRmAmMu1997/My-Algo-Trading-Code

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

165 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

My-Algo-Trading-Code

This contains all the code I have written for the signal generation and the front test where I fetch data using Dhan API

Live track record

I have been running these strategies live (real broker orders) since May 2026. The day-by-day results are recorded here:

πŸ“ˆ Live results spreadsheet

The code

Although I own the code, the coding itself was done entirely using GPT-5.4-xhigh, GPT-5.5-xhigh and Claude Opus 4.7, Claude Opus 4.8 on Max effort. GPT wrote majority of the signal generators and the data fetch files. Claude wrote the big one - the multithreaded Front Test worker. I just did the reviews and the testing

What is included?

  • Data extractors which extract historical data for NIFTY/BANKNIFTY/FINNIFTY indices
  • The backtest files I used to backtest
  • The signal generators I created to generate signals
  • The main front test file which uses miltithreading to execute all strategies together
  • Live order execution to a real broker β€” selectable among Kotak Neo, Shoonya (Finvasia), and Flattrade Pi v2 β€” gated by a global kill-switch and per-strategy paper/live toggles (everything defaults to paper)
  • Live Telegram alerts: the front-test master file can post every entry/exit (option instrument, lot size, entry/exit price, and P&L) to a Telegram group/channel
  • An optional, opt-in LLM trading agent β€” the "SL Hunting AI Agent" β€” a Claude agent that trades a discretionary price-action method on NIFTY options; off by default, paper unless explicitly enabled, and fail-soft (see Recent additions)

Recent additions

  • Per-strategy "off" switch β€” <PREFIX>_VIRTUAL_TRADING. Every strategy now has a virtual (paper) toggle that defaults to true. Set it false to stop that strategy's worker thread from starting at all β€” so it does no paper trading (and, since the thread never runs, no live trading either). Unlike live trading there is no global master switch: the default is that everything runs, and you silence individual strategies. Lets you run just the strategies you want on a given day instead of the whole roster.
  • Quality gates & CI. A GitHub Actions workflow (.github/workflows/quality-and-security.yml) runs the full gate on every push/PR across Python 3.12 + 3.13: both test suites, compileall, ruff, mypy (scoped in pyproject.toml), and bandit. Config lives in pyproject.toml + requirements-dev.txt, with a .pre-commit-config.yaml for local checks. Install the dev tools with pip install -r requirements-dev.txt.
  • SL Hunting AI Agent β€” BankNIFTY mirror basket + newer knowledge (v3c–v3e). The agent now trades Intraday Hunter's multi-index style: every NIFTY entry is mirrored with an equal-lot BankNIFTY ATM leg (SL_HUNTING_BNF_MIRROR, default true). The two legs are tied for hard risk (stop/target, max-loss, 15:15 square-off close both) but the agent evaluates each leg's premise independently and can cut one alone via the EXIT exit_leg selector (NIFTY | BNF | BOTH). Entry stays NIFTY-only (the mirror copies it). Its knowledge also grew several distilled-from-video layers β€” a scoped gap-up opening-drive, a 2-week verbatim transcript sweep, and a live-day match against the agent's own journal (details in Signal Generators/SL Hunting AI Agent/README.md).
  • Optional LLM trading agent β€” the "SL Hunting AI Agent" (opt-in 27th worker). A Claude agent (via the claude-agent-sdk on your Claude subscription β€” no API key) trades the discretionary SL Hunting price-action method on NIFTY ATM options. Once per completed 1-min bar (the method's native timeframe) it reads the NIFTY chart (with BankNIFTY cross-confirmation) and β€” only on a confirmed setup at a real level β€” acts through the SAME tested enter_position/exit_position path as every other worker, with dynamic ~β‚Ή2,500 risk-per-trade position sizing (it does not pick lots). It stops opening new positions after noon (SL_HUNTING_NO_NEW_ENTRY_HOUR, default 12:00) β€” not a square-off: open positions, their stops/targets, and the 15:15 square-off are unaffected. It is off by default (SL_HUNTING_ENABLED), trades paper unless both LIVE_TRADING_ENABLED and SL_HUNTING_LIVE_TRADING are set, and is fail-soft β€” any agent/SDK error becomes a safe HOLD (never an exception into the trading loop), and its extra deps are lazily imported so a missing dep just disables this one worker. It can also learn from its own trades: a per-trade journal feeds an off-loop reflection coach that proposes lessons, which the operator human-gates into the prompt (paper-first, off by default). Needs pip install claude-agent-sdk pydantic and a one-time claude setup-token (keep ANTHROPIC_API_KEY UNSET so it bills your Claude plan, not per-token API). Full details β€” knowledge, tools, safety model, the learning loop β€” are in Signal Generators/SL Hunting AI Agent/README.md. This is the optional 27th worker.
  • CPR Algo 3 (multi-instrument) is now wired into the front test. A new CPRAlgo3StrategyWorker runs the "CPR basic setup" strategy, which watches THREE charts at once β€” the NIFTY spot plus a ~ITM CE and a ~ITM PE of the current-week expiry β€” and only fires when VWAP and the CPR band align across all three (RSI/ARSI on spot). The two ITM options are observation only: a signal still BUYS the ATM CE/PE of the next-next expiry through the same tested path as the other directional workers, so it shares CPR's risk knobs (tunable via CPR_ALGO3_* in .env, including CPR_ALGO3_ITM_OFFSET). It fetches the two option 1-min OHLC feeds on demand and drives its own spot target/stop exit. This brings the runner to 26 workers. (The standalone Algo 3 signal generator + its unit tests live under Signal Generators/CPR Strategy/.)
  • Code-quality pass. Added a requirements.txt; gave every Shoonya broker HTTP call a timeout (a hung call could otherwise stall a worker thread and the shared broker lock); removed hardcoded credentials from the vendored Shoonya client; routed the execution layer's status/errors through logging instead of print(); and ported the master test suite into the repo (test_nifty_multi_strategy_master.py β€” see Tests below).
  • Live broker execution is broker-selectable (Kotak Neo, Shoonya, or Flattrade). LIVE_BROKER picks KOTAK, SHOONYA, or FLATTRADE, and every real order goes through one generic execution_client. The global LIVE_TRADING_ENABLED kill-switch and each strategy's <PREFIX>_LIVE_TRADING flag must both be true; unknown broker names fail closed to paper. Each broker folder contains an execution client and a read-only diagnostic with an optional, typed-YES, round-trip test order. Flattrade uses its official Pi v2 browser-token flow, exact NFO index scrip master, documented request limits, market-order protection, and SingleOrdHist fill confirmation. Everything still defaults to paper. (Shoonya's legacy QuickAuth endpoint is being decommissioned by Finvasia.)
  • End-of-day P&L is now written to a Google Sheet. When all workers exit on a clean end of day, the master parses the run's log for each strategy's realised P&L and writes it into a tracker sheet β€” one row per strategy, one column per calendar day β€” overwriting today's cell and backfilling any blank earlier-this-month cells from the (append-mode) log. Auth is OAuth user-token via gspread; configure GSHEET_ID + an OAuth client in .env (see Setup). It's a safe no-op when unconfigured, so it never disturbs shutdown.
  • 13 TradingBot signal-generator ports added β€” the front test now runs 24 workers. Thirteen more ATM single-leg strategies were ported into Signal Generators/ (SMA Crossover, Bollinger Bands, Keltner Squeeze, Mean Reversion Z-Score, ML Ensemble, Multi-Timeframe, Opening Range Breakout, Parabolic SAR, RSI Divergence, RSI Reversal, Stochastic, Supertrend, Volatility Breakout), all sharing misc_strategy_common.py (TA-Lib-first indicator helpers). They're wired into the master via one shared factory as AtmSingleLegStrategyWorkers β€” the same family as Renko/Goldmine/CPR β€” and each is fully tunable from .env by its own prefix (e.g. SMA_CROSSOVER_*, KELTNER_SQUEEZE_*). This brings the runner to 24 workers (21 ATM single-leg + 2 Hedged Puts + 1 Delta-0.2). ML Ensemble needs scikit-learn.
  • CPR (Central Pivot Range) strategy is now live in the front test. It runs as an ATM single-leg worker (CPRStrategyWorker) alongside the other strategies: the master file feeds it 1-min OHLC, the CPR logic resamples to complete 5-min candles internally, and a LONG/SHORT signal buys the ATM CE/PE of the next-next expiry. Tunable via CPR_* knobs in the .env (lots, max-loss, poll, 09:25-15:15 window). (This brought the master file to nine workers at the time; see the latest addition at the top of this list for the current total.)
  • Telegram trade notifications. A queue-based TelegramMessageWorker posts a message to a Telegram group/channel on every entry and exit from any worker. Each alert shows the strategy, the exact option instrument(s), lot size, entry and exit price, and P&L (hedged spreads show both legs). It runs on its own thread so Telegram latency or downtime never blocks the trading loop, and it's a cheap no-op when disabled. See Setup below to switch it on.

Pro Tip

You might have to adjust the import addresses from which the files are to be imported because the files are in different directories in my local machine(fixed in the latest Claude commit)

Repository structure

.
β”œβ”€β”€ Nifty Multi Strategy Front Test - Master File.py   # multithreaded paper + live runner (26 strategies + 1 optional LLM agent)
β”œβ”€β”€ Data Extractors/                                   # 1m OHLC downloaders + shared helper
β”œβ”€β”€ My Backtest Files (For Reference)/                 # backtesting.py-based backtests
β”œβ”€β”€ Signal Generators/                                 # strategy / signal logic modules
└── Dependencies/                                      # shared config + live-execution layer
    β”œβ”€β”€ env.example                                    # copy to Dependencies/.env and fill in
    β”œβ”€β”€ dhan_token_setup.py                            # one-time DhanHQ OAuth token setup
    β”œβ”€β”€ Kotak API/                                     # kotak_execution.py + diagnose_kotak_symbol.py
    β”œβ”€β”€ Shoonya API/                                   # NorenApi.py + shoonya_execution.py + diagnose_shoonya_symbol.py
    └── Flattrade API/                                 # flattrade_execution.py + diagnose_flattrade_symbol.py

Each subfolder has its own Readme.md with the details.

Setup

  1. Python 3.10+ (I'm running 3.13).

  2. Install dependencies:

    pip install -r requirements.txt
    

    That covers the core (data fetch, backtests, runner). For live trading also install your broker's client β€” see the commented "Live trading (optional)" section in requirements.txt: Kotak Neo (neo_api_client) and/or Shoonya (pyotp + websocket-client; the NorenApi client itself is vendored). Flattrade uses the core requests and pandas dependencies, so it needs no extra SDK.

  3. Configure credentials. Copy Dependencies/env.example to Dependencies/.env and fill it in (.env is git-ignored). Set your Dhan credentials there, then run the one-time token setup:

    python "Dependencies/dhan_token_setup.py"
    

    It walks you through the DhanHQ OAuth login and writes a fresh DHAN_ACCESS_TOKEN back into .env. All tunable strategy parameters live in this same .env.

  4. (Optional) Turn on Telegram trade alerts by adding these to the master file's .env:

    TELEGRAM_ENABLED=true
    TELEGRAM_BOT_TOKEN=your_botfather_token
    TELEGRAM_CHAT_ID=@your_channel_or_-100xxxxxxxxxx
    

    Create the bot via @BotFather and add it to your group/channel as an admin. Leave TELEGRAM_ENABLED=false (the default) to run without alerts. The token stays in .env, which is git-ignored.

  5. (Optional) End-of-day P&L to Google Sheets. After all workers exit, the master writes each strategy's day-end P&L into a tracker sheet (one row per strategy, one column per day, with month backfill). Enable it by adding to the master's .env:

    GSHEET_ID=your_spreadsheet_id
    GSHEET_OAUTH_CLIENT_FILE=Dependencies/gsheet_oauth_client.json
    GSHEET_OAUTH_TOKEN_FILE=Dependencies/gsheet_oauth_token.json
    

    Auth is OAuth user-token via gspread: in Google Cloud enable the Sheets API, create an OAuth client of type Desktop app, download its JSON to GSHEET_OAUTH_CLIENT_FILE, and share the sheet with your Google account. The first run opens a browser once for consent and caches a token at GSHEET_OAUTH_TOKEN_FILE. The sheet needs one row per strategy in column A with exact labels (e.g. Renko Strategy, SMA Crossover Strategy, Stochastic Oscillator Strategy, Supertrend Strategy, …); unmatched strategies are skipped with a warning. Leave GSHEET_ID blank to disable (safe no-op).

  6. (Optional) Live broker execution. Everything is paper by default. To place REAL orders, set in Dependencies/.env:

    LIVE_TRADING_ENABLED=true        # global kill-switch (default false)
    LIVE_BROKER=KOTAK                # KOTAK, SHOONYA, or FLATTRADE
    RENKO_LIVE_TRADING=true          # flip the specific strategies you want live
    

    Then fill the selected broker's credential block. Flattrade needs FLATTRADE_CLIENT_ID, FLATTRADE_API_KEY, and FLATTRADE_API_SECRET; its optional FLATTRADE_ACCESS_TOKEN is validated when supplied, otherwise startup opens browser authorization and asks for the returned request_code. A strategy trades live only when LIVE_TRADING_ENABLED and its own <PREFIX>_LIVE_TRADING are both true; any order failure falls back to paper for that trade. Check connectivity first with the read-only diagnostics β€” they can place a confirmation-gated round-trip (buy + auto square-off) test order via --place-order:

    python "Dependencies/Kotak API/diagnose_kotak_symbol.py" CE 23950 --place-order
    python "Dependencies/Shoonya API/diagnose_shoonya_symbol.py" CE 23950 26JUN25 --place-order
    python "Dependencies/Flattrade API/diagnose_flattrade_symbol.py" CE 24150 14JUL26 --place-order
    

Command-line interface

algo.py is a single entry point for every script in this repo via short commands. It just launches the underlying scripts (so each one still works on its own), and any flag beyond the selector passes straight through. From the repo root:

Command What it does Example
fetch-data --index {nifty,banknifty,finnifty} Download 1-min OHLC for an index python algo.py fetch-data --index nifty --interval 5 --lookback 5y
backtest --strategy {renko,ema,heikin,cpr,profit-shooter,goldmine,money-machine} Backtest one strategy against a CSV python algo.py backtest --strategy renko --data "Backtest Outputs/nifty_renko_futures_5y_1min_data.csv"
run Start the front-test master (paper by default; live per .env) python algo.py run
setup-token One-time DhanHQ token setup (writes .env) python algo.py setup-token
diagnose --broker {kotak,shoonya,flattrade} Read-only broker/symbol check (add --place-order for a test order) python algo.py diagnose --broker flattrade CE 24150 14JUL26

Run python algo.py --help, or python algo.py <command> --help, for the details.

Typical workflow

  1. Pull historical data β€” e.g. python "Data Extractors/Nifty 1m 5Y Data Fetch Dhan.py". The CSV lands in Backtest Outputs/.
  2. Run a backtest against that CSV β€” e.g. python "My Backtest Files (For Reference)/Nifty Renko Strategy Backtest.py".
  3. Once a strategy looks good, run Nifty Multi Strategy Front Test - Master File.py for multi-strategy execution β€” paper by default, or live once you've configured a broker (Setup step 6).

(Or do all three with the unified CLI above: python algo.py fetch-data --index nifty β†’ python algo.py backtest --strategy renko --data ... β†’ python algo.py run.)

The Backtest Outputs/ folder is .gitignore-d, so generated CSVs/logs stay local.

Tests

The front-test master has a unittest suite β€” env toggles, broker paper/live routing and the fail-closed LIVE_BROKER switch, order fill-confirmation, and symbol resolution. Run it from the repo root:

python -m unittest test_nifty_multi_strategy_master

175 tests; broker/SDK-specific cases skip automatically when optional dependencies are absent, and all Flattrade HTTP/browser/order behaviour is mocked. (The CPR, Subhamoy, and SL Hunting AI Agent signal generators have their own tests under Signal Generators/.) CI runs the whole quality gate on every push/PR β€” see "Quality gates & CI" below.

Quality gates & CI

A GitHub Actions workflow (.github/workflows/quality-and-security.yml) runs on every push and pull request across Python 3.12 and 3.13. Locally, the same gate is:

pip install -r requirements-dev.txt          # ruff, mypy, bandit, pre-commit, pytest
python -m unittest test_nifty_multi_strategy_master
python -m pytest "Signal Generators" "Dependencies" -q
python -m compileall -q .
python -m ruff check .
python -m mypy

pyproject.toml holds the ruff + mypy config (mypy is scoped to the identifier-named modules β€” the spaced-name master file is covered by compileall + the unittest suite instead). .pre-commit-config.yaml wires the check-only hooks; install them once with pre-commit install.

License

Released under the MIT License β€” see LICENSE.

About

Python algorithmic trading suite: signal generators, backtests, and a multithreaded paper-trading runner for NIFTY/BANKNIFTY/FINNIFTY via the Dhan API. Also contains a Claude-based AI agent for SL hunting-based strategies

Topics

Resources

License

Stars

8 stars

Watchers

1 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages