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 | <threshold = NO_TRADE |
| −₹90k PnL | Protected capital |
| False confidence | Honest uncertainty |
Design principles
- Gate model se independent hona chahiye (model bias na le).
- Har reason logged hona chahiye (audit trail).
- Kill-switch hard fail pe trip kare.
- 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
- Gate ko model ke baad lagana — pehle lagao.
- Session count ignore karna — 1 session pe trade karna.
- Stale feed allow karna — 10 min old data pe trade.
- 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)
- Always-on signals — 55% pe bhi trade. Capital wipe.
- No session gate — 1 day data pe pattern seekh ke trade.
- Stale data trade — 30 min purani snapshot pe decision.
- 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:
- Gate model se pehle lagao.
- Session minimum set karo (20+).
- Live source + stale check.
- Kill-switch.
- 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:
- Live source? YES (MCP up).
- Sessions? 1/20 → NO_TRADE / INSUFFICIENT_HISTORY. Stop. Model call hi nahi hua.
Week 4, 21 sessions. Gate:
- Live source? YES.
- Sessions? 21/20 → pass.
- Holiday? No.
- Stale? 3 min old → pass.
- 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
- Gate ko model se alag rakho (separate module).
- Har reason log karo — audit trail future debug ke liye.
- Threshold conservative rakho pehle (0.60), bad mei tune.
- 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
- Model se pehle gate likho.
- Session minimum 20 rakho.
- Live source + stale check lagao.
- Kill-switch banao.
- 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 · OptionTradingWithAI.in
- 📚 Books: Build Your Own AI (Amazon) · Option Trading with AI (Amazon)
- 💬 Community: Discord · X · about.me
- 💻 Code: GitHub/shaktitiwari
- 🏛️ Entity: Wikidata Q140689249
Top comments (0)