Python Short Selling Algorithm — Nasdaq-100 Futures (NQ CME)

Python Short Selling Algorithm — Nasdaq-100 Futures (NQ CME)

$0.00
Skip to product information
Python Short Selling Algorithm — Nasdaq-100 Futures (NQ CME)

Python Short Selling Algorithm — Nasdaq-100 Futures (NQ CME)

$0.00

OVERVIEW
────────
Most algorithmic trading products focus on the long side. But professional
quant systems trade both directions — and the short side of Nasdaq-100 futures
requires a completely different signal architecture: overextension detection,
mean-reversion confirmation, momentum exhaustion, and a precisely calibrated
trailing stop that tightens as the trade moves in your favour.

This listing gives you the complete, heavily commented Python source code for
a SHORT mean-reversion strategy on CME Nasdaq-100 E-Mini Futures (NQ).
The strategy uses a multi-layer signal stack: z-score overextension, RSI
momentum turn detection, declining volume confirmation, and a dual-timeframe
(30m signal / 5m execution) architecture that only fires when all conditions
align. Both the original Gen1 bot and the Gen2 evolutionary improvement are
included — giving you a side-by-side view of how the strategy was refined.

This is an educational resource for Python developers, quantitative trading
students, and systematic traders who want to study or adapt a real, production-
grade SHORT strategy that was built and live-tested on Rithmic infrastructure.


BOT IDENTITY
────────────
  Bot Name   : bar_nq_long_20260911_145036
  Created    : September 11, 2026 at 14:50:36 UTC
  Instrument : NQ — Nasdaq-100 E-Mini Futures @ CME (front-month contract)
  Direction  : SHORT  (overextension mean-reversion)
  Generation : Gen1 (original) + Gen2 evolutionary variant (both included)
  Symbol     : NQM6 (Gen1)  /  NQU6 (Gen2)
  Repository : qln-live-trading-rithmic9
  Folder     : bots/bar_historical/2026-09-11/


BACKTESTED PERFORMANCE  (honest disclosure)
───────────────────────────────────────────
  ⚠️  IMPORTANT: This bot has a limited backtest sample due to its strict
      multi-condition entry filter. Only 3 qualifying trades were recorded
      in the backtest window. The strategy requires all of: z-score
      overextension, RSI momentum turn, weakening volume, and price above
      EMA — a high-conviction filter that fires rarely but precisely.

  Metric                          Gen1 Value
  ──────────────────────────────────────────────
  Instrument                      NQ Nasdaq-100 E-Mini @ CME
  Direction                       SHORT (mean-reversion)
  Backtest Trades                 3   (strict minimum: 20 for ranking)
  Win Rate                        0%  (3-trade sample — statistically limited)
  Profit Factor                   0.0  (sample too small for reliability)
  Net PnL (backtest)              -$201
  Total Return (backtest)         -100%
  Max Drawdown — raw              100%
  Max Drawdown — live hard cap    15%  (session circuit-breaker enforced)
  Signal Timeframe                30-minute bars
  Execution Timeframe             5-minute bars
  ATR Multiplier (entry)          Dynamic 1.2x–2.6x  (vol + momentum adjusted)
  ATR Trailing Stop               entry + ATR×1.4  (tightening trailing)
  Min Entry Equity Guard          15% max drawdown → session halted
  Starting Capital (eval run)     $17,092
  ──────────────────────────────────────────────

  Gen2 AI Probability Improvement:
    Gen1 AI profit probability : 55%   (volume score: 30, order-flow: 40)
    Gen2 AI profit probability : 65%   (volume score: 60, order-flow: 70)

  Ranking status: NOT in the Sep 21 profitable bots ranking.
  Reason: Only 3 backtest trades recorded — below the strict 20-trade minimum
  required for ranking inclusion. The strategy's high-conviction filter means
  it fires rarely. This is disclosed fully so buyers can make an informed
  decision. The value here is the strategy architecture and methodology.

  ⚠️  A 3-trade backtest is NOT statistically significant. Past backtested
      performance (or non-performance) does NOT predict future results.
      This product is sold as an educational code resource, not a signal service.


