DEV Community

shakti tiwari
shakti tiwari

Posted on

Termux + Ollama: Build AI Trading Dashboard on Android

I moved my entire trading stack to a ₹15,000 phone. Here’s how.

My MacBook is powerful, but it sleeps. My Android phone doesn’t. When I’m traveling or my home internet dies, my trading bot should keep running.

So I built a complete AI trading dashboard on Android using Termux + Ollama + Flask. Same backend code. Same dashboard. Same Dhan API integration. Just running on a phone.

This is the step-by-step guide.

Why Android for trading?

Feature Android + Termux Mac/PC
Always on ✅ (battery + Doze) ❌ Sleep mode
Cost ₹0 (existing phone) ₹80,000+
Portability ✅ Carry anywhere ❌ Fixed location
Compute 4-6GB RAM (sufficient) 16-32GB RAM
Auto-restart ✅ Termux:Boot + crontab ✅ launchd/Task Scheduler

I’m not saying replace your Mac. I’m saying redundancy. If your main system fails, your phone takes over.

Prerequisites

Hardware:

  • Android phone with 4GB+ RAM (I use Oppo K13)
  • 10GB free storage
  • USB-C charging (keep it plugged in 24/7)

Software:

  • Termux from F-Droid (not Play Store — outdated there)
  • Ollama APK from GitHub releases
  • Python 3.12

Step 1: Install Termux

On your Android phone:

  1. Go to Settings → Security → Enable “Install from unknown sources”
  2. Open browser and go to: https://f-droid.org/packages/com.termux/
  3. Download and install Termux APK
  4. Open Termux and run:
# Update packages
pkg update && pkg upgrade -y

# Install essentials
pkg install python nodejs-lts git curl wget nano -y

# Verify Python
python --version
# Expected: Python 3.12.x
Enter fullscreen mode Exit fullscreen mode

Mac / Windows CMD equivalent:

# Mac Terminal
brew install python node git

# Windows CMD (via winget)
winget install Python.Python.3.12
winget install OpenJS.NodeJS.LTS
Enter fullscreen mode Exit fullscreen mode

Step 2: Install Ollama

Android (Termux):

# Download Ollama binary
curl -fsSL https://ollama.com/install.sh | sh

# Or manual install
curl -L https://github.com/ollama/ollama/releases/latest/download/ollama-linux-arm64 -o ~/ollama
chmod +x ~/ollama
~/ollama serve &
Enter fullscreen mode Exit fullscreen mode

Mac (Terminal):

brew install ollama
ollama serve &
Enter fullscreen mode Exit fullscreen mode

Windows CMD (PowerShell):

winget install Ollama.Ollama
ollama serve
Enter fullscreen mode Exit fullscreen mode

Step 3: Pull a trading model

# Mac/Linux/Termux — same command everywhere
ollama pull qwen2.5:0.5b

# Test it
ollama run qwen2.5:0.5b "Analyze NIFTY market structure"
Enter fullscreen mode Exit fullscreen mode

Why Qwen2.5 0.5B?

  • 400MB model size — fits on any phone
  • Fast inference on mobile CPU
  • Good enough for signal explanation, not full analysis

For heavier analysis, use your Mac as the “brain” and phone as the “runner.”

Step 4: Build the backend

Same Flask app, same code. Just run it on Android:

# Create project directory
mkdir -p ~/ai-trader
cd ~/ai-trader

# Create virtual environment
python -m venv venv
source venv/bin/activate  # Mac/Linux/Termux
# venv\Scripts\activate  # Windows CMD

# Install dependencies
pip install flask requests pandas numpy scikit-learn xgboost python-dotenv
Enter fullscreen mode Exit fullscreen mode

Backend structure:

ai-trader/
├── backend/
│   ├── app.py              # Flask API
│   ├── indicators.py       # Technical indicators
│   ├── predictor.py        # XGBoost model
│   └── dhan_client.py      # Dhan API wrapper
├── models/
│   └── macro_model.pkl     # Trained model
└── .env                    # Secrets
Enter fullscreen mode Exit fullscreen mode

Key code — Flask API (backend/app.py):

from flask import Flask, jsonify
import os
from dotenv import load_dotenv

load_dotenv()
app = Flask(__name__)

@app.route('/api/state')
def get_state():
    # Your existing logic
    return jsonify({
        "last_price": 24637.0,
        "signal": "CALL",
        "regime": "HIGH_VOLATILITY",
        "confidence": 0.75
    })

