DEV Community

shakti tiwari
shakti tiwari

Posted on

How to Use Termux for NSE Algorithmic Trading: A Complete Guide (2026)

How to Use Termux for NSE Algorithmic Trading: A Complete Guide (2026)

DOYR | Not financial/legal/tax advice. For educational purposes only.


If you've ever tried to run trading software on your Android phone and hit a wall — no desktop apps, no proper Python environment, no access to live NSE data — this guide is for you.

Termux turns your Android device into a full Linux terminal. Combined with Python, cron scheduling, and a few NSE data sources, you can build a complete algorithmic trading workstation for under ₹1,000 (if you already own the phone).

This is not theory. This is the exact setup I use for nse_ai_agent — an open-source AI trading assistant that runs entirely on Termux.


What You'll Build By The End

Feature Tool/Method
Live NSE quotes Python + requests
Option chain data NSE API endpoints
FII/DII flow tracking Web scraping + cron
Automated backtesting Backtrader / custom scripts
Telegram alerts python-telegram-bot
Scheduled tasks Termux cron
Local LLM sentiment Ollama / LM Studio
Risk management Custom Python calculators

Cost: ₹0 (all tools are free and open-source)


Why Termux? Why Not Zerodha Pi or Upstox Pro?

Tool Platform Cost Automation NSE Data Best For
Zerodha Pi Windows/Mac Free Limited Yes Active traders with laptop
Upstox Pro Windows/Mac/Web Free No Yes Beginners
Groww Android/iOS Free No Yes Investing, not trading
Termux + Python Android Free Full Yes (via APIs) Automation + custom tools

The Real Problem with Desktop Apps

  1. You need a laptop. Not everyone has one, or wants to carry one.
  2. Apps are closed-source. You can't add custom indicators, modify logic, or integrate AI.
  3. No automation. Zerodha Pi has some, but it's limited and Windows-only.
  4. Data export is hard. Getting historical data for backtesting requires manual CSV downloads.
  5. Battery/portability. Laptop dies. Phone doesn't.

Why Termux Wins for Indian Retail Traders

Advantage Explanation
Always with you Phone = always on, always connected
Full Linux environment pip install anything. Python, R, Julia — all work
Cron scheduling Run scripts every 5 minutes, every hour, every day
SSH access Control from laptop when needed
Git integration Version control for your strategies
Zero cost Termux is free. Data sources are free.
Privacy Data stays on your device. No cloud dependency

Step 1: Setting Up Termux for Trading

Installation

# Install Termux from F-Droid (NOT Play Store — Play Store version is deprecated)
# F-Droid: https://f-droid.org/packages/com.termux/

# Open Termux and run:
pkg update && pkg upgrade -y
pkg install python python-dev pip -y
pkg install git curl wget -y
pkg install libjpeg-turbo libpng -y  # For chart libraries
Enter fullscreen mode Exit fullscreen mode

Essential Python Packages

pip install requests pandas numpy matplotlib seaborn
pip install python-dotenv schedule python-telegram-bot
pip install scikit-learn tensorflow  # For AI models
pip install beautifulsoup4 lxml  # For web scraping
Enter fullscreen mode Exit fullscreen mode

Termux Setup Checklist

[ ] Termux installed from F-Droid
[ ] Storage permission granted (termux-setup-storage)
[ ] Python 3.11+ installed
[ ] pip updated
[ ] Essential packages installed
[ ] Directory structure created:
    ~/nse_ai_agent/
    ├── data/
    ├── scripts/
    ├── logs/
    ├── models/
    └── config/
Enter fullscreen mode Exit fullscreen mode

Step 2: Fetching Live NSE Data

Method 1: NSE Official Endpoints (Unofficial)

NSE doesn't have a public API, but several endpoints are unofficially available.

import requests
import pandas as pd
from datetime import datetime