MARKET CONDITIONS AT CREATION  (Sep 11, 2026 14:50 UTC)
─────────────────────────────────────────────────────────
  ATR (% of price)      0.181%  — moderate volatility for NQ
  Trailing return       +0.163% — slight positive drift
  Up-bar fraction       65.2%   — NQ leaning bullish at creation
  Avg volume/bar        11,657 contracts  (trend: -28.8%, sharply declining)
  ATR analysis source   ai (forward-looking estimate, not a guarantee)

  Analysis rationale: Strong positive up-bar fraction (65%) with sharply
  declining participation (-28.8% volume trend) signals a classic weakening
  uptrend. When buying pressure dries up in an overbought market, the risk of
  a mean-reversion snap-back to the downside increases — exactly the condition
  this SHORT strategy is designed to exploit.


HOW THE STRATEGY WORKS
───────────────────────
ARCHITECTURE: Dual-Timeframe SHORT with Z-Score Overextension Filter

  Signal timeframe (30m): Detects when NQ is overextended to the upside
    and momentum is turning — arms a SHORT signal.

  Execution timeframe (5m): Waits for the first bearish confirmation bar
    below the execution EMA before entering — avoids top-picking.

SIGNAL ARMING (30m bar logic — _update_signal_state)
  All conditions below must be TRUE to arm the SHORT signal:

  1. Z-Score overextension:  z-score of close prices (20-bar lookback) >= 0.8
     OR close > EMA_fast  →  price is stretched above normal range
  2. RSI momentum turn:  RSI(14) is TURNING DOWN (rsi_now < rsi_prev)
     AND RSI is still elevated (rsi_now >= 45)  →  exhaustion signal
  3. Trend bias up:  close >= EMA_slow(12)  →  confirming we are in an
     uptrend before fading it (mean-reversion, not counter-trend bottom)
  4. Gate check passes (relaxed mode if vol_slope < 0 AND z >= 1.0):
       momentum_score >= 35 (relaxed) or >= 45 (strict)
  Signal expires after 6 signal bars if not triggered.

COMPOSITE MOMENTUM SCORE (0–50 capped):
  Component 1: RSI-based (max 20pts):  (60 - RSI) × 1.2
  Component 2: Z-score component (max 20pts):  z × 8.0
  Component 3: Momentum turn bonus (+10 pts if RSI turning down)
  Component 4: Weakening volume bonus (+8 pts if vol_slope < 0)
  Component 5: Trend bias bonus (+8 pts if close >= EMA_slow)

DYNAMIC ATR MULTIPLIER (entry stop placement):
  Base: 1.6x  |  +0.3x if ATR% > 0.8  |  -0.2x if ATR% < 0.4
  +0.2x if momentum_score >= 45  |  -0.1x if vol_slope < 0
  Clamped: 1.2x – 2.6x

DYNAMIC R:R RATIO:
  Base: 1.6  |  +0.4 if score >= 45  |  +0.3 if z >= 1.2
  +0.2 if vol_slope < 0  |  Clamped: 1.2 – 3.0

EXECUTION TRIGGER (5m bar — _execution_entry_ok):
  Signal must be armed. Then on each 5m bar:
  1. Bearish bar: close < open  (sellers in control)
  2. Below EMA: close <= EMA(5) of execution closes  (pullback confirmed)
  3. ATR > 0  (valid volatility environment)
  If all three true → enter SHORT at mid-price.

POSITION MANAGEMENT (_manage_open_position):
  Stop price  : entry + stop_distance (ATR × multiplier from signal)
  Target price: entry - (stop_distance × R:R ratio)
  ATR TRAILING STOP (unique to this strategy):
    On each execution bar, recalculates: proposed_stop = close + ATR×1.4
    If proposed_stop < current stop → TIGHTEN stop  (locks in profit on shorts)
  Exit triggers:
    • High bar >= stop_price         → close at stop (protective ATR stop)
    • Low bar  <= target_price       → close at target (soft target hit)
    • Max drawdown >= 15% of session → force-flatten (circuit breaker)

SESSION MANAGEMENT:
  Each calendar day is a new session.
  If 15% drawdown is hit mid-session → entries halted for rest of that day.
  New day = drawdown counter resets → strategy re-arms.