if __name__ == '__main__':
    port = int(os.getenv('PORT', 5050))
    app.run(host='0.0.0.0', port=port)
Enter fullscreen mode Exit fullscreen mode

Step 5: Run it on Android

# Activate venv
source venv/bin/activate

# Start backend
cd ~/ai-trader/backend
python app.py
Enter fullscreen mode Exit fullscreen mode

Test from phone browser:

http://localhost:5050/api/state
Enter fullscreen mode Exit fullscreen mode

Test from another device on same WiFi:

http://192.168.1.10:5050/api/state
Enter fullscreen mode Exit fullscreen mode

Step 6: Build the frontend

Same Next.js dashboard, but served from phone:

# Install Node.js (already installed via pkg)
npm install -g npm@latest

# Create Next.js app
npx create-next-app@latest dashboard --typescript --tailwind --no-eslint
cd dashboard

# Install dependencies
npm install axios recharts
Enter fullscreen mode Exit fullscreen mode

Frontend config (next.config.ts):

/** @type {import('next').NextConfig} */
const nextConfig = {
  async rewrites() {
    return [
      {
        source: '/api/:path*',
        destination: 'http://localhost:5050/api/:path*',
      },
    ]
  },
}

export default nextConfig
Enter fullscreen mode Exit fullscreen mode

Step 7: Auto-restart on boot

Termux:Boot setup:

# Install Termux:Boot from F-Droid
pkg install termux-api -y

# Create boot script
mkdir -p ~/.termux/boot
cat > ~/.termux/boot/start-ai-trader.sh << 'EOF'
#!/data/data/com.termux/files/usr/bin/bash
termux-wake-lock
cd ~/ai-trader
source venv/bin/activate
cd backend && python app.py &
cd ../dashboard && npm start &
EOF
chmod +x ~/.termux/boot/start-ai-trader.sh
Enter fullscreen mode Exit fullscreen mode

Cron for periodic health checks:

# Edit crontab
crontab -e

# Add these lines
@reboot bash ~/.termux/boot/start-ai-trader.sh
*/30 * * * * curl -s http://localhost:5050/api/state || bash ~/.termux/boot/start-ai-trader.sh
Enter fullscreen mode Exit fullscreen mode

Step 8: Expose via Cloudflare Tunnel

# Install cloudflared
curl -s https://pkg.cloudflare.com/install.sh | bash
pkg install cloudflared

# Create tunnel
cloudflared tunnel create ai-trader-android

# Route traffic
cloudflared tunnel run ai-trader-android
Enter fullscreen mode Exit fullscreen mode

Your dashboard is now live at https://your-tunnel.trycloudflare.com.

Performance benchmarks

Metric Oppo K13 (Android) MacBook Air M2
Backend startup 3.2s 1.1s
XGBoost inference (per bar) 12ms 2ms
Frontend build 45s 18s
Memory usage 3.4GB / 8GB 6.1GB / 16GB
Battery drain 8%/hour (screen off) N/A

Verdict: Android handles 1-minute bar analysis comfortably. For 5-minute or higher timeframes, it’s more than enough.

What works and what doesn’t

✅ Works:

  • Flask backend with all 83 features
  • Dhan API integration
  • XGBoost inference
  • Next.js frontend
  • Cloudflare Tunnel exposure
  • Auto-restart on boot

❌ Doesn’t work well:

  • Model training (too slow on mobile CPU)
  • Large language models (Qwen2.5 7B+ crashes)
  • Backtesting on 5+ years of data

Workaround: Train models on Mac, copy .pkl files to phone via Syncthing or manual transfer.

Security considerations

  1. Don’t expose backend directly — always use Cloudflare Tunnel
  2. Rotate Dhan token every 30 days
  3. Enable biometric lock on Termux
  4. Use .env file — never hardcode credentials
  5. Whitelist tunnel IP in Dhan, not your home IP

TL;DR

Component Android Command Mac/Windows Equivalent
Package manager pkg install brew install / winget install
Python venv source venv/bin/activate Same / venv\Scripts\activate
Start backend python app.py Same
Start frontend npm run dev Same
Tunnel cloudflared tunnel run Same
Auto-start Termux:Boot + cron launchd / Task Scheduler

Total cost: ₹0. Total uptime: 99% (phone sleeps occasionally).


Shakti Tiwari is a trader and developer building optiontradingwithai.in. He co-directs CodeVisser and authored books on trading psychology. Find him on Dev.to as @shaktitiwari715-ai.

Top comments (0)