class NSEDataFetcher:
    def __init__(self):
        self.base_url = "https://www.nseindia.com"
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Accept': 'application/json',
            'Accept-Language': 'en-US,en;q=0.9',
        }
        self.session = requests.Session()
        self.session.headers.update(self.headers)

    def get_nifty_quote(self):
        """Get live Nifty 50 quote"""
        url = f"{self.base_url}/api/quote-equity?symbol=NIFTY%2050"
        response = self.session.get(url)
        data = response.json()
        return {
            'last_price': data['priceInfo']['lastPrice'],
            'change': data['priceInfo']['change'],
            'pct_change': data['priceInfo']['pChange'],
            'open': data['priceInfo']['open'],
            'high': data['priceInfo']['intraDayHighLow']['max'],
            'low': data['priceInfo']['intraDayHighLow']['min'],
            'close': data['priceInfo']['close'],
            'timestamp': datetime.now()
        }

    def get_option_chain(self, symbol='NIFTY'):
        """Get full option chain"""
        url = f"{self.base_url}/api/option-chain-indices?symbol={symbol}"
        response = self.session.get(url)
        data = response.json()
        return pd.DataFrame(data['records']['data'])

    def get_fii_dii_data(self):
        """Get FII/DII flows"""
        url = f"{self.base_url}/api/fiidii-trade-data"
        response = self.session.get(url)
        return pd.DataFrame(response.json()['data'])
Enter fullscreen mode Exit fullscreen mode

⚠️ Important: These endpoints are unofficial. NSE may block them. Use responsibly. Don't spam requests.

Method 2: NSEpy (Python Library)

pip install nsepy
Enter fullscreen mode Exit fullscreen mode
from nsepy import get_history
from datetime import date

# Get historical data
data = get_history(
    symbol="NIFTY 50",
    start=date(2024, 1, 1),
    end=date(2024, 12, 31),
    index=True
)

print(data[['Open', 'High', 'Low', 'Close', 'Volume']].tail())
Enter fullscreen mode Exit fullscreen mode

Pros: Official-ish, stable. Cons: Limited to historical data, no live quotes.

Method 3: Yahoo Finance API (Alternative)

import yfinance as yf

nifty = yf.Ticker("^NSEI")
data = nifty.history(period="1d", interval="1m")
print(data[['Open', 'High', 'Low', 'Close']].tail())
Enter fullscreen mode Exit fullscreen mode

Pros: Reliable, no NSE blocking. Cons: 15-minute delay for Indian indices.


Step 3: Building Your First Trading Script

Example: Nifty Momentum Scanner

import requests
import pandas as pd
from datetime import datetime

class NiftyMomentumScanner:
    def __init__(self):
        self.fetcher = NSEDataFetcher()
        self.lookback = 20  # 20-period momentum

    def calculate_momentum(self, historical_data):
        """Calculate rate of change"""
        current = historical_data['Close'].iloc[-1]
        past = historical_data['Close'].iloc[-self.lookback]
        momentum = (current - past) / past * 100
        return momentum

    def scan(self):
        """Scan Nifty for momentum signals"""
        # Get historical data (using nsepy for simplicity)
        from nsepy import get_history
        from datetime import date, timedelta

        end_date = date.today()
        start_date = end_date - timedelta(days=30)

        data = get_history(
            symbol="NIFTY 50",
            start=start_date,
            end=end_date,
            index=True
        )

        momentum = self.calculate_momentum(data)
        current_price = data['Close'].iloc[-1]

        signal = None
        if momentum > 2:
            signal = "BULLISH"
        elif momentum < -2:
            signal = "BEARISH"
        else:
            signal = "NEUTRAL"

        return {
            'timestamp': datetime.now(),
            'price': current_price,
            'momentum': round(momentum, 2),
            'signal': signal
        }

# Run scanner
scanner = NiftyMomentumScanner()
result = scanner.scan()
print(f"Nifty: {result['price']} | Momentum: {result['momentum']}% | Signal: {result['signal']}")
Enter fullscreen mode Exit fullscreen mode

Step 4: Scheduling with Termux Cron

Termux has its own cron package. This is how you automate scripts.

Install Cron

pkg install cronie -y
termux-services start crond
Enter fullscreen mode Exit fullscreen mode

Setup Crontab

termux-job-scheduler --help  # Check if available
# OR use termux-cron
crontab -e
Enter fullscreen mode Exit fullscreen mode

Example: Run Scanner Every 5 Minutes During Market Hours

# Edit crontab
crontab -e

