Skip to content
Back to search

skill-algotrader

Quantitative trading skill for Indian equity markets with Zerodha integration. Generate trading bots, fetch live index data, and manage risk with Claude Code.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/javajack--skill-algotrader/badge.svg)](/listings/javajack--skill-algotrader)

HTML

<a href="/listings/javajack--skill-algotrader"><img src="/api/listings/javajack--skill-algotrader/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Quick Install (Recommended)

Install directly from the skills.sh directory:

npx skills add javajack/skill-algotrader

Manual Installation

Option 1: Clone to Claude Skills Directory

cd ~/.claude/skills
git clone https://github.com/javajack/skill-algotrader.git algotrader
cd algotrader
./start.sh wizard  # Start using the skill

Option 2: Custom Skills Path

export CLAUDE_SKILLS_PATH=~/work/skills
cd ~/work/skills
git clone https://github.com/javajack/skill-algotrader.git algotrader
cd algotrader
./start.sh wizard

Install Python Dependencies

After installation, set up the Python environment:

cd ~/.claude/skills/algotrader  # or your custom path
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt

# Or use the convenience script (auto-creates venv)
./start.sh wizard

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 565 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # AlgoTrader: Quantitative Trading Skill for Claude Code
  2. > **Comprehensive trading expert embodying real-world learnings from Indian equity markets**
  3. [![Python](https://img.shields.io/badge/Python-3.10+-blue.svg)](https://www.python.org/)
  4. [![Zerodha](https://img.shields.io/badge/Zerodha-Kite%20API-orange.svg)](https://kite.trade/)
  5. [![License](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
  6. [![Skills.sh](https://img.shields.io/badge/skills.sh-install-blue)](https://skills.sh/javajack/skill-algotrader)
  7. [![GitHub](https://img.shields.io/github/stars/javajack/skill-algotrader?style=social)](https://github.com/javajack/skill-algotrader)
  8. ## Overview
  9. AlgoTrader is a Claude Code skill that provides expert guidance for building, optimizing, and running quantitative trading systems on Indian stock markets. It embodies **1,780 lines of real-world learnings** from production trading, including:
  10. - ✅ **65%+ win rate** signal generation strategies
  11. - ✅ **28x performance optimizations** (Parquet caching, vectorization)
  12. - ✅ **Zero-regression code modifications** with automated testing
  13. - ✅ **Production failure prevention** (30+ gotchas documented)
  14. - ✅ **Backtest-live parity** validation
  15. - ✅ **Risk-adjusted capital compounding**
  16. ## Installation
  17. ### Quick Install (Recommended)
  18. Install directly from the skills.sh directory:
  19. ```bash
  20. npx skills add javajack/skill-algotrader
  21. ```
  22. ### Manual Installation
  23. #### Option 1: Clone to Claude Skills Directory
  24. ```bash
  25. cd ~/.claude/skills
  26. git clone https://github.com/javajack/skill-algotrader.git algotrader
  27. cd algotrader
  28. ./start.sh wizard # Start using the skill
  29. ```
  30. #### Option 2: Custom Skills Path
  31. ```bash
  32. export CLAUDE_SKILLS_PATH=~/work/skills
  33. cd ~/work/skills
  34. git clone https://github.com/javajack/skill-algotrader.git algotrader
  35. cd algotrader
  36. ./start.sh wizard
  37. ```
  38. ### Install Python Dependencies
  39. After installation, set up the Python environment:
  40. ```bash
  41. cd ~/.claude/skills/algotrader # or your custom path
  42. python3 -m venv venv
  43. source venv/bin/activate
  44. pip install -r requirements.txt
  45. # Or use the convenience script (auto-creates venv)
  46. ./start.sh wizard
  47. ```
  48. ## Features
  49. ### 🎯 Interactive Bot Generation Wizard
  50. Launch `/algotrader` without parameters to enter the wizard:
  51. ```bash
  52. $ /algotrader
  53. ╔══════════════════════════════════════════════════════════════╗
  54. ║ ALGOTRADER BOT GENERATION WIZARD ║
  55. ╚══════════════════════════════════════════════════════════════╝
  56. Scanning current directory for trading code...
  57. ✓ Found: backtest.py, signal_generator.py
  58. What would you like to do?
  59. 1. Generate new trading bot from scratch
  60. 2. Enhance existing code (fix issues, optimize)
  61. 3. Create universe JSON from live index data
  62. 4. Run backtest comparison
  63. 5. Analyze performance
  64. > 1
  65. Let's design your trading bot. I'll ask a few questions...
  66. ```
  67. The wizard will:
  68. - Scan your folder for existing trading code
  69. - Ask strategic questions (trade type, universe, capital, risk tolerance)
  70. - Generate a complete, working trading bot
  71. - Create universe JSON files with latest index constituents
  72. - Set up logging, analytics, and risk management
  73. ### 📊 Universe Fetcher (Live Index Data)
  74. Automatically fetches latest index constituents from NSE:
  75. ```python
  76. /algotrader universe
  77. Fetching live index data from NSE...
  78. ✓ Nifty 50: 50 stocks (updated: 2026-02-14)
  79. ✓ Nifty 100: 100 stocks
  80. ✓ Nifty Midcap 150: 150 stocks
  81. ✓ Nifty Smallcap 250: 250 stocks
  82. Created:
  83. └─ universe/
  84. ├─ nifty50.json (50 stocks, ₹500Cr+ mcap)
  85. ├─ nifty100.json (100 stocks)
  86. ├─ midcap150.json (150 stocks, ₹50-500Cr mcap)
  87. └─ smallcap250.json (250 stocks, ₹10-50Cr mcap)
  88. Each file includes:
  89. - Symbol, company name, ISIN
  90. - Market cap, sector
  91. - Liquidity metrics (avg volume, spread)
  92. - Last updated timestamp
  93. ```
  94. ### 🧠 16 Knowledge Domains
  95. 1. **Zerodha Integration** - Tick size rounding, position reconciliation, SL lifecycle
  96. 2. **Backtest-Live Parity** - Data caching, T vs T-1 alignment, VWAP reset
  97. 3. **Signal Generation** - Fortress signal (65% win rate), multi-factor confirmation
  98. 4. **Rebalancing Logic** - Weekly vs daily, transaction cost modeling
  99. 5. **Stock Universe Selection** - Liquidity filtering, momentum scoring
  100. 6. **Performance Optimization** - Parquet (28x), Polars vectorization (37x), API batching
  101. 7. **Indian Market Specifics** - Session timing, circuit breakers, T+1 settlement
  102. 8. **Failure Patterns** - 5 production issues + fixes (HINDALCO loop, naked positions)
  103. 9. **Indicators & Formulas** - RSI, MACD, ATR, ADX, VWAP, EMA (exact formulas + parameters)
  104. 10. **Multi-Timeframe Trading** - Intraday vs positional, MTF alignment
  105. 11. **Logging & Observability** - Structured logging, real-time monitoring
  106. 12. **Post-Trade Analytics** - P&L breakdown, Sharpe ratio, drawdown analysis
  107. 13. **Signal Attribution** - Track which indicator triggered, exhaustion detection
  108. 14. **Exit Strategies** - Time decay, trailing stops, partial exits
  109. 15. **Risk Management** - Kelly Criterion, portfolio heat, consecutive loss throttling
  110. 16. **Capital Compounding** - Market regime detection, bull market amplification
  111. ### ⚠️ 30+ Token-Burning Gotchas (NUANCES.md)
  112. Common mistakes that burn hours of debugging:
  113. ```markdown
  114. 🔥 CRITICAL: Tick Size Rounding
  115. Mistake: kite.place_order(price=1847.35, ...)
  116. Error: "Tick size for this script is 5.00"
  117. Fix: price = round(price / tick_size) * tick_size # 1847.35 → 1850.00
  118. Impact: 90% of order rejections are tick size errors
  119. 🔥 CRITICAL: VWAP Must Reset Daily
  120. Mistake: Cumulative VWAP across days
  121. Symptom: Backtest 65% win rate, live 40%
  122. Fix: Reset at market open (9:15)
  123. Impact: #1 cause of backtest-live parity violations
  124. ```
  125. See [NUANCES.md](NUANCES.md) for all 30+ gotchas.
  126. ## Configuration
  127. ### Configure Zerodha API Credentials
  128. For live trading, create a `.env` file in your bot directory:
  129. ```bash
  130. # Create .env file (never commit this!)
  131. cat > .env << EOF
  132. KITE_API_KEY=your_api_key
  133. KITE_API_SECRET=your_api_secret
  134. KITE_ACCESS_TOKEN=your_access_token
  135. EOF
  136. ```
  137. Get credentials from: https://kite.trade/
  138. **Note:** The `.env` file is automatically excluded from git via `.gitignore`. Never commit API credentials!
  139. ## Quick Start
  140. ### Generate Your First Trading Bot
  141. ```bash
  142. # Launch wizard
  143. /algotrader
  144. # Or directly in Claude Code chat
  145. > /algotrader wizard
  146. ```
  147. The wizard will ask:
  148. 1. **Trading Style:** Intraday, Swing (multi-day), Positional (multi-week)
  149. 2. **Universe:** Nifty 50 (largecap), Nifty Midcap 150, Custom
  150. 3. **Strategy:** Momentum, VWAP Pullback, Opening Range Breakout
  151. 4. **Capital:** Starting capital and risk per trade
  152. 5. **Risk Tolerance:** Conservative (0.5% risk), Balanced (1%), Aggressive (2%)
  153. Based on your answers, it generates:
  154. ```
  155. trading_bot/
  156. ├── config.json # Strategy parameters
  157. ├── main.py # Entry point
  158. ├── signal_generator.py # Signal logic
  159. ├── data_manager.py # Data fetching and caching
  160. ├── risk_manager.py # Position sizing, Kelly Criterion
  161. ├── zerodha_client.py # API integration
  162. └── universe/
  163. └── nifty50.json # Stock universe (fetched from NSE)
  164. ```
  165. ### Fetch Universe from Live Data
  166. ```bash
  167. /algotrader universe --indices nifty50,nifty100,midcap150
  168. # Creates JSON files with latest constituents
  169. # Includes liquidity filtering, market cap, sector
  170. ```
  171. ### Analyze Existing Code
  172. ```bash
  173. # Point to your existing trading code
  174. /algotrader check ./my_trading_bot.py
  175. # Output:
  176. ⚠️ Found 3 issues:
  177. 1. Tick size not rounded (line 45) - will cause order rejections
  178. 2. VWAP not reset daily (line 89) - backtest-live parity violation
  179. 3. No symbol cooldown (line 120) - risk of revenge trading
  180. Recommended fixes:
  181. 1. Add tick_size rounding: price = round_to_tick(price, symbol)
  182. 2. Reset VWAP at 9:15: if is_new_day(): vwap_state.reset()
  183. 3. Add 45min cooldown: if not can_trade_symbol(symbol): return None
  184. Apply fixes automatically? (y/n):
  185. ```
  186. ## Usage Examples
  187. ### Example 1: Fortress Signal Generation
  188. ```python
  189. from algotrader import generate_fortress_signal
  190. # Your OHLCV data with indicators
  191. df = load_data("RELIANCE", date="2026-02-14")
  192. signal = generate_fortress_signal(
  193. df=df,
  194. symbol="RELIANCE",
  195. config={
  196. 'rsi_long_min': 45,
  197. 'rsi_long_max': 65,
  198. 'adx_min': 25,
  199. 'volume_mult': 1.5
  200. }
  201. )
  202. if signal:
  203. print(f"🎯 LONG signal for {signal['symbol']}")
  204. print(f" Entry: ₹{signal['entry_price']}")
  205. print(f" Stop Loss: ₹{signal['stop_loss']}")
  206. print(f" Target: ₹{signal['target']}")
  207. print(f" Confidence: {signal['confidence']:.0%}")
  208. print(f" Reason: {signal['reason']}")
  209. ```
  210. ### Example 2: Backtest Comparison
  211. ```python
  212. from algotrader import compare_backtests
  213. # Compare backtest results with live trading
  214. comparison = compare_backtests(
  215. backtest_file="backtests/fortress_v2.parquet",
  216. live_file="backtests/live_results.parquet"
  217. )
  218. print(f"Win Rate: {comparison['backtest_winrate']:.1%} → {comparison['live_winrate']:.1%}")
  219. print(f"Delta: {comparison['winrate_delta']:.1%}")
  220. if comparison['parity_issues']:
  221. print("\n⚠️ Parity Issues:")
  222. for issue in comparison['parity_issues']:
  223. print(f" - {issue['description']}")
  224. print(f" Fix: {issue['recommended_fix']}")
  225. ```
  226. ### Example 3: Universe Fetcher (Programmatic)
  227. ```python
  228. from algotrader.universe import fetch_index_constituents, filter_universe
  229. # Fetch latest Nifty 50 from NSE
  230. nifty50 = fetch_index_constituents("NIFTY 50")
  231. print(f"✓ Fetched {len(nifty50)} stocks")
  232. # Apply liquidity filtering
  233. filtered = filter_universe(
  234. nifty50,
  235. min_volume=100_000, # Min daily volume
  236. max_spread_pct=0.3, # Max bid-ask spread
  237. min_atr_pct=0.15, # Min volatility
  238. max_atr_pct=2.5 # Max volatility
  239. )
  240. print(f"✓ After filtering: {len(filtered)} stocks")
  241. # Save to JSON
  242. save_universe(filtered, "universe/nifty50_filtered.json")
  243. ```
  244. ## Architecture
  245. ### Minimal Design Philosophy
  246. AlgoTrader follows these principles:
  247. 1. **Few files, high cohesion** - 7 files total, not 20+
  248. 2. **LLM-friendly comments** - Clear refactoring guidance
  249. 3. **Pure functions** - Testable, no hidden state
  250. 4. **Vectorized operations** - Polars, not loops
  251. 5. **Single source of truth** - KNOWLEDGE.md for all learnings
  252. ### File Structure
  253. ```
  254. algotrader/
  255. ├── skill.json # Skill manifest (Claude Code integration)
  256. ├── README.md # This file
  257. ├── KNOWLEDGE.md # All 16 domains (1,780 lines of learnings)
  258. ├── NUANCES.md # 30+ token-burning gotchas
  259. ├── algotrader.py # Main CLI + wizard (~800 lines)
  260. ├── requirements.txt # Python dependencies
  261. ├── templates/
  262. │ ├── minimal_intraday.py # Bare minimum intraday bot (50 lines)
  263. │ └── minimal_positional.py # Bare minimum positional bot (50 lines)
  264. └── examples/
  265. ├── full_system.py # Complete reference implementation (~300 lines)
  266. └── universe_fetcher.py # Fetch index constituents from NSE
  267. ```
  268. ## Knowledge Base
  269. ### KNOWLEDGE.md
  270. Comprehensive documentation of all 16 domains:
  271. - Exact code patterns that work in production
  272. - Numeric parameters from real testing (rsi_long_min=45, adx_min=25)
  273. - Before/After comparisons for failures
  274. - Performance benchmarks (Parquet: 28x faster, Polars: 37x faster)
  275. **Size:** 48KB, 1,780 lines
  276. **Format:** Markdown with code examples
  277. **Usage:** Searchable by keyword, cross-referenced
  278. ### NUANCES.md
  279. Token-saving precautions that prevent hours of debugging:
  280. - 🔥 **10 Critical mistakes** that break trading (tick size, VWAP reset, SL lifecycle)
  281. - 🚀 **13 Performance tips** for 10x+ speedups
  282. - 📊 **7 Data quality checks** to prevent backtest lies
  283. - 💰 **5 Capital management rules** to protect capital
  284. - 🐛 **5 Debugging techniques** for production issues
  285. **Summary:** Read this FIRST before implementing anything.
  286. ## Advanced Features
  287. ### Market Regime Detection
  288. Automatically amplifies risk in bull markets:
  289. ```python
  290. from algotrader.risk import detect_market_regime, calculate_position_size
  291. # Detect regime (BULL, BEAR, SIDEWAYS)
  292. regime = detect_market_regime(nifty_data)
  293. # Adjust position size
  294. base_size = 500_000 # ₹5L base
  295. regime_multipliers = {
  296. "BULL": 1.2, # +20% in bull market
  297. "BEAR": 0.5, # -50% in bear market
  298. "SIDEWAYS": 0.8 # -20% in sideways
  299. }
  300. position_size = base_size * regime_multipliers[regime]
  301. # BULL: ₹6L, BEAR: ₹2.5L, SIDEWAYS: ₹4L
  302. ```
  303. ### Kelly Criterion Position Sizing
  304. Optimal position sizing based on win rate:
  305. ```python
  306. from algotrader.risk import calculate_kelly_position
  307. kelly = calculate_kelly_position(
  308. win_rate=0.65, # 65% win rate
  309. avg_win=0.012, # 1.2% avg win
  310. avg_loss=0.006 # 0.6% avg loss
  311. )
  312. print(f"Full Kelly: {kelly['full_kelly']:.1%}") # 28.6%
  313. print(f"Half Kelly: {kelly['half_kelly']:.1%}") # 14.3% (recommended)
  314. print(f"Use {kelly['recommended']:.1%} of capital")
  315. ```
  316. ### Post-Trade Analytics
  317. ```python
  318. from algotrader.analytics import generate_daily_report
  319. report = generate_daily_report(trades_file="logs/trades.jsonl")
  320. print(f"📊 Daily Performance:")
  321. print(f" Trades: {report['total_trades']}")
  322. print(f" Win Rate: {report['win_rate']:.1%}")
  323. print(f" P&L: ₹{report['pnl']:,.0f}")
  324. print(f" Best Trade: {report['best_trade']['symbol']} (+{report['best_trade']['pnl_pct']:.1%})")
  325. print(f" Worst Trade: {report['worst_trade']['symbol']} ({report['worst_trade']['pnl_pct']:.1%})")
  326. print(f" Sharpe Ratio: {report['sharpe_ratio']:.2f}")
  327. ```
  328. ## Production Checklist
  329. Before going live, ensure:
  330. - [ ] **Tick size rounding** implemented for all order prices
  331. - [ ] **Position reconciliation** on startup (Zerodha = truth)
  332. - [ ] **VWAP daily reset** at market open (9:15)
  333. - [ ] **Symbol cooldown** (45min after exit)
  334. - [ ] **Stop loss lifecycle** uses place-then-cancel pattern
  335. - [ ] **Candle completion** check (500ms buffer)
  336. - [ ] **Margin calculation** uses `net` not `opening_balance`
  337. - [ ] **Session timing** blocks 11:30-13:00 (choppy lunch)
  338. - [ ] **Parquet caching** for historical data (28x faster)
  339. - [ ] **Structured logging** (operational, debug, errors separate)
  340. - [ ] **Backtest comparison** validates parity
  341. - [ ] **Risk limits** enforced (max 1% per trade, 5% portfolio heat)
  342. - [ ] **Circuit breaker** proximity check before entry
  343. - [ ] **Graceful shutdown** handler (Ctrl+C closes positions)
  344. - [ ] **Backup automation** before code modifications
  345. See [NUANCES.md](NUANCES.md) for detailed checklist.
  346. ## Performance Benchmarks
  347. Real-world improvements from applying AlgoTrader patterns:
  348. | Optimization | Before | After | Gain |
  349. |--------------|--------|-------|------|
  350. | Parquet caching | 2.3s load | 0.08s load | **28.7x** |
  351. | Polars vectorization | 450ms | 12ms | **37.5x** |
  352. | API batching | 15 calls | 1 call | **15x** |
  353. | Pre-computed indicators | 180ms | 90ms | **2x** |
  354. | **Total backtest time** | **5 min** | **12 sec** | **25x** |
  355. ## Troubleshooting
  356. ### Common Issues
  357. **Issue:** Order rejected with "Tick size error"
  358. ```python
  359. # Fix: Round to tick size
  360. from algotrader.zerodha import get_tick_size, round_to_tick
  361. tick_size = get_tick_size("RELIANCE") # 0.05
  362. price = round_to_tick(1847.35, tick_size) # 1847.35 → 1847.35 (already ok)
  363. price = round_to_tick(1847.33, tick_size) # 1847.33 → 1847.35
  364. ```
  365. **Issue:** Backtest shows 65% win rate, live shows 40%
  366. ```python
  367. # Likely causes:
  368. 1. VWAP not reset daily - check if VWAP resets at 9:15
  369. 2. Candle completion not checked - add 500ms buffer
  370. 3. Different data sources - use same cache for both
  371. 4. Slippage not modeled - add realistic slippage (₹2-5)
  372. # Run parity diagnostic:
  373. /algotrader backtest compare backtest.parquet live.parquet
  374. ```
  375. **Issue:** Same stock bought/sold repeatedly (HINDALCO loop)
  376. ```python
  377. # Fix: Add symbol cooldown
  378. symbol_cooldowns[symbol] = time.time()
  379. if time.time() - symbol_cooldowns.get(symbol, 0) < 45*60:
  380. return None # Skip signal for 45 minutes
  381. ```
  382. ## Contributing
  383. We welcome contributions! This skill is designed for:
  384. 1. **Knowledge expansion** - Add new failure patterns as discovered
  385. 2. **Strategy templates** - Share working strategies
  386. 3. **Performance optimizations** - Better caching, faster indicators
  387. 4. **Indian market updates** - New SEBI regulations, exchange changes
  388. ### How to Contribute
  389. 1. Test changes thoroughly (backtest + paper trade)
  390. 2. Document learnings in KNOWLEDGE.md format
  391. 3. Add nuances to NUANCES.md if token-burning
  392. 4. Include LLM-friendly comments
  393. 5. Submit PR with before/after metrics
  394. ## License
  395. MIT License - see [LICENSE](LICENSE) file
  396. ## Disclaimer
  397. **⚠️ IMPORTANT:** This skill provides educational guidance for building trading systems. It does NOT:
  398. - Guarantee profits or specific returns
  399. - Provide investment advice
  400. - Replace professional financial guidance
  401. - Execute trades without user confirmation
  402. **Trading involves risk. Only trade with capital you can afford to lose.**
  403. Past performance (65% win rate, 51% CAGR) from backtests does NOT guarantee future results.
  404. ## Support
  405. - **Documentation:** [KNOWLEDGE.md](KNOWLEDGE.md) - Comprehensive learnings
  406. - **Quick Reference:** [NUANCES.md](NUANCES.md) - Token-saving gotchas
  407. - **Examples:** See `examples/` directory
  408. - **Issues:** GitHub Issues (if published)
  409. ## Changelog
  410. ### v1.0.0 (2026-02-14)
  411. - ✅ Initial release with 16 knowledge domains
  412. - ✅ Interactive bot generation wizard
  413. - ✅ Universe fetcher from live NSE data
  414. - ✅ 30+ token-burning gotchas documented
  415. - ✅ Fortress signal (65% win rate)
  416. - ✅ Backtest comparison tool
  417. - ✅ Production failure prevention
  418. - ✅ Performance optimizations (28x Parquet, 37x Polars)
  419. - ✅ Risk management (Kelly, regime detection)
  420. ---
  421. **Built with real-world trading experience. Designed for production use.**
  422. *"Read NUANCES.md first. It saves 100+ debugging sessions."*

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.