Single Page Operations Manual

Nifty Maths Strategy Bot 2
Complete Setup, Configuration & ON/OFF Guide

An exhaustive, production-grade guide for deploying, configuring, monitoring, and operating the isolated Second Nifty Maths Strategy Bot on cPanel shared hosting (PHP 8.2+ / MariaDB) with Angel One SmartAPI integration.

1 Quick Setup (3 Steps to Launch)

Bot 2 is engineered to be 100% self-contained inside the bot2/ directory. It does not overwrite, interfere with, or touch any existing Bot 1 files in your root directory.

A Upload Folder

Upload the complete bot2/ folder to your cPanel web root (e.g., /home/reshist/public_html/bot2/).

B Auto-Migrate

Open https://trade.reshi.in/bot2/ in your browser. All tables are automatically created on first visit!

C Authenticate

Log in with the default password: admin. Configure your broker and database keys in 1 click.

Zero-Configuration Database Auto-Installer
Bot 2 checks whether the bot2_settings table exists when you first load the page. If it doesn't, it immediately runs schema.sql and populates default settings. You do not need to manually import SQL files into phpMyAdmin!

2 Folder & File Architecture

Every file required by Bot 2 resides inside bot2/:

Directory Tree — /bot2/
bot2/
├── config.json                     # Primary configuration (DB credentials, Broker, Risk, Cron)
├── db.php                          # Dual PDO connection manager + auto-schema installer
├── schema.sql                      # Complete table definitions for bot2_* tables
├── cron.php                        # CLI & Web cron runner (20s polling loop, sleep(20), lockfile)
├── index.php                       # Interactive mission-control trading dashboard
├── api.php                         # Secure AJAX JSON API backend (Settings, Controls, Backtests)
├── docs.html                       # Self-contained single-page operations and setup manual
├── bot2.lock                       # Concurrency mutex lock (prevents overlapping cron executions)
├── bot2_audit.log                  # Structured append-only audit trail (with secret masking)
├── jwt_cache.json                  # Cached 2-hour Angel One broker session token
├── services/                       # Modular business logic services
│   ├── AdvancedLevelMappingService.php  # MANDATORY: CE -> PE & PE -> CE reversed level resolver
│   ├── TradeManagementService.php       # 2-Lot sizing, Target 1 (+25), 2nd SL (+3), Trailing SL (+5/+5)
│   ├── StrategyEngine.php               # Performer classification (Rule 1 & Rule 2) & state machine
│   ├── OrderLifecycleService.php        # Idempotent order execution & Paper simulation engine
│   ├── RiskManagementService.php        # Daily loss limits, max daily entries, Emergency Stop
│   ├── MarketDataService.php            # Reads 7 AM nifty_option_data from external data DB
│   ├── AngelOneAdapter.php              # SmartAPI client (RFC 6238 TOTP, Quotes, Orders, Positions)
│   ├── AuditLogger.php                  # Database & file logger with Telegram/Email dispatchers
│   └── BacktestEngine.php               # Historical backtesting simulation engine
└── tests/
    ├── MappingTest.php                  # Automated tests A-H for reversed level mapping
    ├── TradeManagementTest.php          # 2-lot trade management, T1 exit, 2nd lot SL, trailing ladder
    ├── OrderLifecycleTest.php           # Idempotent orders, paper simulation, broker reconciliation
    └── run_all_tests.php                # Master test runner (25/25 automated unit tests pass)
                    

3 Login & Password Management

The dashboard is guarded by a session-based password authentication screen.

Default Password

The default password is:

admin

How to Change the Password

  1. Log in to the dashboard at https://trade.reshi.in/bot2/.
  2. In the right-hand Control Panel, enter your new password in the Dashboard Password input box.
  3. Click Apply Configuration. It immediately updates in bot2/config.json!
Emergency Password Reset
If you ever forget your password, simply open bot2/config.json in cPanel File Manager and edit line 5:
"dashboard_password": "your_new_password_here",

4 Dual MySQL Databases Setup

Bot 2 connects to two separate databases simultaneously:

Database Role Config Section Database Name Role & Responsibilities
Bot Operational DB db_bot reshidd (or your chosen DB) Stores Bot 2 operational tables: settings, signals, trades, orders, positions, audit logs, and backtests. Auto-created on first run.
Market Data DB db_data reshist_trade Read-only connection to where the daily 7 AM nifty_option_data table lives. Supplies strike levels and BEP.

Database Credentials in bot2/config.json:

