from kiteconnect import KiteConnect
import logging
import time
# Initialize Kite Connect API
api_key = "your_api_key"
api_secret = "your_api_secret"
access_token = "your_access_token"
kite = KiteConnect(api_key=api_key)
kite.set_access_token(access_token)
logging.basicConfig(level=logging.INFO)
# Configuration
account_balance = 100000 # Account balance in rupees
max_mtm_percent_loss = -0.02 # -2% MTM loss threshold
max_mtm_percent_profit = 0.02 # 2% MTM profit threshold
max_trades = 10 # Maximum number of trades allowed
trade_count = 0 # Initialize trade count
# Variables to track MTM and trades
def get_positions():
"""Fetch current positions."""
try:
positions = kite.positions()
return positions
except Exception as e:
logging.error(f"Failed to fetch positions: {e}")
return None
def calculate_mtm(positions):
"""Calculate MTM based on current positions."""
mtm = 0
for position in positions['day']:
mtm += position['pnl']
return mtm
def square_off_positions():
"""Square off all open positions."""
try:
positions = kite.positions()
for position in positions['day']:
if position['quantity'] != 0:
order_type = kite.TRANSACTION_TYPE_SELL if position['quantity'] > 0
else kite.TRANSACTION_TYPE_BUY
kite.place_order(
tradingsymbol=position['tradingsymbol'],
exchange=position['exchange'],
transaction_type=order_type,
quantity=abs(position['quantity']),
order_type=kite.ORDER_TYPE_MARKET,
product=position['product'],
variety=kite.VARIETY_REGULAR
)
logging.info("All positions squared off.")
except Exception as e:
logging.error(f"Failed to square off positions: {e}")
def activate_kill_switch():
"""Activate the kill switch by cancelling all open orders and squaring off
positions."""
try:
# Cancel all open orders
open_orders = kite.orders()
for order in open_orders:
if order['status'] == 'TRIGGER PENDING':
kite.cancel_order(order_id=order['order_id'],
variety=order['variety'])
logging.info("Kill switch activated: All open orders cancelled.")
# Square off all positions
square_off_positions()
except Exception as e:
logging.error(f"Failed to activate kill switch: {e}")
def place_trade(tradingsymbol, transaction_type, quantity):
"""Place a trade with given parameters."""
try:
order_id = kite.place_order(
tradingsymbol=tradingsymbol,
exchange="NSE",
transaction_type=transaction_type,
quantity=quantity,
order_type=kite.ORDER_TYPE_MARKET,
product=kite.PRODUCT_MIS,
variety=kite.VARIETY_REGULAR
)
logging.info(f"Order placed successfully: {order_id}")
return order_id
except Exception as e:
logging.error(f"Failed to place order: {e}")
return None
def main():
global trade_count
positions = get_positions()
if positions is None:
return
mtm = calculate_mtm(positions)
mtm_percent = mtm / account_balance
if mtm_percent <= max_mtm_percent_loss or mtm_percent >=
max_mtm_percent_profit:
logging.info(f"MTM limit reached: {mtm_percent * 100:.2f}%. Activating kill
switch.")
activate_kill_switch()
return
if trade_count >= max_trades:
logging.info("Trade count limit reached. Activating kill switch.")
activate_kill_switch()
return
# Example dynamic strategy: Buying Bank NIFTY options (replace with your logic)
# Note: Ensure you have appropriate logic to decide the tradingsymbol and
quantity.
bank_nifty_call = "BANKNIFTY21JUN36500CE"
bank_nifty_put = "BANKNIFTY21JUN36500PE"
# Buying a Call option
call_order_id = place_trade(bank_nifty_call, kite.TRANSACTION_TYPE_BUY, 25)
if call_order_id:
trade_count += 1
# Buying a Put option
put_order_id = place_trade(bank_nifty_put, kite.TRANSACTION_TYPE_BUY, 25)
if put_order_id:
trade_count += 1
logging.info(f"Current MTM: {mtm}, MTM Percent: {mtm_percent * 100:.2f}%, Trade
Count: {trade_count}")
if __name__ == "__main__":
while True:
main()
time.sleep(60) # Run the script every 60 seconds