Skip to content

Instantly share code, notes, and snippets.

@davassi
Created October 2, 2025 04:21
Show Gist options
  • Select an option

  • Save davassi/b1008bc30fc7ed77a831b9a73bed5054 to your computer and use it in GitHub Desktop.

Select an option

Save davassi/b1008bc30fc7ed77a831b9a73bed5054 to your computer and use it in GitHub Desktop.
Pine prompt
Here’s a ready-to-paste “super-prompt” you can give to an AI to generate a **Pine Script v6** strategy exactly as you described. It’s explicit, opinionated, and designed to trade **rarely** and **only** when the odds are stacked in one direction.
---
# Prompt to Generate Pine v6 Strategy (High-Confidence, Factor-Inspired, Low-Frequency)
You are an expert Pine Script v6 quant developer.
Write a **Pine Script v6 strategy** (not study) that trades **infrequently** and **only** under **strong** directional evidence. The system must:
* **Go LONG only** when **multiple bullish conditions** are all confirmed and **no bearish or uncertain conditions** are present.
* **Go SHORT only** when **multiple bearish conditions** are all confirmed and **no bullish or uncertain conditions** are present.
* **NEVER trade in uncertain/choppy markets.** If conditions conflict or trend strength is weak, stay flat.
* **One position at a time**, no pyramiding. Enter only at **bar close** of the signal bar. No repainting.
* Include robust **risk management** and **backtest realism**.
## Requirements
### Pine & Execution
* Use **Pine Script v6**: `//@version=6`
* Use `strategy()` with inputs for trading costs and realistic slippage.
* All signals must be generated on **confirmed bars** only; no `lookahead_on`.
* **No repainting**: avoid future leaks; use `barstate.isconfirmed` and evaluate only on bar close.
* **One trade at a time**, `pyramiding=0`.
### Symbols & Timeframes
* The code must support **any symbol** and **any timeframe**.
* Implement **multi-timeframe (MTF) regime filters**:
* **Regime TF (HTF)** input (e.g., 1h/4h/1D) for trend/volatility confirmation.
* Use `request.security()` safely (no lookahead) for HTF filters.
### Factor-Inspired Indicator Set (robust, confirmatory)
Use a combination of indicators that proxy classic “factor” exposures for a single tradable series (price/volume). Treat them as **confirmatory filters**; trades trigger **only** if all required filters align and **uncertainty filters are false**.
1. **Momentum / Trend (primary)**
* **Dual/Triple MA trend filter** (e.g., EMA fast/slow and KAMA):
* Bullish if `EMA_fast > EMA_slow` **and** price ≥ KAMA.
* Bearish if `EMA_fast < EMA_slow` **and** price ≤ KAMA.
* Implement **TEMA** as `ema(ema(ema))` (no built-in TEMA).
* **MACD** histogram regime (bullish > 0, bearish < 0) on both LTF and HTF.
* **Donchian Channel breakout bias** (e.g., close > upper for bullish bias; close < lower for bearish bias).
2. **Trend Strength**
* **ADX** filter (e.g., ADX ≥ threshold means trend is strong).
* **Supertrend** direction must agree with the momentum bias.
3. **Volatility Regime (low-vol → avoid, expansion → allow)**
* **ATR % of price** must be above a minimum (to avoid dead markets).
* **Bollinger Bandwidth** (or %B regime) to detect **squeeze**; if in squeeze + no breakout → **uncertainty**.
4. **Quality / Noise Filters (uncertainty detection)**
* **Choppiness Index** (CHOP) high → uncertain → **no trades**.
* **RSI mid-zone** filter: if RSI in neutral band (e.g., 45–55) → **uncertainty**.
* **Volume confirmation**: OBV slope or **VWAP** proximity filter—require that breakouts are **not** just thin volume spikes. If volume filter fails → **no trade**.
5. **Value / Carry Proxies (optional toggles)**
* Add inputs to optionally include **Funding Rate** or **Basis** proxies if available through the symbol feed; otherwise skip gracefully. If included, require funding-aligned bias (e.g., persistently positive funding aligns with bullish regime). Must not break on symbols without these series.
> All filters must be **inputs** with sensible defaults and ability to **toggle** each block (e.g., “Use MACD filter: true/false”).
### Trade Logic (AND-gated, high confidence)
* **LONG entry conditions (ALL must be true):**
* Momentum: EMA_fast > EMA_slow, price ≥ KAMA, MACD hist > 0 (LTF & HTF), **and** Supertrend is **UP**.
* Trend Strength: **ADX ≥ threshold**.
* Volatility: ATR% ≥ min and either BB expansion or a clean breakout (e.g., close > Donchian upper) confirmed by volume filter.
* Uncertainty filters: **CHOP below max**, RSI **outside** neutral band (e.g., RSI > 55), **no** squeeze-without-breakout state.
* Optional factor toggles (if enabled) agree (e.g., funding regime supports longs).
* No active short and no cool-down lock (see below).
* **SHORT entry conditions (ALL must be true):**
* Momentum: EMA_fast < EMA_slow, price ≤ KAMA, MACD hist < 0 (LTF & HTF), **and** Supertrend is **DOWN**.
* Trend Strength: **ADX ≥ threshold**.
* Volatility: ATR% ≥ min and either BB expansion or a clean breakdown (e.g., close < Donchian lower) confirmed by volume filter.
* Uncertainty filters: **CHOP below max**, RSI **outside** neutral band (e.g., RSI < 45), **no** squeeze-without-breakdown state.
* Optional factor toggles (if enabled) agree (e.g., funding regime supports shorts).
* No active long and no cool-down lock.
* **NO-TRADE (uncertainty) conditions (ANY true → flat, block entries):**
* ADX below threshold, **or**
* RSI in neutral band (e.g., 45–55), **or**
* CHOP above threshold, **or**
* BB squeeze with no decisive break, **or**
* Conflicting LTF vs HTF signals in trend, MACD, or Supertrend, **or**
* Volume confirmation fails (e.g., OBV slope non-confirming).
### Position Management & Debounce
* **One position at a time**; on opposite signal, **close & flip only if** a strict **“flip guard”** passes:
* Require **minimum bars in position** (e.g., `minBarsInTrade`) before exits or flips.
* Require **“direction lock”**: after closing a trade, enforce a **cool-down** (e.g., N bars) where no new entries are allowed.
* Optional **time-of-day/session filter** input; skip entries in illiquid hours if desired.
### Risk Management
* Position size: input as **% of equity** or fixed contracts.
* **Initial Stop-Loss**: ATR-based (e.g., `SL = entry ± k * ATR`) and **hard** stop.
* **Take-Profit**: ATR-multiple (e.g., 2–4× ATR) **OR** a **trailing stop** (ATR-based).
* Include **breakeven rule**: after price moves +X ATR in favor, move stop to breakeven.
* Include an optional **time-stop** (max bars in trade).
* All exits must be placed via `strategy.exit()` with clear names.
* Inputs for **commission** (percent or per-contract) and **slippage** ticks.
### Inputs (make configurable, with robust defaults)
* MAs: lengths for `EMA_fast`, `EMA_slow`, and `KAMA` length.
* MACD: fast, slow, signal lengths.
* Supertrend: ATR length, multiplier.
* ADX: length & threshold.
* Donchian: lookback length.
* Bollinger: length & stdev; bandwidth threshold; neutral `%B` band.
* ATR: length and ATR% minimum for “tradable”.
* RSI: length; neutral band (e.g., 45–55).
* CHOP: length; max allowed.
* OBV/VWAP filter toggles and parameters.
* MTF: Regime TF string; enable/disable HTF checks.
* Debounce: `minBarsInTrade`, `cooldownBars`, and optional `minBarsSinceFlip`.
* Risk: `riskPct`, `atrSLmult`, `atrTPmult`, `trailATRmult`, `breakevenATR`, `timeStopBars`.
* Costs: `commissionType/Value`, `slippageTicks`.
* Sessions: optional session string.
### Plotting & Debug
* Plot:
* EMAs, KAMA, Supertrend direction, Donchian bands, Bollinger bands.
* ADX with threshold line, CHOP with threshold, RSI with neutral band highlights.
* MACD histogram (separate pane).
* Plot **background colors** for regimes: green when “bullish-qualified,” red when “bearish-qualified,” gray when **uncertain** (no-trade).
* Add a **table** showing: HTF trend, ADX, CHOP, ATR%, RSI state, volume confirmation, and whether entries are permitted.
* Use `var` for persistent state where helpful; comment code thoroughly.
### Backtest Hygiene
* `calc_on_every_tick = false`, `process_orders_on_close = true`.
* Handle **commission** and **slippage** realistically.
* **No** use of future-knowledge functions or repaint-prone constructs.
* Use **`strategy.risk.max_drawdown`** and show key performance in a summary table (if feasible in Pine).
* Provide **clear alerts** (`alertcondition`) for Long/Short entries and exits.
### Acceptance Tests (must pass)
* On a choppy symbol/timeframe (e.g., crypto 5–15m), the strategy spends **most time flat**; trades are **rare**.
* When ADX < threshold or CHOP high or RSI neutral, **no entries** occur.
* Entries occur **only** when **all** bullish (for long) or **all** bearish (for short) filters align on both LTF and HTF.
* The code compiles in **Pine v6**, does **not repaint**, and runs on arbitrary symbols without errors (even if funding rate proxies are disabled/not available).
* Inputs allow users to relax/tighten thresholds for more/less trading frequency.
### Deliverables
* Full Pine v6 code with all inputs, plots, alertconditions, and exhaustive inline comments.
* A short README comment at the top explaining how to tune thresholds to **reduce trades further** if needed (e.g., increase ADX threshold, widen RSI neutral band, require Donchian breakout + BB expansion concurrently, lengthen HTF).
---
**Important design intent:** Favor **precision over recall**—skip marginal setups. The default configuration must **trade as little as possible** while aiming for **high-probability entries only**.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment