High-Speed Trading Implementation Guide
Step 1: Environment Setup
Create Project Structure
bashmkdir hft_trading
cd hft_trading
# Create virtual environment
python -m venv venv
# Activate virtual environment
# On Windows:
venv\Scripts\activate
# On Linux/Mac:
source venv/bin/activate
Install Dependencies
bash# For Flattrade
pip install NorenRestApiPy websocket-client
# For Zerodha
pip install kiteconnect
# For Mstock
pip install requests websocket-client
# Common dependencies
pip install pandas numpy python-dotenv
Create Project Files
hft_trading/
│
├── config/
│ └── credentials.env
├── brokers/
│ ├── __init__.py
│ ├── flattrade.py
│ ├── zerodha.py
│ └── mstock.py
├── strategies/
│ ├── __init__.py
│ └── momentum.py
├── utils/
│ ├── __init__.py
│ └── logger.py
└── main.py
High-Speed Trading Implementation Guide
Step 1: Environment Setup
Create Project Structure
bashmkdir hft_trading
cd hft_trading
# Create virtual environment
python -m venv venv
# Activate virtual environment
# On Windows:
venvScriptsactivate
# On Linux/Mac:
source venv/bin/activate
Install Dependencies
bash# For Flattrade
pip install NorenRestApiPy websocket-client
# For Zerodha
pip install kiteconnect
# For Mstock
pip install requests websocket-client
# Common dependencies
pip install pandas numpy python-dotenv
Create Project Files
hft_trading/
│
├── config/
│ └── credentials.env
├── brokers/
│ ├── __init__.py
│ ├── flattrade.py
│ ├── zerodha.py
│ └── mstock.py
├── strategies/
│ ├── __init__.py
│ └── momentum.py
├── utils/
│ ├── __init__.py
│ └── logger.py
└── main.py
Step 2: Configure Credentials
Create config/credentials.env
env# Flattrade Credentials
FLATTRADE_USER_ID=your_user_id
FLATTRADE_PASSWORD=your_password
FLATTRADE_TOTP_KEY=your_totp_key
FLATTRADE_API_KEY=your_api_key
FLATTRADE_VENDOR_CODE=your_vendor_code
# Zerodha Credentials
ZERODHA_API_KEY=your_api_key
ZERODHA_API_SECRET=your_api_secret
ZERODHA_USER_ID=your_user_id
ZERODHA_PASSWORD=your_password
# Mstock Credentials
MSTOCK_APP_KEY=your_app_key
MSTOCK_SECRET_KEY=your_secret_key
MSTOCK_USER_ID=your_user_id
MSTOCK_PASSWORD=your_password
Step 3: Implement Broker Connections
brokers/flattrade.py
pythonfrom NorenRestApiPy.NorenApi import NorenApi
import pyotp
import os
class FlattradeClient:
def __init__(self):
self.api = NorenApi(
host='https://piconnect.flattrade.in/PiConnectTP/',
websocket='wss://piconnect.flattrade.in/PiConnectWSTp/'
)
self.user_id = os.getenv('FLATTRADE_USER_ID')
self.password = os.getenv('FLATTRADE_PASSWORD')
self.totp_key = os.getenv('FLATTRADE_TOTP_KEY')
self.api_key = os.getenv('FLATTRADE_API_KEY')
self.vendor_code = os.getenv('FLATTRADE_VENDOR_CODE')
def login(self):
"""Login to Flattrade"""
# Generate TOTP
totp = pyotp.TOTP(self.totp_key).now()
# Login
response = self.api.login(
userid=self.user_id,
password=self.password,
twoFA=totp,
vendor_code=self.vendor_code,
api_secret=self.api_key,
imei='abc1234'
)
if response['stat'] == 'Ok':
print("Flattrade login successful!")
return True
else:
print(f"Login failed: {response}")
return False
def place_order(self, symbol, exchange, side, qty, price=0, order_type='MKT'):
"""Place order"""
response = self.api.place_order(
buy_or_sell=side, # 'B' or 'S'
product_type='I', # I=MIS, C=CNC, M=NRML
exchange=exchange, # NSE, BSE, NFO
tradingsymbol=symbol,
quantity=qty,
discloseqty=0,
price_type=order_type, # LMT, MKT, SL-LMT, SL-MKT
price=price,
trigger_price=None,
retention='DAY',
remarks='HFT_Order'
)
return response
def get_positions(self):
"""Get current positions"""
return self.api.get_positions()
def start_websocket(self, symbols, callback):
"""Subscribe to live market data"""
def event_handler_feed_update(tick_data):
callback(tick_data)
self.api.start_websocket(
order_update_callback=None,
subscribe_callback=event_handler_feed_update,
socket_open_callback=lambda: print("WebSocket connected")
)
# Subscribe to symbols
for symbol in symbols:
self.api.subscribe(f'{symbol}')
brokers/zerodha.py
pythonfrom kiteconnect import KiteConnect, KiteTicker
import os
class ZerodhaClient:
def __init__(self):
self.api_key = os.getenv('ZERODHA_API_KEY')
self.api_secret = os.getenv('ZERODHA_API_SECRET')
self.kite = KiteConnect(api_key=self.api_key)
self.kws = None
def login(self):
"""Generate login URL and get access token"""
# Step 1: Generate login URL
login_url = self.kite.login_url()
print(f"Please login here: {login_url}")
# Step 2: After login, you'll get request_token in redirect URL
request_token = input("Enter request token from redirect URL: ")
# Step 3: Generate access token
data = self.kite.generate_session(
request_token=request_token,
api_secret=self.api_secret
)
self.kite.set_access_token(data["access_token"])
print("Zerodha login successful!")
return True
def place_order(self, symbol, exchange, side, qty, price=0, order_type='MARKET'):
"""Place order"""
order_id = self.kite.place_order(
variety=self.kite.VARIETY_REGULAR,
exchange=exchange, # NSE, BSE, NFO
tradingsymbol=symbol,
transaction_type=side, # BUY or SELL
quantity=qty,
product=self.kite.PRODUCT_MIS, # MIS, CNC, NRML
order_type=order_type, # MARKET, LIMIT, SL, SL-M
price=price
)
return order_id
def get_positions(self):
"""Get current positions"""
return self.kite.positions()
def start_websocket(self, tokens, callback):
"""Subscribe to live market data"""
self.kws = KiteTicker(self.api_key, self.kite.access_token)
def on_ticks(ws, ticks):
callback(ticks)
def on_connect(ws, response):
ws.subscribe(tokens)
ws.set_mode(ws.MODE_FULL, tokens)
self.kws.on_ticks = on_ticks
self.kws.on_connect = on_connect
self.kws.connect(threaded=True)
Step 4: Create Trading Strategy
strategies/momentum.py
pythonimport numpy as np
from collections import deque
class MomentumStrategy:
def __init__(self, fast_period=5, slow_period=20):
self.fast_period = fast_period
self.slow_period = slow_period
self.price_data = {}
self.positions = {}
def on_tick(self, symbol, ltp):
"""Process each tick"""
if symbol not in self.price_data:
self.price_data[symbol] = deque(maxlen=self.slow_period)
self.price_data[symbol].append(ltp)
def calculate_ema(self, prices, period):
"""Calculate EMA"""
if len(prices) < period:
return None
prices_array = np.array(prices)
ema = prices_array[-period:].mean()
return ema
def get_signal(self, symbol):
"""Generate trading signal"""
if symbol not in self.price_data:
return None
prices = list(self.price_data[symbol])
if len(prices) < self.slow_period:
return None
fast_ema = self.calculate_ema(prices, self.fast_period)
slow_ema = self.calculate_ema(prices, self.slow_period)
if fast_ema is None or slow_ema is None:
return None
# Buy signal
if fast_ema > slow_ema and symbol not in self.positions:
return 'BUY'
# Sell signal
elif fast_ema < slow_ema and symbol in self.positions:
return 'SELL'
return None
Step 5: Main Trading Engine
main.py
pythonimport os
from dotenv import load_dotenv
import time
from brokers.flattrade import FlattradeClient
from strategies.momentum import MomentumStrategy
# Load environment variables
load_dotenv('config/credentials.env')
class TradingBot:
def __init__(self, broker='flattrade'):
self.broker_name = broker
self.broker = None
self.strategy = MomentumStrategy(fast_period=5, slow_period=20)
self.symbols = ['SBIN-EQ', 'RELIANCE-EQ', 'TCS-EQ']
def initialize_broker(self):
"""Initialize selected broker"""
if self.broker_name == 'flattrade':
self.broker = FlattradeClient()
# Add other brokers here
# Login
if self.broker.login():
print(f"{self.broker_name} initialized successfully")
else:
raise Exception("Broker login failed")
def on_tick_data(self, tick):
"""Handle incoming tick data"""
try:
symbol = tick.get('tk') # Symbol/token
ltp = tick.get('lp') # Last traded price
if symbol and ltp:
# Update strategy
self.strategy.on_tick(symbol, float(ltp))
# Get signal
signal = self.strategy.get_signal(symbol)
# Execute trade
if signal == 'BUY':
self.execute_buy(symbol, ltp)
elif signal == 'SELL':
self.execute_sell(symbol, ltp)
except Exception as e:
print(f"Error processing tick: {e}")
def execute_buy(self, symbol, price):
"""Execute buy order"""
print(f"BUY Signal: {symbol} at {price}")
response = self.broker.place_order(
symbol=symbol,
exchange='NSE',
side='B',
qty=1,
price=0,
order_type='MKT'
)
print(f"Buy order response: {response}")
self.strategy.positions[symbol] = {'price': price, 'qty': 1}
def execute_sell(self, symbol, price):
"""Execute sell order"""
print(f"SELL Signal: {symbol} at {price}")
response = self.broker.place_order(
symbol=symbol,
exchange='NSE',
side='S',
qty=1,
price=0,
order_type='MKT'
)
print(f"Sell order response: {response}")
if symbol in self.strategy.positions:
del self.strategy.positions[symbol]
def start(self):
"""Start trading bot"""
print("Starting trading bot...")
# Initialize broker
self.initialize_broker()
# Start websocket
self.broker.start_websocket(self.symbols, self.on_tick_data)
# Keep running
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print("nShutting down...")
if __name__ == "__main__":
bot = TradingBot(broker='flattrade')
bot.start()
Step 6: Run the Bot
Basic Execution
bash# Activate virtual environment
source venv/bin/activate # Linux/Mac
# or
venvScriptsactivate # Windows
# Run the bot
python main.py
With Custom Parameters
python# Modify main.py
bot = TradingBot(broker='flattrade')
bot.symbols = ['SBIN-EQ', 'RELIANCE-EQ', 'INFY-EQ', 'TCS-EQ']
bot.start()
Step 7: Testing & Monitoring
Paper Trading Mode
pythonclass TradingBot:
def __init__(self, broker='flattrade', paper_trading=True):
self.paper_trading = paper_trading
# ... rest of code
def execute_buy(self, symbol, price):
if self.paper_trading:
print(f"[PAPER] BUY: {symbol} at {price}")
return
# ... actual order placement
Add Logging
pythonimport logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('trading.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
logger.info("Trade executed: BUY SBIN @ 500")
Important Considerations
Risk Management
Always set stop-loss limits
Implement position sizing
Set maximum daily loss limits
Monitor account balance
Performance Optimization
Use compiled libraries (NumPy, Pandas)
Minimize API calls
Cache market data
Use efficient data structures
Error Handling
Handle network disconnections
Implement order retry logic
Log all errors
Set up alerts for critical failures
Compliance
Follow exchange regulations
Maintain audit logs
Respect rate limits
Test thoroughly before live trading
Troubleshooting
Common Issues
1. WebSocket Disconnection
pythondef reconnect_websocket(self):
max_retries = 5
for i in range(max_retries):
try:
self.broker.start_websocket(...)
break
except Exception as e:
print(f"Retry {i+1}/{max_retries}")
time.sleep(5)
2. Order Rejection
Check margin availability
Verify symbol format
Confirm exchange timings
Check order limits
3. Data Latency
Use dedicated server
Optimize network
Use broker's co-location services
Reduce processing overhead