From `nse-options-mcp-research/signal_gate.py` — why a trading system should say "I don't know" most of the time, and the exact rule I coded. If your system always says BUY/SELL, ye padho.


The trap


Retail systems har bar signal dete hain. Confidence 55% pe bhi "BUY" bol dete hain. Result: V1 paper trading mei **31.6% win, −₹90.3k PnL**. The fix isn't a better model — it's a **gate** that refuses to vote when evidence is thin.


What a signal gate does


Input: market snapshot + session history. Output: ek decision:

  • `TRADE` — sufficient evidence, session/hours/holiday rules pass
  • `NO_TRADE` — reason ke saath: `INSUFFICIENT_HISTORY`, `NO_LIVE_SOURCE`, `STALE_FEED`, `HOLIDAY`, `LOW_CONFIDENCE`

  • Gate model se pehle aata hai. Model kuch bhi bole, gate veto kar sakta hai.


    The ≥20 sessions rule


    Guide ka hard rule: **no trade signal until ≥20 recorded sessions** in DuckDB history. Why? 1-2 sessions ka "pattern" noise hai. 20+ sessions se basic regime/volatility stats bante hain.


    
    MIN_SESSIONS = 20
    sessions = db.execute(
        "SELECT count(DISTINCT session_date) FROM market_raw").fetchone()[0]
    if sessions < MIN_SESSIONS:
        return ("NO_TRADE", "INSUFFICIENT_HISTORY", f"{sessions}/{MIN_SESSIONS}")
    

    Other gates


  • **Live source check** — MCP down hai toh NO_TRADE (stale data pe trade nahi).
  • **Holiday/weekend** — NSE closed → NO_TRADE.
  • **Stale feed** — last snapshot > 10 min old → NO_TRADE.
  • **Kill-switch** — any hard failure → trip, block all trades.

  • Now() IST handling


    
    from datetime import datetime, timedelta
    now_ist = (datetime.utcnow() + timedelta(hours=5, minutes=30)).replace(tzinfo=None)
    

    DB naive IST store karta hai, isliye naive compare. Pehle aware/naive mismatch se tz error aata tha — fix kiya.


    Real result


    Mera system abhi **NO_TRADE / INSUFFICIENT_HISTORY** deta hai (sirf 1 session). Ye sahi hai. 5-min recorder 4 weeks mei 20+ sessions build karega, tab real probability niklegi.


    Why this matters


    Ek system jo NO_TRADE 90% bolta hai aur sahi 10% mei trades kare = survivable. Ek system jo har bar trade kare = margin call. Gate pehle, model baad mei.


    Comparison


    | Without gate | With gate |

    |-|--|

    | Always signals | Signals only when ready |

    | 55% conf trades |

    | −₹90k PnL | Protected capital |

    | False confidence | Honest uncertainty |


    Design principles


    1. Gate model se independent hona chahiye (model bias na le).

    2. Har reason logged hona chahiye (audit trail).

    3. Kill-switch hard fail pe trip kare.

    4. Session/holiday rules non-bypassable.


    FAQ


    **Q: 20 sessions kyun?** Basic stats ke liye minimum sample. Kam mei noise.

    **Q: Gate model ko override kar sakta?** Haan, NO_TRADE har time model veto karega.

    **Q: Live source down toh?** NO_TRADE, stale pe trade nahi.

    **Q: Kill-switch manual?** Auto trip on hard failure + manual bhi.


    Common mistakes


    1. Gate ko model ke baad lagana — pehle lagao.

    2. Session count ignore karna — 1 session pe trade karna.

    3. Stale feed allow karna — 10 min old data pe trade.

    4. Kill-switch na hona — hard fail pe bhi trade.


    What I learned


    V1 mei gate nahi tha, isliye 31.6% win pe bhi trade ho raha tha. V2 mei gate first line of defense hai. Ab system 4 weeks tak NO_TRADE bolega — wo loss nahi, protection hai.


    *Research only. Not investment advice.*


    Deep dive: gate logic in code


    
    def evaluate(snapshot, db):
        # 1. Live source
        if not snapshot or snapshot.get("stale"):
            return ("NO_TRADE", "NO_LIVE_SOURCE", None)
        # 2. Session count
        sessions = db.execute(
            "SELECT count(DISTINCT session_date) FROM market_raw").fetchone()[0]
        if sessions < MIN_SESSIONS:
            return ("NO_TRADE", "INSUFFICIENT_HISTORY", f"{sessions}/{MIN_SESSIONS}")
        # 3. Holiday/weekend
        if is_nse_holiday(now_ist):
            return ("NO_TRADE", "HOLIDAY", None)
        # 4. Stale feed
        if (now_ist - snapshot["ts"]).seconds > 600:
            return ("NO_TRADE", "STALE_FEED", None)
        # 5. Model confidence
        conf = model.predict(snapshot)
        if conf < 0.60:
            return ("NO_TRADE", "LOW_CONFIDENCE", conf)
        return ("TRADE", "OK", conf)
    

    Session build timeline


    5-min recorder 2 symbols × ~124 rows = ~250 rows/session. 20 sessions ≈ 4 weeks market days. Tab tak system data collect karta hai, trade nahi.


    Why 0.60 confidence threshold


    V1 mei 55-64% confidence pe trade hue, sab loss. 0.60 conservative start hai. Jab data build hoga, calibration se threshold tune karna (isotonic).


    Kill-switch design


    
    def killswitch_tripped(reason):
        db.execute("INSERT INTO scan_log VALUES (?, 'KILLSWITCH', ?)",
                   (now_ist, reason))
        return ("NO_TRADE", "KILLSWITCH", reason)
    

    Hard failure (MCP crash, DB corrupt) pe trip. Manual reset only.


    Real-world analogy


    Gate ek bouncer hai club ke bahar. Model andar dance karna chahta hai, bouncer check karta hai: ID hai? (session) Source legit? (live) Time sahi? (holiday) Bouncer na bola toh andar nahi jaane deta.


    My experience


    Pehle bina gate ke model ko bharosa tha. 31.6% win dekh kar samjha ki problem model nahi, discipline thi. Gate ne discipline enforce kiya — ab system 4 weeks chup rahega, jo sahi hai.


    *Research only. Not investment advice.*


    Extended FAQ


    **Q: Gate model se independent kyun?** Model apna bias defend karega. Gate neutral check kare.

    **Q: 20 sessions bad mei kya?** Walk-forward validator real signal nikalta hai, tab TRADE allow.

    **Q: Confidence threshold tune kaise?** Calibration set pe isotonic regression, false-positives minimize.

    **Q: Manual override?** Sirf emergency kill-switch, normal NO_TRADE auto.


    Common pitfalls (retail)


    1. **Always-on signals** — 55% pe bhi trade. Capital wipe.

    2. **No session gate** — 1 day data pe pattern seekh ke trade.

    3. **Stale data trade** — 30 min purani snapshot pe decision.

    4. **No kill-switch** — crash mei bhi orders.


    Comparison: my V1 vs V2


    | | V1 | V2 |

    |--|-|-|

    | Gate | None | 5-layer |

    | Session min | 0 | 20 |

    | Result | −₹90.3k | Protected |

    | Confidence | 55% trades | <60% NO_TRADE |


    What you should build


    Agar tum apna system bana rahe ho:

    1. Gate model se pehle lagao.

    2. Session minimum set karo (20+).

    3. Live source + stale check.

    4. Kill-switch.

    5. Har decision log karo.


    Closing


    Signal gate trading system ka seatbelt hai. Bina uske tum 31.6% win pe bhi trade karoge aur paise gawayoge. NO_TRADE bolna seekho — wo weakness nahi, strength hai.


    *Research only. Not investment advice. SEBI compliance separate topic.*


    Worked scenario


    Monday 09:35 IST. Snapshot aaya. Gate evaluate:


    1. Live source? YES (MCP up).

    2. Sessions? 1/20 → **NO_TRADE / INSUFFICIENT_HISTORY**. Stop. Model call hi nahi hua.


    Week 4, 21 sessions. Gate:

    1. Live source? YES.

    2. Sessions? 21/20 → pass.

    3. Holiday? No.

    4. Stale? 3 min old → pass.

    5. Confidence? 0.67 → **TRADE**.


    Ye difference hai gate wale aur bina gate wale mei.


    Why I coded it this way


    V1 ke sabse dardnaak loss tab aaye jab 1-2 sessions ka data tha aur model confident tha. Gate ne wo band kar diya. Ab system 4 weeks discipline se data collect karega, fir trade karega.


    Recommendations


    1. Gate ko model se alag rakho (separate module).

    2. Har reason log karo — audit trail future debug ke liye.

    3. Threshold conservative rakho pehle (0.60), bad mei tune.

    4. Kill-switch non-bypassable ho.


    *Research only. Not investment advice.*


    The philosophy


    Trading mei "not trading" bhi ek position hai. Zyada traders isko bhool jate hain. Gate system ko force karta hai ki wo apni limits jane. 90% time NO_TRADE bolna = 90% time capital safe.


    Summary


    Signal gate = system ka seatbelt. 5 layers (live source, sessions≥20, holiday, stale, confidence≥0.60) + kill-switch. V1 bina gate ke −₹90k gaya, V2 gate ke saath protected. Build it first, model later.


    *Research only. Not investment advice. SEBI compliance separate topic.*



    Action plan

    1. Model se pehle gate likho.

    2. Session minimum 20 rakho.

    3. Live source + stale check lagao.

    4. Kill-switch banao.

    5. Har decision log karo.


    Bina gate ke mat trade karo — V1 ne sikha diya ye.



    Agar tumhare system mei bhi har bar signal aa raha hai, gate nahi hai. 5 layers lagao, dekho kitne signals survive karte hain. Shayad 90% NO_TRADE ho — wo hi sahi hai.



    Final note

    Gate design mei sabse zaroori: model ko veto power dena. Model chahe jitna confident ho, gate NO_TRADE bol sakta hai. Ye hierarchy retail systems mei missing hoti hai, aur isliye woh blow up hote hain.



    *Research only. Not investment advice.*


    Why I'm sharing this


    Zyada "AI trading" content fake 90% accuracy bechta hai. Mera system abhi NO_TRADE de raha hai by design — wo honest hai. Gate lagana hi wo cheez hai jo retail ko pro bana ti hai. Build it, respect it.


    *Research only. Not investment advice. SEBI compliance separate topic.*



    Next: hum isi gate + data pe walk-forward validator chalayenge jab 20 sessions build honge. Tab real signals milengi.



    Build the gate first. Your capital will thank you.





    More From Shakti Tiwari


  • 🌐 **Websites:** [shaktitiwari.github.io/shakti-tiwari-nse](https://shaktitiwari.github.io/shakti-tiwari-nse) · [OptionTradingWithAI.in](https://optiontradingwithai.in)
  • 📚 **Books:** *Build Your Own AI* ([Amazon](https://www.amazon.in/dp/B0HBBFKDQF)) · *Option Trading with AI* ([Amazon](https://www.amazon.in/dp/B0H9ZNTBPK))
  • 💬 **Community:** [Discord](https://discord.gg/shaktitiwari) · [X](https://x.com/shaktitiwari) · [about.me](https://about.me/shaktitiwari)
  • 💻 **Code:** [GitHub/shaktitiwari](https://github.com/shaktitiwari)
  • 🏛️ **Entity:** [Wikidata Q140689249](https://www.wikidata.org/wiki/Q140689249)
  • Educational only — not SEBI-registered investment advice. NISM-Series-XII certified; not a SEBI-registered Research Analyst. Content is educational only.

    Home | About