gAIn. Terminal Documentation
Welcome to the official documentation for the gAIn. Stock Market Terminal. This platform provides real-time, mathematically calculated trading targets and news for the Indian Stock Market (NSE/BSE).
The Name "gAIn." & The Pivot to Pure Math
The name gAIn. originally stood for the use of AI in predicting stock market. The initial concept was to build a system that utilized Large Language Models — particularly large-context models like the GLM series — to read vast amounts of financial news, parse historical balance sheets, and output trading predictions.
However, during development, a fundamental decision was made: financial predictions ought to be done via strict calculations, not AI hallucinations. Relying on an AI to determine exact entry and stop-loss prices introduced too much unpredictability. Therefore, the AI component was completely stripped out.
There is absolutely NO AI involved in the current system. Every number, target, and trend you see is calculated deterministically using pure, textbook technical analysis math executed via Python and Pandas.
However, I am too lazy to think of a better name, so the old one stays.
Architecture Overview
The application is split into a decoupled Frontend and Backend architecture, allowing for seamless live updates without relying on heavy processing for every tick.
- Frontend (Vercel / GitHub Pages): A pure HTML/JS/CSS file styled as a macOS terminal. It polls the backend every 2 seconds for live data, renders Markdown text, and draws Plotly charts directly in the browser.
- Backend (Fly.io / Render / Localhost): Built with Python FastAPI. It acts as the orchestrator, receiving requests, fetching live data, performing the math, and returning a formatted JSON payload.
- Data Server (
server.py): A local Python script spawned by the backend. It contains the "Tools" (functions) that fetch Yahoo Finance data, NSE profiles, and live RSS news feeds.
Input Format
You simply type the ticker (e.g., RELIANCE). The system handles the mapping to the correct Yahoo Finance suffix (e.g., .NS). Position sizing based on user capital has been removed to focus purely on signal generation.
The Mathematics (Explained Simply)
All math is calculated natively in Python using Pandas to ensure 100% accuracy. To ensure timeframe consistency, Trade Setup levels (Entry, Stop, Target) are derived from Daily Data (1d), while Momentum and Charts are derived from Intraday Data (5m).
Intraday Math (5-Minute Intervals)
- Session VWAP (Volume Weighted Average Price): The average price weighted by volume for today's trading session.
Formula: Cumulative(Typical Price * Volume) / Cumulative(Volume)
If current price > Session VWAP, intraday buyers currently have an advantage.
- Intraday ADX (5m): Measures intraday trend strength. If ADX > 25, the trend is strong. If ADX < 25, the market is sideways/choppy, and the system disables trades to prevent whipsaw losses.
- RSI (Relative Strength Index): Compares the magnitude of recent gains to recent losses. RSI >70 indicates strong/possibly overextended momentum; RSI <30 indicates weak/possibly oversold momentum.
- Stochastic RSI: Applies the RSI formula to RSI itself to find extreme edges over 14 periods.
- MACD (Moving Average Convergence Divergence): Shows momentum by comparing 12-period and 26-period EMAs.
Daily Math (Trade Setup & Long-Term Levels)
- Daily Bollinger Bands (20, 2): Volatility bands around the price. Touching an outer band indicates an unusually large move relative to recent volatility, not necessarily that price is overvalued or undervalued.
- Daily ATR (14): Measures how much the stock price moves up and down in a day. Used for the Stop Loss calculation.
- Recent Trading Hours Performance: Calculates the percentage change, High, and Low over the last ~6, ~12, and ~24 hours to give immediate context on short-term price action.
- 50-DMA & 200-DMA: Simple Moving Averages over 50 and 200 days. If 50-DMA > 200-DMA, it's an uptrend (Golden Cross). If below, downtrend (Death Cross).
- Fibonacci Retracement: Horizontal support/resistance lines based on the golden ratio, derived from the 52-Week High and Low.
Trade Setup, Trend Filters & Risk Management
This system uses strict trend-following principles and macro-filters to avoid systematic traps.
- Trend Regime: If 50-DMA > 200-DMA, the system looks for LONG setups. If 50-DMA < 200-DMA (Death Cross), the system looks for SHORT setups and disables BUY signals entirely.
- Nifty Trend Filter: The backend simultaneously fetches the Nifty 50 trend. If Nifty is crashing, individual stock BUY signals are downgraded to "WAIT (Nifty is down)".
- Heuristic Technical Score: A pure price-action score (e.g., 0) used to determine the bias multiplier for volatility projections.
- Technical Reasons: The system outputs a plain-English bulleted list of active signals (e.g., "MACD Bearish Cross", "Price > 50-DMA (Uptrend)", "Death Cross (50-DMA < 200-DMA)", "Low Volume (<0.5x Avg)") so the user knows exactly why a decision was made.
- Entry (LONG):
max(Daily Lower Bollinger Band, 24-hour Low)
- Target (LONG):
min(Daily Upper Bollinger Band, 24-hour High)
- Entry (SHORT):
min(Daily Upper Bollinger Band, 24-hour High) *(short only if price rallies to this level)*
- Target (SHORT):
max(Daily Lower Bollinger Band, 24-hour Low)
- Stop Loss:
Entry Price +/- (Daily ATR * 1.5)
- Realistic Indian Costs: Net Reward subtracts STT (0.1% turnover), Exchange Txn, GST, SEBI fees, Stamp Duty, and Slippage.
- Dynamic Risk/Reward: The required Net R:R is strictly
1.5 in low volatility, but jumps to 2.5 in high volatility (when Daily ATR > 2% of price).
- NO TRADE Hierarchy: If Net R:R <= 0, system outputs "NO TRADE (Negative Net Reward)". If R:R is positive but below the required threshold, or if ADX < 25, it outputs "AVOID / NO TRADE" and lists the specific failed conditions in parentheses, e.g., "(Failed: R:R < 1.5, ADX < 25)".
ATR Volatility Envelope (Projections)
Projections use a dynamic bias multiplier derived from the Technical Score. This is a volatility envelope, not a directional price prediction. The math scales Daily ATR by the exact fraction of the trading day remaining (6.25 hours total).
- 1-Hour Projection:
Current Price +/- (Daily ATR * (1/6.25) * max(0.5, 1 +/- Bias))
- Market Close:
Current Price +/- (Daily ATR * (Hours to Close / 6.25) * max(0.5, 1 +/- Bias))
Relative Volatility Gate
The system calculates the 90-day ATR percentile rank.
- < 20% = Very low volatility
- > 80% = Elevated volatility
- > 95% = Extreme volatility (Hard NO TRADE threshold)
Rolling OOS Validation (Walk-Forward Backtest)
The system runs a deterministic backtest using a 5-year Train / 1-year Test rolling window. It uses conservative same-day execution assumptions and deducts realistic costs.
- Metrics: Win Rate, Profit Factor, Mean Expectancy (R/Trade), Max Drawdown.
- Portfolio Simulation: Simulates a ₹10L portfolio risking 1% per trade to calculate CAGR, Daily Sharpe, and Daily Sortino ratios.
- Bootstrap CI: Runs 5,000 Monte Carlo simulations to calculate the 95% Confidence Interval for Expectancy and Max Drawdown.
- Robustness Check: Tests ATR multipliers (1.0, 1.5, 2.0) on the exact same OOS periods to ensure the strategy isn't fragile.
Live Market Scan (Tickers to Watch)
Aside from individual ticker analysis, the terminal runs an automated scan based on current price momentum and market trading activity. This is not a direct buy signal, but a watchlist generator.
- Short-Term Momentum Plays: Lists the Top NIFTY Gainers and Losers with their Last Traded Price (LTP) and percentage change.
- High-Activity Stocks: Lists stocks with the highest Traded Value (in Crores) to show where the highest institutional and retail capital is flowing right now.
Data Sources & Fallbacks
- Yahoo Finance API: Primary source for 5m intraday OHLCV and 2y daily historical data. (Uses explicit browser headers to bypass blocks).
- Stooq: 10-year daily historical fallback if Yahoo blocks the server IP.
- NSE India API: Fallback for company fundamentals (P/E, P/B, ROE) if Yahoo fails.
- News Aggregators (RSS): Scraped live for Stock-Specific and Global/Macro news. (Note: News is displayed for user context only and is NOT factored into the mathematical quant score).
- Event Risk Flag: The system checks for upcoming earnings within 3 days and flags them as "YES" or "NO" to warn the user of high volatility risk.
- Data Source Transparency: The terminal displays the exact data source used (e.g., "Yahoo"), the age of the data in seconds (e.g., "Age: 0.4s"), and the exact number of daily history days fetched (e.g., "500 days").
⚙️ How It Works (Step-by-Step)
- User types a ticker (e.g.,
RELIANCE) in the terminal.
- The Frontend sends a POST request to the FastAPI backend and starts a 2-second polling loop.
- The Backend runs the data engine, fetching 5m intraday data, 2y daily data (or Stooq 10y fallback), and Nifty trend.
- The Server fetches raw data, runs the Pandas mathematical calculations, applies the trend-following + macro + R:R + ADX filters, and structures it into JSON.
- The Backend formats this JSON into a Markdown string with
[CHART:...] tags and sends it back.
- The Frontend parses the Markdown, renders the text with yellow/green syntax highlights (using Indian comma formatting), and draws the Plotly charts exactly where the tags are placed without resetting zoom levels or jumping your scroll position.
← Back to Terminal