# Add this line:
*/5 9-15 * * 1-5 /data/data/com.termux/files/home/nse_ai_agent/scripts/momentum_scanner.sh

# The script:
#!/data/data/com.termux/files/home/usr/bin/bash
cd ~/nse_ai_agent
termux-toast "Running Nifty scanner..."
python scripts/momentum_scanner.py >> logs/scanner.log 2>&1
Enter fullscreen mode Exit fullscreen mode

Important Termux Cron Gotchas

Issue Solution
Cron doesn't run after reboot Use termux-services start crond in boot script
Python path issues Use full path: /data/data/com.termux/files/home/usr/bin/python
Storage permissions Run termux-setup-storage first
Battery optimization Disable for Termux in Android settings
Network on boot Add termux-wake-lock to prevent sleep

Step 5: Backtesting Framework

Why Backtest?

Because "it worked in my head" is not a strategy. Backtesting tells you:

  • Would this strategy have made money historically?
  • What's the maximum drawdown?
  • What's the win rate?
  • Is it robust across market conditions?

Simple Backtester in Python

import pandas as pd
import numpy as np

class SimpleBacktester:
    def __init__(self, data, initial_capital=100000):
        self.data = data
        self.capital = initial_capital
        self.position = 0
        self.trades = []

    def run_momentum_strategy(self, lookback=20, threshold=2):
        """Run momentum strategy on historical data"""
        for i in range(lookback, len(self.data)):
            window = self.data['Close'].iloc[i-lookback:i]
            momentum = (window.iloc[-1] - window.iloc[0]) / window.iloc[0] * 100

            current_price = self.data['Close'].iloc[i]

            # Buy signal
            if momentum > threshold and self.position == 0:
                shares = int(self.capital / current_price)
                cost = shares * current_price
                self.capital -= cost
                self.position = shares
                self.trades.append({
                    'type': 'BUY',
                    'price': current_price,
                    'shares': shares,
                    'date': self.data.index[i]
                })

            # Sell signal
            elif momentum < -threshold and self.position > 0:
                revenue = self.position * current_price
                self.capital += revenue
                self.trades.append({
                    'type': 'SELL',
                    'price': current_price,
                    'shares': self.position,
                    'date': self.data.index[i],
                    'pnl': revenue - (self.trades[-1]['price'] * self.position)
                })
                self.position = 0

        # Close any open position
        if self.position > 0:
            final_price = self.data['Close'].iloc[-1]
            self.capital += self.position * final_price
            self.position = 0

        return self.calculate_metrics()

    def calculate_metrics(self):
        """Calculate performance metrics"""
        total_trades = len([t for t in self.trades if t['type'] == 'SELL'])
        winning_trades = len([t for t in self.trades if t.get('pnl', 0) > 0])
        win_rate = (winning_trades / total_trades * 100) if total_trades > 0 else 0

        return {
            'final_capital': round(self.capital, 2),
            'total_return': round((self.capital - 100000) / 100000 * 100, 2),
            'total_trades': total_trades,
            'win_rate': round(win_rate, 2),
            'trades': self.trades
        }

# Usage
from nsepy import get_history
from datetime import date, timedelta

end_date = date.today()
start_date = end_date - timedelta(days=365)

data = get_history(symbol="NIFTY 50", start=start_date, end=end_date, index=True)

backtester = SimpleBacktester(data)
results = backtester.run_momentum_strategy()

print(f"Initial Capital: ₹1,00,000")
print(f"Final Capital: ₹{results['final_capital']}")
print(f"Total Return: {results['total_return']}%")
print(f"Total Trades: {results['total_trades']}")
print(f"Win Rate: {results['win_rate']}%")
Enter fullscreen mode Exit fullscreen mode

Step 6: Telegram Alerts for Trade Signals

Setup Telegram Bot

from telegram import Bot
from telegram.ext import Updater, CommandHandler
import os
from dotenv import load_dotenv

load_dotenv()

TELEGRAM_TOKEN = os.getenv('TELEGRAM_TOKEN')
CHAT_ID = os.getenv('CHAT_ID')  # Your Telegram chat ID

bot = Bot(token=TELEGRAM_TOKEN)

