Re: High speed trading code in python, using flattrade | zerodha | mstock
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}')