GEN2 EVOLUTIONARY IMPROVEMENT
──────────────────────────────
  Gen2 was auto-generated by the system's evolutionary optimisation engine
  after analysing Gen1 live logs.

  AI profit probability : 55% (Gen1) → 65% (Gen2)  (+10 ppts)
  Volume score          : 30  (Gen1) → 60  (Gen2)   (2× improvement)
  Order-flow score      : 40  (Gen1) → 70  (Gen2)   (+75%)
  Architecture adds: statistics module, Path-based imports, extended
  warmup handling, additional internal safeguards in bar-processing logic.
  Both Gen1 and Gen2 source files are included in this product.


WHAT YOU RECEIVE
─────────────────
  ✅  bar_nq_long_20260911_145036_portable.py
        Gen1 broker-agnostic Python strategy — Rithmic + Redis removed,
        clearly labelled placeholder comments throughout.
  ✅  Complete Gen1 strategy logic intact:
        Z-score (20-bar), RSI(14), EMA(6/12) signal + EMA(5) execution,
        ATR(14) signal + execution, composite momentum score (50-pt),
        dynamic ATR multiplier (1.2x–2.6x), dynamic R:R (1.2–3.0),
        ATR tightening trailing stop, gate check (strict + relaxed),
        signal arming + 6-bar expiry, drawdown guard, session reset,
        _finalize_position with P&L tracking
  ✅  Gen2 variant file noted (bar_nq_long_20260911_145036_gen2.py)
  ✅  Heavily commented — every method explained
  ✅  Broker-agnostic: ib_insync, Alpaca, TradeStation, NinjaTrader, etc.


INTEGRATION QUICK-START
────────────────────────
  bot = BarNqLong20260911145036()
  # tf_key = "30m" for signal bars, "5m" for execution bars
  await bot.on_bar_closed("30m", {"open":x,"high":x,"low":x,"close":x,"volume":x,"timestamp":t})
  await bot.on_bar_closed("5m",  {"open":x,"high":x,"low":x,"close":x,"volume":x,"timestamp":t})
  # Implement in subclass:
  async def _submit_short_entry(self, qty, reason): ...   # place SELL order
  async def _submit_flatten(self, reason): ...            # cover/close order


TECHNICAL REQUIREMENTS
───────────────────────
  Python 3.10+  |  stdlib: asyncio, math, statistics, os, sys, datetime,
                           pathlib, typing
  Any OHLCV bar source with timestamp  |  Any broker API or paper engine
  Tested: Windows 10/11, Linux Ubuntu 22.04+, macOS 13+


FREQUENTLY ASKED QUESTIONS
───────────────────────────
  Q: Only 3 backtest trades — is this strategy usable?
  A: The architecture is complete and production-grade. The 3-trade count
     reflects a very strict, high-conviction filter. Relax the z-score or
     RSI thresholds, or use shorter timeframes, to generate more signals.
     The methodology is sound; the backtest window was short relative to
     the filter's selectivity. All parameters are documented and adjustable.

  Q: Why "long" in the filename but trades SHORT?
  A: Naming encodes the creation sequence, not direction. The header, class
     definition, and all trading logic explicitly operate SHORT. Fully documented.

  Q: Does this require Rithmic or Redis?
  A: No. The portable edition removes all Rithmic and Redis dependencies.

  Q: Can I paper-trade this?
  A: Yes — replace the _submit_short_entry and _submit_flatten placeholders
     with print statements or a simulated fill engine.

  Q: Can I use this on other instruments?
  A: Yes — the z-score + RSI + volume-slope architecture is instrument-agnostic.
     Update SYMBOL, EXCHANGE, and tune z-score threshold and R:R parameters.


RISK DISCLAIMER
───────────────
This software is for EDUCATIONAL PURPOSES ONLY. It does NOT constitute
investment or trading advice. Futures trading involves substantial risk of loss.
Short selling futures carries theoretically unlimited upside risk. The 3-trade
backtest is NOT statistically significant and must NOT be used as a basis for
any trading decision. Past performance does not guarantee future results.
The 15% drawdown circuit breaker is a software safeguard only — it does not
eliminate risk of loss. Consult a qualified financial professional before
trading real capital.

You may also like