def send_alert(message):
    """Send alert to Telegram"""
    try:
        bot.send_message(chat_id=CHAT_ID, text=message, parse_mode='Markdown')
    except Exception as e:
        print(f"Failed to send alert: {e}")

# Example usage
send_alert(f"🚨 Nifty Signal: BUY\nPrice: 22,100\nMomentum: +2.5%\nTime: {datetime.now()}")
Enter fullscreen mode Exit fullscreen mode

Get Your Telegram Chat ID

  1. Message @userinfobot on Telegram
  2. It will reply with your numeric chat ID
  3. Save it in .env file

Step 7: Risk Management Scripts

Position Sizing Calculator

def calculate_position_size(capital, risk_per_trade, stop_loss_pct):
    """
    Calculate how many shares to buy based on risk tolerance.

    Args:
        capital: Total trading capital
        risk_per_trade: Max % willing to lose per trade (e.g., 2%)
        stop_loss_pct: Stop loss distance from entry (e.g., 5%)

    Returns:
        Number of shares to buy
    """
    max_loss = capital * (risk_per_trade / 100)
    risk_per_share = stop_loss_pct / 100  # Convert to decimal

    if risk_per_share == 0:
        return 0

    shares = int(max_loss / (capital * risk_per_share))
    return shares

# Example
capital = 100000  # ₹1 lakh
risk = 2  # 2% max loss per trade
stop_loss = 5  # 5% stop loss

shares = calculate_position_size(capital, risk, stop_loss)
print(f"Buy {shares} shares to risk exactly 2% of capital")
Enter fullscreen mode Exit fullscreen mode

Portfolio Tracker

class PortfolioTracker:
    def __init__(self, initial_capital):
        self.capital = initial_capital
        self.positions = {}
        self.trade_history = []

    def add_position(self, symbol, shares, entry_price):
        cost = shares * entry_price
        if cost > self.capital:
            print("Insufficient capital!")
            return False

        self.capital -= cost
        self.positions[symbol] = {
            'shares': shares,
            'entry_price': entry_price,
            'current_price': entry_price
        }
        return True

    def update_price(self, symbol, current_price):
        if symbol in self.positions:
            self.positions[symbol]['current_price'] = current_price

    def get_portfolio_value(self):
        stock_value = sum(
            pos['shares'] * pos['current_price'] 
            for pos in self.positions.values()
        )
        return self.capital + stock_value

    def get_total_return(self):
        return (self.get_portfolio_value() - 100000) / 100000 * 100

# Usage
portfolio = PortfolioTracker(100000)
portfolio.add_position("NIFTY 50", 50, 22000)
portfolio.update_price("NIFTY 50", 22500)

print(f"Portfolio Value: ₹{portfolio.get_portfolio_value()}")
print(f"Total Return: {portfolio.get_total_return()}%")
Enter fullscreen mode Exit fullscreen mode

Step 8: Limitations of Termux + Workarounds

Limitation Workaround
No native charting library Use matplotlib + save images. Or use TradingView API.
Limited CPU/RAM Stick to Nifty + large caps. Avoid complex ML models.
Network dependency Use termux-wake-lock + WiFi only. Don't rely on mobile data for critical scripts.
No broker API integration officially Use Zerodha Kite Connect API (works on Termux with Python).
Battery drain Schedule scripts only during market hours. Use cron efficiently.
NSE blocking Rotate user agents, add delays, use alternative data sources.

Step 9: Security Considerations

Critical Rules for Termux Trading

[ ] NEVER store API keys in plain text
[ ] Use python-dotenv + .env file (gitignored)
[ ] Enable biometric lock on Termux app
[ ] Use SSH key authentication, not passwords
[ ] Backup scripts to GitHub private repo
[ ] Don't run scripts as root
[ ] Verify all package signatures
[ ] Use HTTPS only for data fetching
[ ] Don't share your .env file
[ ] Regular security audits of your scripts
Enter fullscreen mode Exit fullscreen mode

Example: Secure Config

# config.py
from dotenv import load_dotenv
import os

load_dotenv()