Database Snippet — bot2/config.json
"db_bot": {
    "host": "localhost",
    "port": 3306,
    "name": "reshidd",
    "user": "reshiddb",
    "pass": "Rddb",
    "charset": "utf8mb4"
},
"db_data": {
    "host": "localhost",
    "port": 3306,
    "name": "reshist_trade",
    "user": "reshist_trade",
    "pass": "Reshi@trade",
    "table": "nifty_option_data",
    "charset": "utf8mb4"
}
                    
What if both tables are in the SAME database?
If you prefer to host both in the same database, simply set db_bot.name and db_data.name to the same database name! Bot 2's tables use the prefix bot2_* so there will never be any table name collisions.

5 Angel One SmartAPI & TOTP Authentication

Bot 2 integrates directly with Angel One SmartAPI using RFC 6238 HMAC-SHA1 dynamic Time-Based One-Time Passwords (TOTP). This means you never have to manually enter an OTP every morning — the bot logs in autonomously!

How to Obtain Your Credentials from Angel One:

  1. API Key: Visit smartapi.angelbroking.com, log in, create a Trading App, and copy the API Key.
  2. Client Code: Your Angel One account username (e.g. R123456).
  3. Trading MPIN: The 4-digit or 6-digit MPIN you use to log into the Angel One mobile app.
  4. TOTP Secret Key (Crucial):
    • Go to Angel One SmartAPI Profile → Enable TOTP.
    • When the QR code appears, click "Can't scan QR code? Click here to reveal code".
    • Copy the Base32 alphanumeric key (e.g. JBSWY3DPEHPK3PXP) and paste it into broker.totp_secret.
Broker Config Snippet — bot2/config.json
"broker": {
    "api_key": "YOUR_ANGEL_SMARTAPI_KEY",
    "client_code": "YOUR_CLIENT_ID",
    "password": "YOUR_TRADING_MPIN",
    "totp_secret": "YOUR_BASE32_TOTP_KEY",
    "index_symbol": "Nifty 50",
    "index_token": "26000",
    "hist_index_token": "99926000",
    "index_exch": "NSE",
    "opt_exch": "NFO",
    "default_lot_size": 65
}
                    
Intelligent Session Caching (jwt_cache.json)
SmartAPI session tokens are cached in bot2/jwt_cache.json for 2 hours. The bot automatically re-authenticates only when the token is near expiration, ensuring zero API rate-limit violations.

6 Complete `config.json` Reference

Below is the complete, documented bot2/config.json file. Every field is explained in detail:

Full Annotated File — bot2/config.json
{
    "bot_name": "Nifty Maths Strategy Bot 2",
    "bot_enabled": true,
    "execution_mode": "LIVE_DISABLED",
    "dashboard_password": "admin",
    "secret_cron_key": "nifty_maths_secret_cron_2026",
    "cron": {
        "loop_count": 3,
        "sleep_seconds": 20,
        "max_execution_seconds": 55
    },
    "db_bot": {
        "host": "localhost",
        "port": 3306,
        "name": "reshidd",
        "user": "reshiddb",
        "pass": "Rddb",
        "charset": "utf8mb4"
    },
    "db_data": {
        "host": "localhost",
        "port": 3306,
        "name": "reshist_trade",
        "user": "reshist_trade",
        "pass": "Reshi@trade",
        "table": "nifty_option_data",
        "charset": "utf8mb4"
    },
    "broker": {
        "api_key": "YOUR_API_KEY",
        "client_code": "YOUR_CLIENT_CODE",
        "password": "YOUR_MPIN",
        "totp_secret": "YOUR_TOTP_KEY",
        "index_symbol": "Nifty 50",
        "index_token": "26000",
        "hist_index_token": "99926000",
        "index_exch": "NSE",
        "opt_exch": "NFO",
        "default_lot_size": 65
    },
    "strategy": {
        "lots_to_trade": 2,
        "strike_interval": 100,
        "initial_sl_offset": 25.0,
        "target1_points": 25.0,
        "second_lot_sl_offset": 3.0,
        "trailing_activation_offset": 35.0,
        "trailing_sl_initial_offset": 25.0,
        "trailing_step_points": 5.0,
        "trailing_sl_step_points": 5.0,
        "reverse_mapping_enforced": true,
        "market_start_time": "09:15",
        "market_end_time": "15:15",
        "auto_square_off_time": "15:20"
    },
    "risk": {
        "max_daily_loss": 5000.0,
        "max_daily_entries": 3,
        "max_open_positions": 1,
        "max_capital_allocated": 100000.0,
        "max_data_age_minutes": 1440,
        "emergency_stop": false
    },
    "telegram": {
        "enabled": true,
        "bot_token": "YOUR_BOT_TOKEN",
        "chat_id": "YOUR_CHAT_ID"
    },
    "smtp": {
        "enabled": true,
        "host": "mail.reshi.in",
        "port": 465,
        "encryption": "ssl",
        "username": "trade@reshi.in",
        "password": "Reshi@trade",
        "from_email": "trade@reshi.in",
        "to_email": "streshi17@gmail.com"
    }
}
                    

