Order Execution & Risk Controls

Robust automated trading requires careful handling of order parameters, errors, and risk limits.

3. Order Execution Best Practices

Product Types

MIS (Intraday): Requires square-off before market close (approx 3:20 PM IST).

NRML (Overnight): Used for carry-forward positions in Futures & Options.

CNC (Delivery): For equity holdings.

Order Types

MARKET: Fills immediately. Vulnerable to slippage in illiquid contracts.

LIMIT: Fills at specified price. Safer but may miss entries.

SL-M: Market order triggered at a stop price (mostly for exits).

4. Risk Management Layer

  • Max Loss/Day: Check P&L before every order. Stop trading if daily limit is hit.
  • Quantity Limits: Hard-code max quantity per order to prevent "fat-finger" errors from algorithms.
  • Market Hours: Reject orders outside 9:15 AM - 3:30 PM to avoid rejection from broker.
  • Kill Switch: Have a manual override button (e.g., a file flag or admin API) to stop all trading instantly.

5. Reliability & Ops

  • Token Rotation: Zerodha access tokens expire daily. Automate the login flow or manually update the `.env` every morning.
  • Logging: log every incoming webhook and outgoing order response. This is crucial for debugging "Why didn't my trade fire?".
  • Idempotency: If TradingView sends duplicate alerts, use the `alert_id` to prevent double entry.

6. Handling Large Orders (Iceberging)

If you are trading large quantities, placing a single market order can cause significant slippage. "Iceberging" or "Slicing" splits one large order into smaller chunks.

# Pseudocode logic for order slicing
target_qty = 5000
slice_size = 500
remaining = target_qty

while remaining > 0:
    current_batch = min(slice_size, remaining)
    kite.place_order(..., quantity=current_batch)
    remaining -= current_batch
    time.sleep(1) # wait for liquidity to refill
                

Note: Zerodha has frozen limits per instrument (e.g., Nifty Futures has a max qty per order). You must slice orders if your quantity exceeds these freeze limits, otherwise the API will reject the order.

7. Common Error Codes Reference

Understanding these codes helps you write better error handling logic.

InputException

The input parameters (symbol, quantity, etc.) are invalid. E.g., sending quantity=-5 or a misspelled symbol.

OrderException

The order was rejected by the exchange or RMS. Common reasons: Insufficient funds, Market closed, or Outside circuit limits.

NetworkException

The connection to the Kite server failed. This is transient; retry the request.

DataException

Bad response from the server, potentially a parsing error. Check if the API endpoint has changed.