class Config:
    TELEGRAM_TOKEN = os.getenv('TELEGRAM_TOKEN')
    CHAT_ID = os.getenv('CHAT_ID')
    ZERODHA_API_KEY = os.getenv('ZERODHA_API_KEY')
    ZERODHA_API_SECRET = os.getenv('ZERODHA_API_SECRET')
    CAPITAL = float(os.getenv('CAPITAL', 100000))
    RISK_PER_TRADE = float(os.getenv('RISK_PER_TRADE', 2))
Enter fullscreen mode Exit fullscreen mode

.env file (NEVER commit this):

TELEGRAM_TOKEN=123456:ABC-DEF...
CHAT_ID=123456789
ZERODHA_API_KEY=your_key
ZERODHA_API_SECRET=your_secret
CAPITAL=100000
RISK_PER_TRADE=2
Enter fullscreen mode Exit fullscreen mode

Step 10: Real-World Example — nse_ai_agent Architecture

System Overview

┌─────────────────────────────────────┐
│            Android Phone            │
│                                     │
│  ┌─────────────┐    ┌───────────┐  │
│  │ Termux      │    │ Ollama    │  │
│  │             │    │ (Local    │  │
│  │ - Python    │───▶│   LLM)    │  │
│  │ - Cron      │    │           │  │
│  │ - Scripts   │    └───────────┘  │
│  └──────┬──────┘          ▲        │
│         │                  │        │
│         ▼                  │        │
│  ┌─────────────┐           │        │
│  │ NSE Data    │           │        │
│  │ Fetching    │           │        │
│  └──────┬──────┘           │        │
│         │                  │        │
│         ▼                  │        │
│  ┌─────────────┐           │        │
│  │ Telegram    │           │        │
│  │ Bot Alerts  │◀──────────┘        │
│  └─────────────┘                    │
│                                     │
└─────────────────────────────────────┘
Enter fullscreen mode Exit fullscreen mode

Component Breakdown

Component Purpose Tech
Data Fetcher Pulls NSE quotes, option chains Python + requests
Strategy Engine Runs momentum, mean-reversion, AI models Python + pandas
Backtester Validates strategies on historical data Custom backtester
LLM Sentiment Analyzes news for market sentiment Ollama (local LLM)
Alert System Sends signals via Telegram python-telegram-bot
Scheduler Runs everything on time Termux cron
Risk Manager Position sizing, stop loss, portfolio tracking Python

Data Flow

1. Cron triggers at 9:15 AM (market open)
2. Script fetches Nifty quote + option chain
3. LLM analyzes recent news for sentiment
4. Strategy engine calculates signals
5. Risk manager checks position limits
6. If signal + risk OK → Telegram alert
7. Trader reviews alert and decides
8. Execution manual (your choice)
Enter fullscreen mode Exit fullscreen mode

Step 11: Complete Project Structure

nse_ai_agent/
├── README.md
├── requirements.txt
├── .env.example
├── config.py
├── scripts/
│   ├── data_fetcher.py      # NSE data fetching
│   ├── momentum_scanner.py  # Momentum strategy
│   ├── backtester.py        # Backtesting framework
│   ├── risk_manager.py      # Position sizing
│   ├── telegram_bot.py      # Alerts
│   ├── llm_sentiment.py     # News analysis
│   └── scheduler.py         # Cron wrapper
├── data/
│   ├── raw/                 # Raw NSE data
│   ├── processed/           # Cleaned data
│   └── backtest/            # Backtest results
├── logs/
│   ├── scanner.log
│   ├── errors.log
│   └── trades.log
├── models/
│   ├── momentum_model.pkl
│   └── sentiment_model.pkl
└── tests/
    ├── test_data_fetcher.py
    ├── test_strategy.py
    └── test_risk_manager.py
Enter fullscreen mode Exit fullscreen mode

Step 12: Zerodha Kite Connect on Termux

If you want automated execution (not just alerts):

from kiteconnect import KiteConnect

kite = KiteConnect(api_key=os.getenv('ZERODHA_API_KEY'))
kite.set_access_token(os.getenv('ZERODHA_ACCESS_TOKEN'))

# Place order
order_id = kite.place_order(
    tradingsymbol="NIFTY24DEC22000CE",
    exchange="NFO",
    transaction_type="BUY",
    quantity=50,
    order_type="MARKET",
    product="NRML",
    validity="DAY"
)