Key Parameters Breakdown:

Parameter Default Impact & Description
strategy.lots_to_trade 2 Number of lots entered on every signal (2 lots × 65 = 130 quantity for Nifty).
strategy.initial_sl_offset 25.0 Initial SL points subtracted from the Mapped Reversed Advanced Level ($\text{SL} = \text{Mapped Level} - 25$).
strategy.target1_points 25.0 Points above Entry Fill where Lot 1 exits ($\text{Entry} + 25$). Exits 65 quantity.
strategy.second_lot_sl_offset 3.0 Stop-loss for Lot 2, activated only after Lot 1 exits at Target 1 ($\text{Entry} + 3$).
strategy.trailing_activation_offset 35.0 Premium gain above Entry Fill that triggers the Trailing Stop-Loss ladder ($\text{Entry} + 35$). Sets SL to $\text{Entry} + 25$.
strategy.trailing_step_points 5.0 For every additional ₹5 gain in the High-Water Mark above activation, Stop-Loss moves up by ₹5.
risk.max_daily_loss 5000.0 Max intraday loss in ₹. Once breached, all further entries for the day are halted.

7 cPanel Cron & 20-Second Polling Loop

Standard cPanel shared hosting cron allows tasks to run at most once per minute (* * * * *). However, an options strategy requires faster evaluation to catch breakouts and manage trailing stop losses.

How the Sub-Minute Polling Loop Works
When cPanel fires cron.php once a minute, the script executes 3 distinct ticks inside that single minute using sleep(20):
  1. Tick 1: Runs immediately at Second 00.
  2. Sleep: Pauses for 20 seconds.
  3. Tick 2: Runs at Second 20.
  4. Sleep: Pauses for 20 seconds.
  5. Tick 3: Runs at Second 40.
  6. Exit: Terminates cleanly at Second 42 — well before the 55-second safety cutoff and before the next minute's cron begins!

Setting up the Cron Job in cPanel:

  1. Log into your cPanel.
  2. Under Advanced, click Cron Jobs.
  3. Under Add New Cron Job, select Once Per Minute (* * * * *).
  4. In the Command box, paste the following command:
cPanel Cron Command
* * * * * /usr/local/bin/php /home/reshist/public_html/bot2/cron.php > /dev/null 2>&1

Alternative: Webhook / External Cron (UptimeRobot / Cron-Job.org):

If your hosting provider restricts command-line PHP, you can trigger the cron via HTTPS webhook using your secret cron key:

HTTP Webhook URL
https://trade.reshi.in/bot2/cron.php?key=nifty_maths_secret_cron_2026

Concurrency Safety (`bot2.lock`):

cron.php uses a non-blocking operating system file lock (flock(LOCK_EX | LOCK_NB)) on bot2.lock. If a previous cron run is still active, new cron triggers exit immediately, preventing overlapping trades or duplicate orders.

8 How to Turn the Bot ON / OFF

Bot 2 provides three levels of operational control: Global Strategy State, Execution Mode, and Emergency Stop.

ON Bot Strategy Active: ON

  • Reads 7 AM data from nifty_option_data.
  • Monitors Spot Open and 9:20 candle for performer selection.
  • Evaluates breakout criteria and enters 2-lot trades.
  • Actively manages Target 1, 2nd lot SL, and Trailing SL.

OFF Bot Strategy Active: OFF

  • Completely suspends all new trade entry signals.
  • Safe Position Monitoring: If a position is already open, the bot continues to monitor and exit it safely.
  • Zero new risk is taken while disabled.

How to Toggle via Dashboard (1 Click):

  1. Log in to https://trade.reshi.in/bot2/.
  2. In the right-hand Control Panel, locate the Bot Strategy Active switch.
  3. Toggle the switch to ON or OFF.
  4. Click Apply Configuration. The change is saved to both MySQL database and bot2/config.json instantly.

9 Execution Modes (Live vs Demo / Paper)

