Yeh ek complete walkthrough hai — local setup, code, paper trade, fir live, fir VPS pe deploy. End mein aapka apna bot 24/7 chalega.
Pre-requisites
- Python 3.10+ installed
- Zerodha account + Kite Connect API (₹2k/month)
- Basic Python knowledge
- VPS account (Vultr/DigitalOcean — ₹500/month)
Step 1 — Project setup
mkdir trading-bot && cd trading-bot
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
pip install kiteconnect pandas python-dotenv schedule
Folder structure
trading-bot/
├── .env
├── config.py
├── auth.py
├── strategy.py
├── bot.py
├── logger.py
└── logs/
Step 2 — config & auth
.env
KITE_API_KEY=your_key
KITE_API_SECRET=your_secret
KITE_ACCESS_TOKEN=
SYMBOL=RELIANCE
INSTRUMENT_TOKEN=738561
QUANTITY=10
PAPER_TRADE=true
auth.py
from kiteconnect import KiteConnect
from dotenv import load_dotenv, set_key
import os
load_dotenv()
def get_kite():
kite = KiteConnect(api_key=os.getenv("KITE_API_KEY"))
token = os.getenv("KITE_ACCESS_TOKEN")
if not token:
print("Visit:", kite.login_url())
request_token = input("Paste request_token: ")
data = kite.generate_session(request_token, api_secret=os.getenv("KITE_API_SECRET"))
token = data["access_token"]
set_key(".env", "KITE_ACCESS_TOKEN", token)
kite.set_access_token(token)
return kite
Step 3 — strategy logic
strategy.py
import pandas as pd
def ma_crossover_signal(df):
df['ma_fast'] = df['close'].rolling(9).mean()
df['ma_slow'] = df['close'].rolling(21).mean()
if len(df) < 22:
return None
last = df.iloc[-1]
prev = df.iloc[-2]
# Bullish crossover
if prev['ma_fast'] <= prev['ma_slow'] and last['ma_fast'] > last['ma_slow']:
return "BUY"
# Bearish crossover
if prev['ma_fast'] >= prev['ma_slow'] and last['ma_fast'] < last['ma_slow']:
return "SELL"
return None
Step 4 — main bot loop
bot.py
import os, time
import pandas as pd
from datetime import datetime, timedelta
from auth import get_kite
from strategy import ma_crossover_signal
from logger import log
PAPER = os.getenv("PAPER_TRADE", "true") == "true"
SYMBOL = os.getenv("SYMBOL")
TOKEN = int(os.getenv("INSTRUMENT_TOKEN"))
QTY = int(os.getenv("QUANTITY"))
def fetch_candles(kite):
end = datetime.now()
start = end - timedelta(days=5)
return kite.historical_data(TOKEN, start, end, "5minute")
def place_order(kite, side):
if PAPER:
log(f"[PAPER] {side} {QTY} {SYMBOL}")
return
order_id = kite.place_order(
variety="regular",
exchange="NSE",
tradingsymbol=SYMBOL,
transaction_type=side,
quantity=QTY,
product="MIS",
order_type="MARKET"
)
log(f"[LIVE] {side} order: {order_id}")
def main():
kite = get_kite()
log("Bot started — paper=" + str(PAPER))
while True:
try:
now = datetime.now()
# Trade only 9:15-15:15
if not (9 <= now.hour < 15 or (now.hour == 15 and now.minute < 15)):
time.sleep(60); continue
candles = fetch_candles(kite)
df = pd.DataFrame(candles)
signal = ma_crossover_signal(df)
if signal:
log(f"Signal: {signal}")
place_order(kite, signal)
time.sleep(300) # 5 min
except Exception as e:
log(f"ERROR: {e}")
time.sleep(60)
if __name__ == "__main__":
main()
Step 5 — logger
logger.py
import os
from datetime import datetime
os.makedirs("logs", exist_ok=True)
def log(msg):
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
line = f"[{ts}] {msg}"
print(line)
with open(f"logs/{datetime.now().strftime('%Y-%m-%d')}.log", "a") as f:
f.write(line + "\n")
Step 6 — paper trade test
python bot.py
1-2 hafta paper mode mein chalao. Logs check karo. Strategy theek lag rahi ho toh PAPER_TRADE=false kar do.
Step 7 — VPS deployment
- Vultr/DigitalOcean pe Ubuntu 22.04 VPS (₹400-600/month)
- SSH login → git clone aapka repo
- Same setup repeat karo VPS pe
tmuxyasystemd servicebanao taaki bot disconnect ho ke bhi chalta rahe
systemd service example
# /etc/systemd/system/tradingbot.service
[Unit]
Description=Trading Bot
After=network.target
[Service]
Type=simple
User=ubuntu
WorkingDirectory=/home/ubuntu/trading-bot
ExecStart=/home/ubuntu/trading-bot/venv/bin/python bot.py
Restart=always
[Install]
WantedBy=multi-user.target
sudo systemctl enable tradingbot
sudo systemctl start tradingbot
sudo journalctl -u tradingbot -f # live logs
Step 8 — monitoring
Telegram bot setup karo alerts ke liye:
import requests
def telegram_alert(msg):
requests.post(
f"https://api.telegram.org/bot{TOKEN}/sendMessage",
data={"chat_id": CHAT_ID, "text": msg}
)
Improvements (homework)
- Stop-loss + target add karo
- Position sizing logic
- Multiple symbols support
- Daily loss limit / killer switch
- Backtesting module
Conclusion
Aapka pehla bot tayar hai. Yeh educational hai — production mein chalane se pehle thorough backtest, paper trade, aur risk management add karna zaroori hai. Custom production-ready bot chahiye? Hum complete system bana ke deten hain.
FAQs
Bot 24/7 chalana zaroori hai?
Equity ke liye sirf 9:15-15:30. F&O bhi market hours mein. VPS isliye chahiye taaki internet/electricity issue na ho.
Paper trade kitne din karein?
Minimum 2 hafte different market conditions mein. Live jaane se pehle confidence build hone do.
Need a custom solution?
Instacode builds production-grade software — algo trading, ecommerce, web apps. Let's talk.
Get in Touch
💬 Comments (0)
Be the first to comment 🚀