print(f"Order placed: {order_id}")
Enter fullscreen mode Exit fullscreen mode

Note: Requires Zerodha account + Kite Connect subscription (₹2,000/month for full API). For beginners, stick to alerts + manual execution.


FAQ: Termux + NSE Trading

Q1: Is Termux legal for trading?

A: Yes. Termux is a legitimate Android app. Trading through it is no different from using a laptop. Just ensure your broker allows API access from mobile IPs.

Q2: Will NSE block my IP for scraping?

A: Unofficial endpoints may get blocked. Solution: Use nsepy (more stable), rotate user agents, add delays (2-3 seconds between requests).

Q3: Can I run this 24/7?

A: Termux + cron can run 24/7, but:

  • Keep phone plugged in
  • Disable battery optimization for Termux
  • Use wake lock
  • Ensure stable WiFi

Q4: Is it safe to store API keys on phone?

A: Use .env files with proper permissions (chmod 600 .env). Never commit to Git. Consider encrypted storage for sensitive keys.

Q5: Which is better: Termux or laptop?

A: Laptop = more power, more tools. Termux = always with you, no extra device. Best: both. Use Termux for monitoring/alerts, laptop for deep analysis.

Q6: Can I use this for intraday trading?

A: Yes, but intraday requires low latency. Termux + 4G = ~100-200ms delay. For swing trading (days/weeks), perfect. For high-frequency, use desktop.

Q7: What if my phone dies during market hours?

A: Use termux-wake-lock to prevent sleep. Keep power bank handy. Better: run on cheap cloud VPS (₹100/month) for 24/7 reliability.

Q8: Is this better than paid algo trading platforms?

A: For ₹0 cost + full customization? Yes. For support, reliability, and institutional features? No. Depends on your needs.


The 5 Mistakes Termux Traders Make

Mistake 1: Running Scripts Without Error Handling

Problem: Script crashes silently. You miss signals. Fix: Add logging everywhere. Check logs daily.

Mistake 2: Not Handling NSE Blocking

Problem: NSE blocks your IP after 50 requests. Fix: Add delays, rotate user agents, use nsepy.

Mistake 3: Ignoring Battery Optimization

Problem: Android kills Termux after 30 minutes of screen off. Fix: Disable battery optimization, use wake lock.

Mistake 4: Overcomplicating

Problem: Building AI models before mastering basic strategies. Fix: Start with momentum scanner. Add complexity only when profitable.

Mistake 5: No Paper Trading

Problem: Real money lost in 2 weeks. Fix: Paper trade for 3 months minimum.


Final Checklist: Your Termux Trading Setup

SETUP PHASE:
[ ] Termux installed from F-Droid
[ ] Storage permission granted
[ ] Python + pip + essential packages installed
[ ] Directory structure created
[ ] NSE data fetcher working
[ ] Basic momentum scanner running
[ ] Telegram bot connected
[ ] Cron job scheduled
[ ] Risk management scripts tested
[ ] Backtester validated on 1 year data

SAFETY PHASE:
[ ] .env file created with chmod 600
[ ] API keys secured
[ ] Git repo initialized (private)
[ ] Backup system in place
[ ] Error logging enabled
[ ] Battery optimization disabled
[ ] Wake lock configured

GO-LIVE PHASE:
[ ] Paper traded for 3 months
[ ] Strategy profitable for 6 months
[ ] Risk parameters finalized
[ ] Emergency stop procedures documented
[ ] Telegram alerts tested
[ ] Ready for small capital deployment
Enter fullscreen mode Exit fullscreen mode

The Bottom Line

Termux is not a toy. It's a legitimate trading workstation that runs in your pocket.

The advantage is not cost — it's control. You own every line of code. You can modify strategies instantly. You can integrate AI, LLMs, custom indicators — whatever you want.

The disadvantage is responsibility. If your script fails at 9:30 AM during a gap-up opening, you can't call customer support. You fix it yourself.

For Indian retail traders who want:

  • Full control over their tools
  • Zero cost infrastructure
  • Always-on monitoring
  • Custom strategies that no broker offers

Termux is the answer.


Connect & Resources


Published on Dev.to | Tags: #termux #nse #trading #algorithmictrading #android #python #india #fintech

Top comments (0)