Bot 2 supports three execution modes selectable from the dashboard dropdown:

Mode Badge Real Money? Behavior
LIVE_DISABLED LIVE_DISABLED NO RISK Default safe mode. Connects to broker for real-time market data quotes, evaluates reversed level mapping, and prints audit logs without placing any orders.
PAPER (Demo) PAPER (DEMO) NO RISK Full simulated trading engine. Uses live market tick prices to simulate entries, fills, Target 1 exit (65 qty), 2nd lot SL (+3), and the trailing stop-loss ladder. Calculates real-time PnL.
LIVE LIVE BROKER REAL MONEY Routes real orders to Angel One broker. Sized at 2 lots (130 qty). Double-checked by risk filters (Max Daily Loss, Max Entries).

10 Emergency Stop Kill-Switch

In fast-moving volatile markets or extreme news events, operator protection is paramount.

Immediate Kill-Switch Action
Clicking the red EMERGENCY STOP button in the dashboard header sets an immediate, persistent database flag (emergency_stop = 1). All strategy cron executions halt instantly across all subsequent cycles.

When Emergency Stop is active, the button turns into a flashing indicator. Clicking it again allows you to disengage the emergency stop once conditions have stabilized.

11 Telegram & Email Alerts Configuration

Receive instantaneous notifications on your mobile phone for every trading event:

Telegram Alerts

  1. Create a bot on Telegram with @BotFather to get your bot_token.
  2. Message @userinfobot to get your chat_id.
  3. Toggle Telegram alerts ON in the dashboard Control Panel.
"telegram": {
    "enabled": true,
    "bot_token": "8469066890:AAEt5s...",
    "chat_id": "903944657"
}
                            

Email (SMTP) Alerts

Sends HTML emails for daily trade summaries and risk limit triggers via your cPanel mail server:

"smtp": {
    "enabled": true,
    "host": "mail.reshi.in",
    "port": 465,
    "encryption": "ssl",
    "username": "trade@reshi.in",
    "password": "Reshi@trade",
    "from_email": "trade@reshi.in",
    "to_email": "streshi17@gmail.com"
}
                            

Alert Types Dispatched:

  • 🚀 Entry Triggered: Option symbol, 2 lots (130 qty), entry price, mapped reversed level source, and initial SL.
  • 🎯 Target 1 Hit: 1 lot (65 qty) exit at Entry + 25 points. Second-lot SL adjusted to Entry + 3.
  • 📈 Trailing SL Step: High-water mark increase → SL raised by +5 points.
  • 🛑 Position Closed: Final PnL and trade duration.
  • ⚠️ Risk Warning: Max daily loss threshold reached or Emergency Stop triggered.

12 Mandatory Reversed Advanced Level Mapping Rule

CRITICAL STRATEGY INVARIANT
In this strategy, the Advanced Level mapping is intentionally reversed between Call (CE) and Put (PE) trades:
  • Long CE trade → MUST use the corresponding PE-side Advanced Level (put_price).
  • Long PE trade → MUST use the corresponding CE-side Advanced Level (call_price).
  • Same-side fallback is STRICTLY PROHIBITED. If the opposite-side record is missing, the trade is rejected.
Long CE Signal (Call Option)
→ Reversed Mapping →
Read PE-side put_price
→ Initial SL Rule →
Initial SL = PE Level − 25
Long PE Signal (Put Option)
→ Reversed Mapping →
Read CE-side call_price
→ Initial SL Rule →
Initial SL = CE Level − 25

Concrete Example:

Parameter Call Option (CE Trade) Put Option (PE Trade)
Option Traded NIFTY 24500 CE NIFTY 24500 PE
Entry Fill Price ₹200.00 ₹180.00
CE Level in 7 AM Table (call_price) ₹210.00 ₹210.00
PE Level in 7 AM Table (put_price) ₹195.00 ₹195.00
Level Used by Strategy ₹195.00 (from PE) ₹210.00 (from CE)
Initial Stop-Loss $195 - 25 = \mathbf{₹170.00}$ $210 - 25 = \mathbf{₹185.00}$
Target 1 (+25 pts) $200 + 25 = \mathbf{₹225.00}$ $180 + 25 = \mathbf{₹205.00}$

13 2-Lot Management & Trailing Stop-Loss Ladder

Every executed trade strictly follows this 4-stage lifecycle:

Stage 1 Entry Execution (2 Lots = 130 Qty)

Both lots are bought simultaneously. The initial stop loss is set at $\text{Mapped Opposite Level} - 25$.

Stage 2 First-Lot Target Hit ($\text{Entry} + 25$)

When the option premium rises by 25 points above entry:

  • 1 lot (65 qty) exits immediately at the market price, locking in $+25 \text{ pts} \times 65 = \mathbf{+₹1,625}$ profit.
  • Second-Lot Stop Loss activates: The SL for the remaining 65 quantity is moved to $\text{Entry} + 3$ points (locking in $+3 \text{ pts} \times 65 = \mathbf{+₹195}$ guaranteed minimum profit on lot 2).

Stage 3 Trailing SL Activation ($\text{Entry} + 35$)

When the option premium reaches $\text{Entry} + 35$ points:

  • The Stop-Loss for Lot 2 is immediately moved up to $\text{Entry} + 25$ points.
  • The High-Water Mark (HWM) tracking begins.

Stage 4 High-Water Mark Trailing Ladder (+5 / +5)

For every additional 5 points the market advances above activation, the Stop Loss is bumped up by 5 points:

Option Premium High-Water Mark Gain Above Entry (₹200 Example) Active Stop-Loss Level Locked Profit (Lot 2)
₹235.00 (Activation Trigger)+35 pts₹225.00 (Entry + 25)+₹1,625.00
₹240.00+40 pts₹230.00 (Entry + 30)+₹1,950.00
₹245.00+45 pts₹235.00 (Entry + 35)+₹2,275.00
₹250.00+50 pts₹240.00 (Entry + 40)+₹2,600.00
₹255.00+55 pts₹245.00 (Entry + 45)+₹2,925.00
₹260.00+60 pts₹250.00 (Entry + 50)+₹3,250.00
Monotonicity Guarantee (Ratchet Principle)
The Stop Loss is strictly non-decreasing. If the option premium pulls back from ₹258 to ₹248, the Stop Loss remains firmly at ₹245. It never moves backward.

14 Daily Automated Trading Timeline

Time (IST) Phase Action & System Event
07:00 AM Data Population External system populates table nifty_option_data in reshist_trade. Bot 2's dashboard shows 7 AM Data Ready badge.
09:00 - 09:14 AM Pre-Market Prep Operator checks dashboard status. Bot ensures Angel One session token is valid and databases are connected.
09:15 AM Market Open Bot records the Nifty Spot Open price. Evaluates Rule 1 (Spot Open vs Previous Day Close).
09:20 AM Performer Selection The 09:15-09:20 five-minute candle closes. Rule 2 evaluates (Open vs Close). The winning performer (CALL or PUT) is locked for the day.
09:20 - 15:15 PM Trading Window cPanel cron evaluates market ticks every 20 seconds. Breakouts trigger 2-lot orders. Exits managed via T1, 2nd lot SL, and Trailing ladder.
15:15 - 15:20 PM Auto Square-Off Intraday positions are squared off automatically. No overnight risk is carried. End-of-day summary email dispatched.

15 Troubleshooting & Frequently Asked Questions

1. What is the default password and how do I reset it?
The default password is admin. You can change it directly in the dashboard Control Panel. If you forgot your password, open bot2/config.json in cPanel File Manager and edit line 5: "dashboard_password": "your_password".
2. "Database Connection Failed: Access denied for user" error?
Check bot2/config.json under db_bot and db_data. Ensure that the database user is assigned to the database in cPanel → MySQL Databases with "ALL PRIVILEGES" checked.
3. Cron job seems stuck or isn't triggering?
Check if an old lock file exists. Delete bot2/bot2.lock if it hasn't been modified in over 5 minutes. You can also test your cron in browser by visiting: https://trade.reshi.in/bot2/cron.php?key=nifty_maths_secret_cron_2026.
4. How do I know if the Reversed Mapping is working correctly?
Look at the prominent Mandatory Reversed Advanced Level Mapping Transparency card in the dashboard. When a CE trade evaluates, the "Mapped Source Side" column will explicitly show a green PE-Side (put_price) badge with full mathematical proof.
5. Will Bot 2 interfere with my existing Bot 1?
No, absolutely not. Bot 2 has its own isolated namespace, own database tables (bot2_*), own config, own lockfile, and own cron script. Bot 1 remains 100% untouched.
6. How do I test the bot before trading live money?
Set the execution mode to PAPER (Demo) in the dashboard Control Panel. The bot will connect to live market data, simulate orders, execute Target 1 exits, adjust stop-losses, and track virtual PnL with zero real financial risk!
Copied to clipboard!