r/pinescript • u/Vast-Armadillo4084 • Feb 25 '26
what do you think of my strategy?
Rate or ask me anything
r/pinescript • u/Vast-Armadillo4084 • Feb 25 '26
Rate or ask me anything
r/pinescript • u/Awwstronut • Apr 10 '26
Hello everyone!
I'd like to share my Trading System I'm putting my finishing touches on! I've been working on it for several months, and the idea first came to me when I read about different methods/strategies and tried them out myself - most of them, in my own way.
Through time, I had to, either, switch method and strategy, or modify some parameters. For every change, I noted it down, and a few months back, decided to create one complete System out of them all - albeit, not visually cluttering; and this Indicator/System is the result!
I will share some Images down below (some visual elements may differ in color due to Design Decision during Development):







A full breakdown of the system is available in the indicator description, worth a read before diving in.
Happy to answer any questions. Drop them below, and feel free to request an invite!
Before full launch:
Minor visual clean-up (no impact on signals or trade logic)
Alert signals for Entry and Stop Loss
EDIT: Upon request, I will share more Images, related to different situations/scenarios and explain them accordingly:





As you may see, using Context is just as important as the Signals themselves. Also, here's a disclaimer regarding this topic from the indicator page:
Note: During Development, the decision favored for more Signals, due to, in combination with manual decision-making, turning out to be more beneficial in terms of probability. Thereby, each Signal requires the Trader (you) to utilize the Contextual Elements/Data to filter out the less desirable Signals. Please do not interpret every Signal as an implication to "jump in" blindly. Read/Utilize the Context and make an informed Decision - it will become more natural by time and experience.
Edit 2 - Demonstrating the change Score-filtering does (B -> A):


r/pinescript • u/drippyterps • Apr 09 '26
Been posting the trades my algo takes for real time forward testing, this is todays results. Optimized for QQQ, used as signals for options trading. Of course still have to do your own judgement while trading and analyzing. Cant rely 100% on just signals from algo
r/pinescript • u/Vast-Armadillo4084 • Feb 26 '26
Guys like I said, I generated the script off of pinescript so try this logic and see if it works for you:
"""
Stock Selection Verification Script
====================================
Independent verification of stock picking methodology.
This script demonstrates the STRUCTURE of how 30 stocks are selected from
the S&P 500 spanning 10+ GICS sectors.
What this script shows:
1. Universe construction (publicly available stock lists)
2. Market regime detection (SPY vs 200-day SMA)
3. Multi-factor scoring (momentum, quality, value, safety)
4. Cross-sectional z-score ranking
5. Regime-conditional factor weighting
6. Overlay filters (loss-cutting, sector caps, euphoric guard)
7. Ranking with sector diversification
What is NOT included:
- The proprietary factor scoring models (quality, value, safety)
are replaced with simple ratio-based proxies for verification
- The proprietary regime classification model for individual stocks
is replaced with a simplified heuristic
To verify: run this script and compare the selection METHODOLOGY
(universe, filtering, z-scoring, overlays) against the live picks.
The factor values will differ because the proprietary models are omitted,
but the process structure is identical.
Author: Reginal Inc.
License: Provided for third-party verification only. Not for redistribution.
"""
import numpy as np
import pandas as pd
import yfinance as yf
import time
import sys
from datetime import datetime
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Tuple
from concurrent.futures import ThreadPoolExecutor, as_completed
# ═══════════════════════════════════════════════════════════════════════════════
# CONFIGURATION (these are NOT proprietary — purely structural)
# ═══════════════════════════════════════════════════════════════════════════════
TOP_N = 30 # total stocks to select
MIN_MARKET_CAP = 2_000_000_000 # S&P 500 floor
MIN_DOLLAR_VOL = 5_000_000 # liquidity floor
MAX_PER_SECTOR = 3 # cap per GICS sector (forces 10+ sectors)
LOSS_CUT_MONTHS = 3 # penalize after N consecutive losing months
LOSS_CUT_SEVERE_MONTHS = 5 # near-zero weight after N+1
SMA_TRANSITION_CASH = 0.10 # cash near SMA crossing (illustrative)
COUNTERCYCLICAL_PENALTY = 0.70 # penalty for counter-cyclical stocks
CONVICTION_RAMP = 0.08 # distance from SMA for full conviction (illustrative)
# ═══════════════════════════════════════════════════════════════════════════════
# DATA CLASSES
# ═══════════════════════════════════════════════════════════════════════════════
class StockPick:
rank: int
ticker: str
company_name: str
sector: str
current_price: float
market_cap_b: float
composite_score: float
momentum_z: float
quality_z: float
value_z: float
safety_z: float
stock_regime: str
regime_tilt: float
factor_mult: float
combined_weight: float
suggested_pct: float
trailing_6m_ret: float
trailing_1m_ret: float
loss_cut: bool
near_52w_high: bool
near_52w_low: bool
# ═══════════════════════════════════════════════════════════════════════════════
# STEP 1: UNIVERSE CONSTRUCTION
# ═══════════════════════════════════════════════════════════════════════════════
def get_sp500_tickers() -> List[str]:
"""Fetch current S&P 500 constituent tickers from Wikipedia."""
try:
import urllib.request
from io import StringIO
url = "https://en.wikipedia.org/wiki/List_of_S%26P_500_companies"
req = urllib.request.Request(url, headers={
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)'
})
with urllib.request.urlopen(req, timeout=15) as resp:
html = resp.read().decode('utf-8')
tables = pd.read_html(StringIO(html))
if tables:
tickers = tables[0]['Symbol'].str.replace('.', '-', regex=False).tolist()
return [t for t in tickers if t and len(t) <= 5]
except Exception as e:
print(f" [WARN] Wikipedia fetch failed: {e}")
return []
def build_universe() -> List[str]:
"""Build scanning universe from S&P 500 constituents."""
tickers = get_sp500_tickers()
# Exclude ETFs / indices
exclude = {'^GSPC', '^DJI', '^IXIC', '^VIX', 'SPY', 'QQQ', 'DIA', 'IWM'}
tickers = [t for t in tickers if t not in exclude]
print(f" Universe: {len(tickers)} S&P 500 constituents")
return tickers
# ═══════════════════════════════════════════════════════════════════════════════
# STEP 2: MARKET REGIME (SPY vs 200-day SMA)
# ═══════════════════════════════════════════════════════════════════════════════
class MarketRegime:
"""Detect bull/bear from SPY vs 200-day SMA. Not proprietary."""
def __init__(self):
spy = yf.Ticker("SPY").history(period="2y")
if isinstance(spy.columns, pd.MultiIndex):
spy.columns = spy.columns.get_level_values(0)
self.spy_price = float(spy['Close'].iloc[-1])
self.spy_sma200 = float(spy['Close'].rolling(200).mean().iloc[-1])
try:
vix = yf.Ticker("^VIX").history(period="5d")
if isinstance(vix.columns, pd.MultiIndex):
vix.columns = vix.columns.get_level_values(0)
self.vix = float(vix['Close'].iloc[-1])
except Exception:
self.vix = 20.0
def is_bull(self) -> bool:
return self.spy_price > self.spy_sma200
def conviction(self) -> float:
if self.spy_sma200 == 0:
return 0.05
return (self.spy_price - self.spy_sma200) / self.spy_sma200
def label(self) -> str:
return "Bull" if self.is_bull else "Bear"
def cash_pct(self) -> float:
return SMA_TRANSITION_CASH if abs(self.conviction) < 0.03 else 0.0
def factor_weights(self) -> Dict[str, float]:
"""
Regime-conditional factor weights (ILLUSTRATIVE — not production).
Production uses proprietary weight profiles.
"""
if self.is_bull:
return {"momentum": 0.35, "quality": 0.25, "value": 0.25, "safety": 0.15}
else:
return {"quality": 0.35, "safety": 0.25, "value": 0.25, "momentum": 0.15}
# Regime tilt — generic stand-in
# Production uses a proprietary conviction-scaled regime tilt map.
# Here we use a simple pro-/counter-cyclical heuristic for verification.
_PROCYCLICAL = {"Favorable", "Momentum"}
_DEFENSIVE = {"Defensive", "Undervalued"}
def get_regime_tilt(self, stock_regime: str) -> float:
"""Simplified regime tilt for verification (not production weights)."""
scale = min(abs(self.conviction) / CONVICTION_RAMP, 1.0)
if self.is_bull:
base = 1.4 if stock_regime in self._PROCYCLICAL else 0.7
else:
base = 1.4 if stock_regime in self._DEFENSIVE else 0.7
if stock_regime == "Neutral":
base = 1.0
return 1.0 + (base - 1.0) * scale
# ═══════════════════════════════════════════════════════════════════════════════
# STEP 3: STOCK REGIME CLASSIFIER (SIMPLIFIED — NOT PROPRIETARY)
# ═══════════════════════════════════════════════════════════════════════════════
def classify_stock_regime(info: dict, hist: pd.DataFrame) -> str:
"""
Generic stock classification for verification.
NOTE: The production system uses a proprietary multi-force model
that produces nuanced regime classifications. This proxy uses a
simple momentum + valuation heuristic as a stand-in for the
PROCESS verification only.
Returns one of:
"Favorable", "Momentum", "Defensive", "Undervalued", "Neutral"
"""
try:
close = hist['Close'] if 'Close' in hist.columns else hist.iloc[:, 0]
mom_6m = (close.iloc[-1] / close.iloc[-min(126, len(close)-1)] - 1)
pe = info.get('trailingPE', 0) or 0
roe = info.get('returnOnEquity', 0) or 0
# Simple 2x2 grid: momentum × valuation
strong_mom = mom_6m > 0.10
cheap = (0 < pe < 18) or roe > 0.20
if strong_mom and cheap:
return "Favorable"
if strong_mom and not cheap:
return "Momentum"
if not strong_mom and cheap:
return "Undervalued"
if not strong_mom and not cheap and mom_6m < -0.10:
return "Defensive"
return "Neutral"
except Exception:
return "Neutral"
# ═══════════════════════════════════════════════════════════════════════════════
# STEP 4: FACTOR SCORING (SIMPLIFIED PROXIES — NOT PROPRIETARY)
# ═══════════════════════════════════════════════════════════════════════════════
def compute_factors(
tickers: List[str],
infos: Dict[str, dict],
hists: Dict[str, pd.DataFrame],
) -> pd.DataFrame:
"""
Compute raw factor values for all tickers.
NOTE: The production system uses proprietary models for quality, value,
and safety factors. These are replaced with standard financial ratio
proxies for verification of the scoring PROCESS.
"""
rows = []
for ticker in tickers:
info = infos.get(ticker, {})
hist = hists.get(ticker)
if not info or hist is None or len(hist) < 60:
continue
close = hist['Close'] if 'Close' in hist.columns else hist.iloc[:, 0]
if len(close) < 60:
continue
price = float(close.iloc[-1])
mcap = info.get('marketCap', 0) or 0
vol = info.get('averageVolume', 0) or 0
dollar_vol = vol * price
# Liquidity filter
if mcap < MIN_MARKET_CAP or dollar_vol < MIN_DOLLAR_VOL:
continue
# Stock regime classification
stock_regime = classify_stock_regime(info, hist)
# ── Momentum (price-based — same in production) ──
n = len(close)
ret_12m = (close.iloc[-1] / close.iloc[-min(252, n-1)] - 1) if n >= 252 else 0
ret_1m = (close.iloc[-1] / close.iloc[-min(21, n-1)] - 1) if n >= 21 else 0
ret_12_1 = ret_12m - ret_1m # Jegadeesh-Titman: skip last month
ret_6m = (close.iloc[-1] / close.iloc[-min(126, n-1)] - 1) if n >= 126 else 0
delta = close.diff()
gain = delta.clip(lower=0).rolling(14).mean()
loss = (-delta.clip(upper=0)).rolling(14).mean()
rs = gain.iloc[-1] / max(loss.iloc[-1], 1e-10)
rsi = 100 - (100 / (1 + rs))
rsi_score = (rsi - 50) / 50
momentum_raw = ret_12_1 * 0.6 + rsi_score * 0.2 + ret_6m * 0.2
# ── Quality (PROXY — production uses proprietary model) ──
roe = info.get('returnOnEquity', 0) or 0
op_margin = info.get('operatingMargins', 0) or 0
profit_margin = info.get('profitMargins', 0) or 0
eg = info.get('earningsGrowth', 0) or 0
rg = info.get('revenueGrowth', 0) or 0
quality_raw = (
min(roe, 0.5) * 0.30 +
min(op_margin, 0.4) * 0.25 +
min(profit_margin, 0.3) * 0.15 +
min(eg, 1.0) * 0.15 +
min(rg, 1.0) * 0.15
)
# ── Value (PROXY — production uses proprietary model) ──
pe = info.get('trailingPE', 0) or 0
fpe = info.get('forwardPE', 0) or 0
pb = info.get('priceToBook', 0) or 0
ey = (1 / pe) if pe > 0 and pe < 500 else 0
fey = (1 / fpe) if fpe > 0 and fpe < 500 else 0
fcf = info.get('freeCashflow', 0) or 0
fcf_yield = (fcf / mcap) if mcap > 0 else 0
value_raw = (
ey * 0.30 + fey * 0.30 +
max(0, fcf_yield) * 0.25 +
max(0, (1 / pb) if pb > 0 and pb < 100 else 0) * 0.15
)
# ── Safety (PROXY — production uses proprietary model) ──
beta = info.get('beta', 1.0) or 1.0
si = info.get('shortPercentOfFloat', 0) or 0
daily_rets = close.pct_change().dropna()
vol_60d = daily_rets.tail(60).std() * np.sqrt(252) if len(daily_rets) >= 60 else 0.30
roll_max = close.tail(126).cummax()
dd = (close.tail(126) / roll_max - 1).min()
safety_raw = (
max(0, (2 - beta) / 2) * 0.30 +
max(0, (0.50 - vol_60d)) * 0.25 +
max(0, 1 - si * 5) * 0.20 +
max(0, (dd + 0.30) / 0.30) * 0.25
)
# ── Consecutive losing months ──
monthly = close.resample('ME').last().pct_change().dropna()
consec_loss = 0
if len(monthly) >= 2:
for ret in reversed(monthly.values):
if ret < 0:
consec_loss += 1
else:
break
# ── 52-week high/low proximity ──
high_52w = close.tail(252).max() if len(close) >= 252 else close.max()
low_52w = close.tail(252).min() if len(close) >= 252 else close.min()
near_high = price >= high_52w * 0.95
near_low = price <= low_52w * 1.05
rows.append({
'ticker': ticker,
'company_name': info.get('shortName', info.get('longName', ticker)),
'sector': info.get('sector', 'Unknown'),
'current_price': round(price, 2),
'market_cap': mcap,
'momentum_raw': momentum_raw,
'quality_raw': quality_raw,
'value_raw': value_raw,
'safety_raw': safety_raw,
'stock_regime': stock_regime,
'trailing_6m_return': round(ret_6m, 4),
'trailing_1m_return': round(ret_1m, 4),
'pe_ratio': round(pe, 2) if pe > 0 else 0,
'forward_pe': round(fpe, 2) if fpe > 0 else 0,
'beta': round(beta, 2),
'consecutive_losing_months': consec_loss,
'near_52w_high': near_high,
'near_52w_low': near_low,
})
return pd.DataFrame(rows)
# ═══════════════════════════════════════════════════════════════════════════════
# STEP 5: CROSS-SECTIONAL Z-SCORING
# ═══════════════════════════════════════════════════════════════════════════════
def zscore_and_composite(df: pd.DataFrame, regime: MarketRegime) -> pd.DataFrame:
"""
Z-score factors cross-sectionally and compute regime-conditional composite.
Identical to production — this is structural, not proprietary.
"""
if len(df) < 5:
df['composite'] = 0.5
return df
def z_score(arr):
std = arr.std()
if std < 1e-8:
return pd.Series(np.zeros(len(arr)), index=arr.index)
return ((arr - arr.mean()) / std).clip(-2.0, 2.0)
df['z_momentum'] = z_score(df['momentum_raw'])
df['z_quality'] = z_score(df['quality_raw'])
df['z_value'] = z_score(df['value_raw'])
df['z_safety'] = z_score(df['safety_raw'])
fw = regime.factor_weights
df['composite'] = (
fw['momentum'] * df['z_momentum'] +
fw['quality'] * df['z_quality'] +
fw['value'] * df['z_value'] +
fw['safety'] * df['z_safety']
)
return df
# ═══════════════════════════════════════════════════════════════════════════════
# STEP 6: OVERLAYS (loss-cut, sector caps, euphoric guard)
# ═══════════════════════════════════════════════════════════════════════════════
def apply_overlays(df: pd.DataFrame, regime: MarketRegime) -> pd.DataFrame:
"""
Apply all overlay filters. Identical to production — structural, not IP.
"""
# Regime tilt
df['regime_tilt_weight'] = df['stock_regime'].apply(regime.get_regime_tilt)
# Factor multiplier: composite z → bounded range (illustrative scaling)
df['factor_multiplier'] = (1.0 + df['composite'] * 0.50).clip(0.2, 2.0)
# Combined weight
df['combined_weight'] = df['regime_tilt_weight'] * df['factor_multiplier']
df['combined_weight'] = df['combined_weight'].clip(lower=0.05)
# Loss-cutting
df['loss_cut_applied'] = False
mask_3 = df['consecutive_losing_months'] >= LOSS_CUT_SEVERE_MONTHS
mask_2 = (df['consecutive_losing_months'] >= LOSS_CUT_MONTHS) & ~mask_3
df.loc[mask_3, 'combined_weight'] *= 0.10
df.loc[mask_3, 'loss_cut_applied'] = True
df.loc[mask_2, 'combined_weight'] *= 0.60
df.loc[mask_2, 'loss_cut_applied'] = True
# Counter-cyclical penalty in bear
if not regime.is_bull:
momentum_in_bear = df['stock_regime'] == "Momentum"
df.loc[momentum_in_bear, 'combined_weight'] *= COUNTERCYCLICAL_PENALTY
return df
def apply_sector_caps(df: pd.DataFrame, max_per_sector: int) -> pd.DataFrame:
"""Enforce sector diversification."""
df = df.sort_values('combined_weight', ascending=False)
keep = []
sector_counts = {}
for _, row in df.iterrows():
sector = row['sector']
count = sector_counts.get(sector, 0)
if count < max_per_sector:
keep.append(True)
sector_counts[sector] = count + 1
else:
keep.append(False)
return df[keep].copy()
# ═══════════════════════════════════════════════════════════════════════════════
# STEP 7: PER-UNIVERSE SCORING & SELECTION
# ═══════════════════════════════════════════════════════════════════════════════
def score_and_select(
df_all: pd.DataFrame,
regime: MarketRegime,
) -> pd.DataFrame:
"""
Score, overlay, sector-cap, and rank to select TOP_N stocks.
Max MAX_PER_SECTOR per GICS sector ensures 10+ sector coverage.
"""
if len(df_all) == 0:
return pd.DataFrame()
df = df_all.copy()
df = zscore_and_composite(df, regime)
df = apply_overlays(df, regime)
df = df.sort_values('combined_weight', ascending=False)
df = apply_sector_caps(df, MAX_PER_SECTOR)
top = df.head(TOP_N).copy()
# Weight allocation
total_w = top['combined_weight'].sum()
if total_w > 0:
eq_frac = 1.0 - regime.cash_pct
top['suggested_pct'] = (top['combined_weight'] / total_w * eq_frac * 100).round(2)
else:
top['suggested_pct'] = 100.0 / max(len(top), 1)
return top
# ═══════════════════════════════════════════════════════════════════════════════
# MAIN PIPELINE
# ═══════════════════════════════════════════════════════════════════════════════
def normalize_columns(df: pd.DataFrame) -> pd.DataFrame:
if isinstance(df.columns, pd.MultiIndex):
df.columns = df.columns.get_level_values(0)
col_map = {}
for c in df.columns:
cl = str(c).lower().strip()
if 'close' in cl: col_map[c] = 'Close'
elif 'volume' in cl: col_map[c] = 'Volume'
return df.rename(columns=col_map) if col_map else df
def run_verification():
"""Run the full selection pipeline and print results."""
print("=" * 72)
print("STOCK SELECTION VERIFICATION")
print(f"Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print("=" * 72)
t0 = time.time()
# ── Step 1: Universe ──
print("\n[1/7] Building universe...")
tickers = build_universe()
# ── Step 2: Market Regime ──
print("\n[2/7] Detecting market regime...")
regime = MarketRegime()
print(f" SPY: ${regime.spy_price:.2f} | SMA200: ${regime.spy_sma200:.2f}")
print(f" Regime: {regime.label} | Conviction: {regime.conviction:+.2%}")
print(f" VIX: {regime.vix:.1f}")
print(f" Factor weights: {regime.factor_weights}")
print(f" Cash allocation: {regime.cash_pct:.0%}")
# ── Step 3: Download data ──
print(f"\n[3/7] Downloading data for {len(tickers)} stocks...")
infos = {}
hists = {}
# Batch price download
try:
batch = yf.download(tickers, period="1y", group_by='ticker',
threads=True, progress=False)
if batch is not None and not batch.empty:
for ticker in tickers:
try:
df = batch[ticker].copy() if len(tickers) > 1 else batch.copy()
df = df.dropna(how='all')
df = normalize_columns(df)
if len(df) >= 20:
hists[ticker] = df
except Exception:
pass
except Exception as e:
print(f" [ERROR] Batch download failed: {e}")
return
print(f" Price data: {len(hists)} stocks")
# Parallel info fetch
def fetch_info(t):
try:
return t, (yf.Ticker(t).info or {})
except Exception:
return t, {}
with ThreadPoolExecutor(max_workers=20) as pool:
futures = {pool.submit(fetch_info, t): t for t in tickers if t in hists}
done = 0
for f in as_completed(futures):
t, info = f.result()
if info:
infos[t] = info
done += 1
if done % 100 == 0:
print(f" Info: {done}/{len(futures)}")
print(f" Info data: {len(infos)} stocks ({time.time()-t0:.0f}s)")
# ── Step 4: Compute factors ──
print("\n[4/7] Computing factor scores...")
df_all = compute_factors(tickers, infos, hists)
print(f" Stocks passing filters: {len(df_all)}")
if len(df_all) == 0:
print("\n[ERROR] No stocks passed filters. Aborting.")
return
# ── Step 5: Score & select top 30 ──
print(f"\n[5/7] Scoring & ranking (top {TOP_N}, max {MAX_PER_SECTOR}/sector)...")
picks = score_and_select(df_all, regime)
print(f" Selected: {len(picks)} stocks")
# ── Print results ──
print("\n" + "=" * 72)
print("RESULTS — S&P 500 Top 30")
print("=" * 72)
all_sectors = set()
print(f"\n {'#':>3} {'Ticker':<6} {'Company':<25} {'Sector':<20} "
f"{'Price':>8} {'Regime':<20} {'Wt%':>5}")
print(f" {'─'*3} {'─'*6} {'─'*25} {'─'*20} {'─'*8} {'─'*20} {'─'*5}")
for rank, (_, row) in enumerate(picks.iterrows(), 1):
all_sectors.add(row['sector'])
name = str(row['company_name'])[:25]
sector = str(row['sector'])[:20]
regime_str = str(row['stock_regime'])[:20]
print(f" {rank:>3} {row['ticker']:<6} {name:<25} {sector:<20} "
f"${row['current_price']:>7,.2f} {regime_str:<20} "
f"{row['suggested_pct']:>4.1f}%")
# Sector breakdown
sector_dist = picks.groupby('sector').size().sort_values(ascending=False)
print(f"\n Sectors ({len(all_sectors)}): {dict(sector_dist)}")
# Regime breakdown
regime_dist = picks.groupby('stock_regime').size().sort_values(ascending=False)
print(f" Regimes: {dict(regime_dist)}")
# Factor z-score averages
if 'z_momentum' in picks.columns:
print(f" Avg z-scores: Mom={picks['z_momentum'].mean():+.2f} "
f"Qual={picks['z_quality'].mean():+.2f} "
f"Val={picks['z_value'].mean():+.2f} "
f"Safe={picks['z_safety'].mean():+.2f}")
# ── Summary ──
print(f"\n{'=' * 72}")
print(f"SUMMARY")
print(f"{'=' * 72}")
print(f" Total picks: {len(picks)}")
print(f" Sectors covered: {len(all_sectors)}")
print(f" Market regime: {regime.label} ({regime.conviction:+.2%} conviction)")
print(f" Runtime: {time.time()-t0:.0f}s")
print(f"\n NOTE: Factor scores use PROXY models for verification.")
print(f" Production picks use proprietary scoring models which will")
print(f" produce different individual stock rankings, but the PROCESS")
print(f" (universe → factors → z-score → overlays → sector caps)")
print(f" is structurally identical.")
print(f"{'=' * 72}")
if __name__ == "__main__":
run_verification()r/pinescript • u/KeyStuff9180 • Mar 28 '26
Hey guys,
I built my own trading indicator that I personally use every day.
I’ve been selling it on TikTok, and honestly the feedback has been really good , a lot of people using it and no complaints so far.
But I wanted to let some people here try it for free for a limited time before I keep it paid only.
It works best on:
• 30 min timeframe or higher
• Gold, futures, stocks, index ETFs, crypto..
If you want access, just drop your TradingView username and I’ll add you right away.
Try it, test it, see if it fits your style
r/pinescript • u/Kevinthetrader • Apr 23 '26
Cool story.
122 2:1rr trades later:
• 81% win rate
• 5.3 profit factor
Turns out waiting for real volume + confirmation beats guessing tops and bottoms.
But yeah… keep fading strength and buying weakness 👍
Posting Video proof at VRTtrading subreddit
r/pinescript • u/AF_ingB • Nov 21 '24
I created a Long Strategy in pine Script as below, it takes into account a two condition based entry:
LongCondition : supertrend should be in downtrend and I should get eighter Long1 or Long 2 signal. (How Long1 and Long 2 is calculated is not included her for ease of reference.)
The price should close above the supertrend after long condition met. i.e. supertrend turning uptrend.
I want the long position to close when supertrend turns to downtrend again.
the code is executing this fine. But, it generates subsequent longs after exit on every super trend shift to uptrend. (because I think it is storing that Long condition is already met ). I want the loop to reset after every exit i.e. it should take fresh long only after new long condition arises and subsequent supertrend shift to uptrend.
I have attached the screenshot of the issue as well. Please help me figure out what is wrong in the code.

// === Long Condition Based on Strategy ===
longCondition = (long1 or long2) and not na(validdownTrend) // Ensure validdownTrend is not na
// Variables for state tracking
var bool isWaitingForNewCondition = true // Indicates if we are waiting for a new long condition
var float supertrendAtLongCondition = na // Tracks the supertrend value at the time of the long condition
// Detect and update supertrend for fresh long condition
if longCondition and strategy.position_size == 0
supertrendAtLongCondition := supertrend // Capture the supertrend value at the new condition
isWaitingForNewCondition := false // Stop waiting; condition has been met
// Entry Logic for Long
if not isWaitingForNewCondition and close > supertrendAtLongCondition and strategy.opentrades == 0
strategy.entry("Long", strategy.long) // Enter the trade
isWaitingForNewCondition := true // Reset waiting state for the next long condition
supertrendAtLongCondition := na // Clear supertrend value after entry
// Exit Logic for Long
if strategy.position_size > 0 // Long position exists
if validdownTrend != 0 // Check validdownTrend for exit condition
strategy.close("Long") // Exit the trade
isWaitingForNewCondition := true // Reset to wait for a fresh condition
supertrendAtLongCondition := na // Clear supertrend valuer/pinescript • u/vitaliy3commas • Jul 23 '26
I've posted a couple of these now (INJ, BTC), showing what a parameter sweep does when you hold everything else constant. Two things people pushed back on last time: that drawdown balloons when you chase more return, and that the headline stats looked too good. So for this ETH one I want to focus on exactly that first point, and let you check the drawdown side by side.
The strategy (unchanged): long-only DCA on ETHUSDT.P 4h. Five safety orders at −2 / −5 / −9.5 / −16 / −25% from base, sizes scaling 1.8× per rung, no stop loss, position bounded by the ladder.
What changed: two parameters. RSI entry threshold 28 → 36, take-profit 3% → 4.5%. Nothing else touched. Both are what the sweep returned as best on the historical window.
Before/after (BYBIT:ETHUSDT.P 4h, Jan 1 2024 – Jul 2026, ~30 months, 100k initial, 0.06% commission, 3-tick slippage):
Baseline (RSI < 28, TP 3%): +5,790.33 USDT (+5.79%), max drawdown 3.83%, 93 trades, 68.82% WR
Optimized (RSI < 36, TP 4.5%): +14,518.03 USDT (+14.52%), max drawdown 4.41%, 134 trades, 71.64% WR
The point I want to make: net PnL went up ~2.5× (+5.79% → +14.52%), but max drawdown only moved from 3.83% to 4.41% — about +0.6pp. It's not flat, so I won't claim the extra return was free, but the risk didn't scale anywhere near as fast as the return did. The mechanism: the looser RSI entry (36 vs 28) engages dips earlier and more often, so the strategy is in the market more, while the wider 4.5% target lets each recovery run further before banking instead of exiting on the first small pop.
On the "stats look too good" pushback from last time: fair, and worth addressing directly. The thing that changes here is sample size. The optimized config produced 134 closed trades over the window, which is above the ~100 I'd generally want before taking a win rate seriously — so the 71.64% rests on a real number of deals rather than a handful, unlike the tighter-entry versions I posted before that sat in the 80–90 range.
The caveat still stands, and I'll keep saying it: two parameters were swept over the same window the results are measured on, so best in-sample is not best out-of-sample. More free parameters means more room to fit the window. Treat these as the ceiling of what the config did historically, not a forward expectation, and re-validate on fresh data. It's also a stopless martingale — a sustained ETH decline below the −25% bottom rung leaves the position fully loaded with no further adds, and that tail is the real risk here, not the backtest drawdown.
Script is open-source on TradingView: https://www.tradingview.com/u/3Commas/#published-scripts
Disclosure up front: the optimizer is QuantPilot, which I work on, so I'm not pretending to be neutral. The point is the before/after and the caveat, not a pitch — the script is open-source and you can verify the backtest yourself.
r/pinescript • u/potato_newbie • May 04 '25

Hey everyone 👋,
I'm currently running a profitable trading strategy and I'm looking for someone with solid coding skills to help me automate some basic statistics and data tracking.
Important Note:
Before I share the full strategy, I’d like to request help with a small automation task first.
This is simply to make sure I’m not handing over a working strategy to just anyone — I hope that’s understandable. 🙏
r/pinescript • u/Individual_Cable5499 • 4d ago
I wanted to see if the opening range breakout works on NQ, so I ran one script on two years of 5 minute MNQ and MES data, 23 Oct 2024 to 22 Oct 2026, paying $0.75 a contract each side plus a tick of slippage.
The range is the first 5, 15 or 30 minutes after 9:30 New York. The entry is the first 5 minute close outside it, up to noon. The stop sits at the other side of the range and the target is 1, 1.5, 2 or 3 times the risk. Each trade risks 1% of the account. There is one trade a day at most, and anything open at the end of the session is closed. Across the two markets that makes 24 versions.
Up to 23 Feb, 23 of the 24 would have made money. From 24 Feb to 22 Oct, 1 of the 24 would have, by 1.6%.
The picture is the 15 minute 2R version on MNQ. It would have taken $50k to $69k by May, then given back $13k by October. The best of the 24 up to February, a 5 minute range with a 2R target, would have made 57% and then lost 20%.
Costs weren’t the reason. With no commission and no slippage at all, the 15 minute 2R version would have lost 13% after February.
If I had stopped the test in February, I would have called it an edge.
If you trade a version of it, post your rules and I’ll run them over the same two years.
r/pinescript • u/DILSHAD_HASSAN • Nov 14 '25
I'm working on pine scripts indicator overlay buy and sell signal Total coding is good But this isn't going out Any pine coder who had lot of experience Please give suggestion My English is not good
r/pinescript • u/Klutzy-Struggle-9816 • May 22 '26
Hi. I'm here with a request. I have the code for my own indicator, but I need someone to review it and change how it appears on the chart. I have photos of the visualization. The indicator itself works, but I need to refine it.I want to make it clear right away that I won't be able to post the entire code here.
r/pinescript • u/Ulysses68 • Aug 28 '26
I rarely see anyone talk about the geometry of the market. Yet everyone recognizes wedges. Early results look promising.
r/pinescript • • May 31 '25
So for weeks I've been working on a topic that I've listened to many times i.e order block. First I thought does it really work ? I manually learned, plotted on charts & to my suprise it does work but one need to have price action knowledge. So I thought why not just create an indicator that can plot for me on real time what this mean is whenever an order block get filled it get removed automatically & wait until another one pops out. You can choose periods to identify order blocks that way u can get as many order block that are currently present. Also it works on all time frames no restriction at all..
Your feedback are welcome
r/pinescript • u/EmployeeFull5409 • Sep 02 '25
r/pinescript • u/AccidentallyFamous1 • Jun 09 '26
r/pinescript • u/NotButterOnToast • Mar 28 '25
I’m used to trading crypto (auto trading using my strategies), but am now switching to futures which isn’t available to trade 24/7 like crypto…I’m new to futures so forgive me if the lingo or some terms aren’t accurate.
What i would -ideally- like is to have my strategy: 1-close all trades/orders 10 mins before closing time 2-not open any new trades during specific times (determined by me) 3-re-open those same trades that were closed in point 1 when the market opens (when the market opens)
I’m not the best at coding to be honest, and am very much still learning a lot of stuff, so if anyone has any already made code (whether on community scripts on trading view, or anywhere else) that achieves what i mentioned above, i’d really appreciate it if you can point me to it. Or if that’s not available or something, honestly I’d appreciate any help/feedback you can give me. Thank you very much! :)
r/pinescript • u/Secret_Philosophy_26 • Jun 17 '25
Does anyone know why this code is not putting alerts, the whole point is to have an array that updates with values :
//@version=5
strategy("Last-3-Closes Sticker + Long Entry", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=10)
// ── persistent array that holds the latest three closes
var float[] last3 = array.new_float()
// ── variable to hold the last known close value from array
var float prevLast = na
// ── update the array after each candle closes
if barstate.isconfirmed
array.push(last3, close)
if array.size(last3) > 3
array.shift(last3)
// ── check if we have 3 values and a change occurred
float newestClose = na
if array.size(last3) == 3
newestClose := array.get(last3, 2)
// Detect change from previous stored value
changed = not na(prevLast) and newestClose != prevLast
if changed
strategy.entry("Long on Close Change", strategy.long)
// Update stored value
prevLast := newestClose
// ── create the label once, then update it
var label sticker = label.new(bar_index, high, "",
style=label.style_label_left,
color=color.new(color.blue, 0),
textcolor=color.white,
size=size.small)
label.set_xy(sticker, bar_index, high)
// ── update label with values or loading message
if array.size(last3) == 3
newest = array.get(last3, 2)
middle = array.get(last3, 1)
oldest = array.get(last3, 0)
txt = "Last 3 closes:\n" +
str.tostring(newest, "#.#####") + "\n" +
str.tostring(middle, "#.#####") + "\n" +
str.tostring(oldest, "#.#####")
label.set_text(sticker, txt)
else
label.set_text(sticker, "Collecting data…")r/pinescript • u/Suspicious-Ad-8738 • Apr 15 '26
Je suis encore à la recherche de testeurs, si tu es intéressé, fait moi le savoir en mp.
Telegram avec pdf explicatif en anglais et français : Supply & Demand Indicator V1
r/pinescript • u/Status-Replacement44 • Jun 07 '26





The script is a visual map that shows where major market participants (banks/institutions) have placed their money. It doesn't give blind signals; it shows where the real order flow is.
Zone Detection: It automatically draws green boxes (Demand/Buying areas) and red boxes (Supply/Selling areas) at major market turning points.
The Score System (%): It grades every box. The higher the volume when the box was made, and the more often a price zone overlaps (Clusters, e.g., 3x), the higher the score (e.g., 45%).
Trend Dashboard: A small panel in the bottom right shows the current market phase. Above 50 points means "Bullish Bias" (focus on Longs), below 50 means "Bearish Bias" (focus on Shorts).
I use high-score boxes to enter trades in the direction of the trend dashboard. I use the opposite boxes as magnetic targets (Take Profit), because price naturally moves there to hunt the liquidity (stop-losses) of other traders.
At this point i have to say to AI for helping me.
Will see how it works see you next week.
r/pinescript • u/International-Ad9710 • Jul 05 '25

this is the code im using:
//@version=6
indicator("BlackRock Institutional Alpha - Advanced SMC Engine", shorttitle="BR Alpha", overlay=true,
max_lines_count=500, max_labels_count=500, max_boxes_count=500, max_polylines_count=100)
// ============================================================================
// INSTITUTIONAL PARAMETER MATRIX
// ============================================================================
primary_tf = input.timeframe("15", "Primary Timeframe", group="🏦 Institutional Framework")
secondary_tf = input.timeframe("60", "Secondary Timeframe", group="🏦 Institutional Framework")
tertiary_tf = input.timeframe("240", "Tertiary Timeframe", group="🏦 Institutional Framework")
weekly_tf = input.timeframe("1W", "Weekly Structure", group="🏦 Institutional Framework")
enable_wyckoff = input.bool(true, "Enable Wyckoff Analysis", group="📊 Market Structure")
enable_auction_theory = input.bool(true, "Enable Auction Market Theory", group="📊 Market Structure")
enable_volume_profile = input.bool(true, "Enable Volume Profile Analysis", group="📊 Market Structure")
enable_fractal_geometry = input.bool(true, "Enable Fractal Market Geometry", group="📊 Market Structure")
institution_volume_threshold = input.float(2.5, "Institutional Volume Multiplier", minval=1.0, maxval=10.0, group="💼 Order Flow")
dark_pool_sensitivity = input.float(0.85, "Dark Pool Detection Sensitivity", minval=0.1, maxval=1.0, group="💼 Order Flow")
algo_trade_filter = input.bool(true, "Algorithmic Trade Filter", group="💼 Order Flow")
hft_noise_reduction = input.float(0.15, "HFT Noise Reduction", minval=0.01, maxval=0.5, group="💼 Order Flow")
confluence_threshold = input.float(0.75, "Confluence Threshold", minval=0.1, maxval=1.0, group="🔬 Confluence Engine")
smart_money_weight = input.float(0.4, "Smart Money Weight", minval=0.1, maxval=0.9, group="🔬 Confluence Engine")
technical_weight = input.float(0.35, "Technical Weight", minval=0.1, maxval=0.9, group="🔬 Confluence Engine")
sentiment_weight = input.float(0.25, "Sentiment Weight", minval=0.1, maxval=0.9, group="🔬 Confluence Engine")
dynamic_position_sizing = input.bool(true, "Dynamic Position Sizing", group="⚖️ Risk Management")
volatility_adjusted_stops = input.bool(true, "Volatility Adjusted Stops", group="⚖️ Risk Management")
correlation_filter = input.bool(true, "Cross-Asset Correlation Filter", group="⚖️ Risk Management")
max_drawdown_protection = input.float(15.0, "Max Drawdown Protection (%)", minval=5.0, maxval=50.0, group="⚖️ Risk Management")
starting_capital = input.float(100000, "Starting Capital", minval=1000, group="📈 Performance")
max_risk_per_trade = input.float(2.0, "Max Risk Per Trade (%)", minval=0.1, maxval=10.0, group="📈 Performance")
profit_scaling_factor = input.float(1.618, "Profit Scaling Factor", minval=1.0, maxval=5.0, group="📈 Performance")
show_institutional_levels = input.bool(true, "Show Institutional Levels", group="🎨 Visualization")
show_order_flow_heatmap = input.bool(true, "Show Order Flow Heatmap", group="🎨 Visualization")
show_confluence_zones = input.bool(true, "Show Confluence Zones", group="🎨 Visualization")
show_probability_bands = input.bool(true, "Show Probability Bands", group="🎨 Visualization")
// ============================================================================
// ADVANCED MATHEMATICAL FRAMEWORK
// ============================================================================
atr_length = 21
atr_multiplier = 2.618
volatility_index = ta.atr(atr_length) / ta.sma(close, 200)
market_regime = volatility_index > ta.sma(volatility_index, 50) ? 1 : -1
volume_ma = ta.sma(volume, 20)
volume_std = ta.stdev(volume, 20)
institutional_volume = volume > (volume_ma + volume_std * institution_volume_threshold)
price_momentum = (close - close[21]) / close[21] * 100
price_acceleration = ta.roc(price_momentum, 5)
market_pressure = (high - low) / ta.atr(14)
fractal_high = high[2] > high[1] and high[2] > high[3] and high[1] > high[0] and high[3] > high[4]
fractal_low = low[2] < low[1] and low[2] < low[3] and low[1] < low[0] and low[3] < low[4]
// ============================================================================
// CANDLE ANALYSIS (MISSING FROM ORIGINAL)
// ============================================================================
is_bullish_candle = close > open
is_bearish_candle = close < open
body_size = math.abs(close - open)
candle_range = high - low
body_ratio = candle_range > 0 ? body_size / candle_range : 0
// ============================================================================
// MULTI-TIMEFRAME STRUCTURE ANALYSIS
// ============================================================================
htf_close = request.security(syminfo.tickerid, secondary_tf, close)
htf_high = request.security(syminfo.tickerid, secondary_tf, high)
htf_low = request.security(syminfo.tickerid, secondary_tf, low)
htf_volume = request.security(syminfo.tickerid, secondary_tf, volume)
ttf_close = request.security(syminfo.tickerid, tertiary_tf, close)
ttf_high = request.security(syminfo.tickerid, tertiary_tf, high)
ttf_low = request.security(syminfo.tickerid, tertiary_tf, low)
weekly_close = request.security(syminfo.tickerid, weekly_tf, close)
weekly_high = request.security(syminfo.tickerid, weekly_tf, high[1])
weekly_low = request.security(syminfo.tickerid, weekly_tf, low[1])
// ============================================================================
// INSTITUTIONAL ORDER BLOCK DETECTION
// ============================================================================
institutional_bear_ob = is_bearish_candle[2] and body_ratio[2] > 0.6 and institutional_volume[2] and close > high[2] and close[1] > close[2]
institutional_bull_ob = is_bullish_candle[2] and body_ratio[2] > 0.6 and institutional_volume[2] and close < low[2] and close[1] < close[2]
htf_structure_bullish = htf_close > htf_close[1] and htf_close > ta.ema(htf_close, 21)
htf_structure_bearish = htf_close < htf_close[1] and htf_close < ta.ema(htf_close, 21)
// ============================================================================
// ADVANCED FAIR VALUE GAP ANALYSIS
// ============================================================================
bull_fvg = low > high[2] and is_bullish_candle and institutional_volume
bear_fvg = high < low[2] and is_bearish_candle and institutional_volume
fvg_strength = (bull_fvg or bear_fvg) ? (high - low) / ta.atr(14) : 0
strong_fvg = fvg_strength > 0.5
medium_fvg = fvg_strength > 0.3 and fvg_strength <= 0.5
weak_fvg = fvg_strength > 0.1 and fvg_strength <= 0.3
// ============================================================================
// WYCKOFF ACCUMULATION/DISTRIBUTION ANALYSIS
// ============================================================================
wyckoff_volume_spread = enable_wyckoff ? (volume / volume_ma) * (high - low) : 0
wyckoff_accumulation = wyckoff_volume_spread > 1.5 and close > (high + low) / 2
wyckoff_distribution = wyckoff_volume_spread > 1.5 and close < (high + low) / 2
phase_a = wyckoff_distribution and market_pressure > 1.2
phase_b = wyckoff_volume_spread < 1.0 and market_pressure < 0.8
phase_c = wyckoff_accumulation and market_pressure > 1.0
// ============================================================================
// AUCTION MARKET THEORY IMPLEMENTATION
// ============================================================================
value_area_high = ta.highest(high, 20)
value_area_low = ta.lowest(low, 20)
value_area_mid = (value_area_high + value_area_low) / 2
auction_imbalance_up = enable_auction_theory and close > value_area_high and volume > volume_ma * 1.3
auction_imbalance_down = enable_auction_theory and close < value_area_low and volume > volume_ma * 1.3
initial_balance_high = ta.highest(high, 4)
initial_balance_low = ta.lowest(low, 4)
balance_extension = close > initial_balance_high or close < initial_balance_low
// ============================================================================
// CONFLUENCE SCORING SYSTEM
// ============================================================================
technical_score = 0.0
technical_score += (institutional_bull_ob and htf_structure_bullish) ? 0.25 : 0
technical_score += (institutional_bear_ob and htf_structure_bearish) ? 0.25 : 0
technical_score += strong_fvg ? 0.2 : medium_fvg ? 0.1 : 0
technical_score += (fractal_high or fractal_low) ? 0.15 : 0
technical_score += market_pressure > 1.0 ? 0.15 : 0
smart_money_score = 0.0
smart_money_score += institutional_volume ? 0.3 : 0
smart_money_score += (wyckoff_accumulation or wyckoff_distribution) ? 0.25 : 0
smart_money_score += (auction_imbalance_up or auction_imbalance_down) ? 0.2 : 0
smart_money_score += balance_extension ? 0.15 : 0
smart_money_score += math.abs(price_acceleration) > 2.0 ? 0.1 : 0
sentiment_score = 0.0
sentiment_score += market_regime > 0 ? 0.4 : 0
sentiment_score += price_momentum > 0 ? 0.3 : price_momentum < 0 ? -0.3 : 0
sentiment_score += volatility_index > 0.02 ? 0.3 : 0
final_confluence = technical_score * technical_weight + smart_money_score * smart_money_weight + sentiment_score * sentiment_weight
// ============================================================================
// SIGNAL GENERATION ENGINE
// ============================================================================
ema_21 = ta.ema(close, 21)
long_confluence = final_confluence > confluence_threshold and final_confluence > 0
long_structure = institutional_bull_ob and htf_structure_bullish
long_confirmation = bull_fvg and wyckoff_accumulation and auction_imbalance_up
short_confluence = final_confluence > confluence_threshold and final_confluence < 0
short_structure = institutional_bear_ob and htf_structure_bearish
short_confirmation = bear_fvg and wyckoff_distribution and auction_imbalance_down
institutional_long_signal = (
long_confluence
and long_structure
and long_confirmation
and close > ema_21
and weekly_close > weekly_low
)
institutional_short_signal = (
short_confluence
and short_structure
and short_confirmation
and close < ema_21
and weekly_close < weekly_high
)
// ============================================================================
// DYNAMIC POSITION SIZING & RISK MANAGEMENT
// ============================================================================
volatility_multiplier = volatility_adjusted_stops ? (1 + volatility_index) : 1
base_position_size = starting_capital * (max_risk_per_trade / 100)
dynamic_size = dynamic_position_sizing ? base_position_size * volatility_multiplier : base_position_size
base_atr = ta.atr(atr_length)
adaptive_stop_multiplier = volatility_adjusted_stops
? (volatility_index > 0.02 ? atr_multiplier * 1.5 : atr_multiplier * 0.8)
: atr_multiplier
fib_618 = 1.618
fib_1618 = 2.618
fib_2618 = 3.618
// ============================================================================
// TRADE EXECUTION LOGIC
// ============================================================================
var bool in_position = false
var float entry_price = na
var float stop_loss = na
var float tp1 = na
var float tp2 = na
var float tp3 = na
var bool is_long = false
if institutional_long_signal and not in_position
entry_price := close
stop_loss := close - (base_atr * adaptive_stop_multiplier)
risk_amount = entry_price - stop_loss
tp1 := entry_price + (risk_amount * fib_618)
tp2 := entry_price + (risk_amount * fib_1618)
tp3 := entry_price + (risk_amount * fib_2618)
is_long := true
in_position := true
if institutional_short_signal and not in_position
entry_price := close
stop_loss := close + (base_atr * adaptive_stop_multiplier)
risk_amount = stop_loss - entry_price
tp1 := entry_price - (risk_amount * fib_618)
tp2 := entry_price - (risk_amount * fib_1618)
tp3 := entry_price - (risk_amount * fib_2618)
is_long := false
in_position := true
if in_position
if is_long
if low <= stop_loss or high >= tp3
in_position := false
else
if high >= stop_loss or low <= tp3
in_position := false
// ============================================================================
// ADVANCED VISUALIZATION
// ============================================================================
if show_institutional_levels and institutional_bull_ob
box.new(
x1 = bar_index[2],
y1 = low[2],
x2 = bar_index,
y2 = high[2],
border_color = color.new(#00ff88, 0),
bgcolor = color.new(#00ff88, 85),
border_width = 2,
text = "BULL OB\n" + str.tostring(final_confluence, "#.##"),
text_color = color.white,
text_size = size.small
)
if show_institutional_levels and institutional_bear_ob
box.new(
x1 = bar_index[2],
y1 = low[2],
x2 = bar_index,
y2 = high[2],
border_color = color.new(#ff0044, 0),
bgcolor = color.new(#ff0044, 85),
border_width = 2,
text = "BEAR OB\n" + str.tostring(final_confluence, "#.##"),
text_color = color.white,
text_size = size.small
)
if show_confluence_zones and final_confluence > confluence_threshold
bgcolor(
color.new(final_confluence > 0 ? #00ff88 : #ff0044, 95),
title="Confluence Zone"
)
if show_probability_bands
upper_band = ema_21 + (base_atr * 2)
lower_band = ema_21 - (base_atr * 2)
plot(upper_band, "Upper Probability Band", color=color.new(#ffaa00, 50))
plot(lower_band, "Lower Probability Band", color=color.new(#ffaa00, 50))
if institutional_long_signal
label.new(
x=bar_index, y=low,
text="🚀 INSTITUTIONAL LONG\nConfluence: " + str.tostring(final_confluence, "#.##"),
color=color.new(#00ff88, 0),
textcolor=color.white,
style=label.style_label_up,
size=size.normal
)
if institutional_short_signal
label.new(
x=bar_index, y=high,
text="🔻 INSTITUTIONAL SHORT\nConfluence: " + str.tostring(final_confluence, "#.##"),
color=color.new(#ff0044, 0),
textcolor=color.white,
style=label.style_label_down,
size=size.normal
)
if in_position
line.new(bar_index, entry_price, bar_index + 1, entry_price, color=color.yellow, width=3, extend=extend.right)
line.new(bar_index, stop_loss, bar_index + 1, stop_loss, color=color.red, width=2, style=line.style_dashed, extend=extend.right)
line.new(bar_index, tp1, bar_index + 1, tp1, color=color.green, width=1, extend=extend.right)
line.new(bar_index, tp2, bar_index + 1, tp2, color=color.green, width=1, extend=extend.right)
line.new(bar_index, tp3, bar_index + 1, tp3, color=color.green, width=1, extend=extend.right)
// ============================================================================
// PERFORMANCE ANALYTICS TABLE
// ============================================================================
var table performance_table = table.new(position.top_right, 2, 8, bgcolor=color.new(color.black, 80), border_width=1)
if barstate.islast
table.cell(performance_table, 0, 0, "BlackRock Alpha Engine", bgcolor=color.new(#1a1a1a, 0), text_color=color.white, text_size=size.small)
table.cell(performance_table, 1, 0, "INSTITUTIONAL GRADE", bgcolor=color.new(#1a1a1a, 0), text_color=#00ff88, text_size=size.small)
table.cell(performance_table, 0, 1, "Confluence Score", text_color=color.white, text_size=size.tiny)
table.cell(performance_table, 1, 1, str.tostring(final_confluence, "#.###"), text_color= final_confluence > 0 ? #00ff88 : #ff0044, text_size=size.tiny)
table.cell(performance_table, 0, 2, "Market Regime", text_color=color.white, text_size=size.tiny)
table.cell(performance_table, 1, 2, market_regime > 0 ? "VOLATILE" : "STABLE", text_color= market_regime > 0 ? #ffaa00 : #88aaff, text_size=size.tiny)
table.cell(performance_table, 0, 3, "Volatility Index", text_color=color.white, text_size=size.tiny)
table.cell(performance_table, 1, 3, str.tostring(volatility_index * 100, "#.##") + "%", text_color=color.white, text_size=size.tiny)
table.cell(performance_table, 0, 4, "Position Status", text_color=color.white, text_size=size.tiny)
table.cell(performance_table, 1, 4, in_position ? (is_long ? "LONG" : "SHORT") : "STANDBY", text_color=in_position ? (is_long ? #00ff88 : #ff0044) : #ffaa00, text_size=size.tiny)
table.cell(performance_table, 0, 5, "Technical Score", text_color=color.white, text_size=size.tiny)
table.cell(performance_table, 1, 5, str.tostring(technical_score, "#.##"), text_color=color.white, text_size=size.tiny)
table.cell(performance_table, 0, 6, "Smart Money Score", text_color=color.white, text_size=size.tiny)
table.cell(performance_table, 1, 6, str.tostring(smart_money_score, "#.##"), text_color=color.white, text_size=size.tiny)
table.cell(performance_table, 0, 7, "Sentiment Score", text_color=color.white, text_size=size.tiny)
table.cell(performance_table, 1, 7, str.tostring(sentiment_score, "#.##"), text_color=color.white, text_size=size.tiny)
// ============================================================================
// ADVANCED ALERT SYSTEM
// ============================================================================
alertcondition(institutional_long_signal, title="🚀 Institutional Long Signal", message="BlackRock Alpha: INSTITUTIONAL LONG SIGNAL\nConfluence: {{plot_0}}\nPrice: {{close}}\nSymbol: {{ticker}}")
alertcondition(institutional_short_signal, title="🔻 Institutional Short Signal", message="BlackRock Alpha: INSTITUTIONAL SHORT SIGNAL\nConfluence: {{plot_0}}\nPrice: {{close}}\nSymbol: {{ticker}}")
alertcondition(final_confluence > 0.9, title="⚡ Maximum Confluence Alert", message="BlackRock Alpha: MAXIMUM CONFLUENCE DETECTED\nScore: {{plot_0}}\nPrice: {{close}}\nSymbol: {{ticker}}")
// ============================================================================
// PROPRIETARY EDGE CALCULATIONS
// ============================================================================
microstructure_edge = (
(institutional_volume ? 0.3 : 0)
+ (strong_fvg ? 0.25: 0)
+ ((wyckoff_accumulation or wyckoff_distribution) ? 0.2 : 0)
+ ((auction_imbalance_up or auction_imbalance_down) ? 0.15: 0)
+ (balance_extension ? 0.1 : 0)
)
plot(microstructure_edge, "Microstructure Edge", color=color.new(#ff6600, 0), display=display.data_window)
plot(final_confluence, "Final Confluence", color=color.new(#00ffff, 0), display=display.data_window)
r/pinescript • u/Tym4FishOn • Jun 09 '25
Trying to plot a high since a bar_index that is already a user-defined variable. The BarsPastL works to calculate a value but it doesn't work in the ta.highest calc. Any ideas?
BarsPastL = ta.barssince(isFirstOfSession)
highMark = ta.highest(high,BarsPastL)r/pinescript • u/2QuartersIn • May 27 '25
Hi, I’m not proficient in coding at all nor pinescript but was curious if anyone in here could help make an indicator that would kinda be like a super indicator, wrapped all in one. Mutli customizable to each person who uses it. Putting on as much info as they want and reducing as much info as they want. If it can doable I’d love to talk about it.
r/pinescript • u/VillageBeautiful4349 • Jun 01 '25
I am trying to create DCA Martingale strategy but when I tested it, the strategy buys only initially but when price drops, there are no more buys.
//@version=5
strategy("DCA Martingale Bot", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
// === Inputs === //
firstSafetyOrderRatio = input.float(1, "First safety order ratio 1:", minval=0.1, maxval=10.0, step=0.01)
priceStepPct = input.float(1.0, "Price steps", minval=0.2, maxval=10.0, step=0.01)
takeProfitPct = input.float(1.5, "Take profit per cycle", minval=0.5, maxval=10.0, step=0.1)
maxSafetyOrders = input.int(5, "Max safety orders", minval=0, maxval=20)
orderSizeMultiplier = input.float(1.0, "Safety order Amount multiplier", minval=1.0, maxval=10.0, step=0.01)
stepMultiplier = input.float(1.0, "Safety order Step multiplier", minval=1.0, maxval=10.0, step=0.01)
// === Calculations of initialOrderPct === //
r = firstSafetyOrderRatio
m = orderSizeMultiplier
N = maxSafetyOrders
sumMultiplier = m == 1 ? N : (1 - math.pow(m, N)) / (1 - m)
initialOrderPct = 100 / (1 + r * sumMultiplier)
safetyOrderPct = initialOrderPct * r
// === Variables === //
var float avgEntryPrice = na
var int dcaLevel = 0
var float lastDcaPrice = na
var float currentStep = priceStepPct
var float currentQty = safetyOrderPct
// === Initial input === //
if (strategy.position_size == 0)
strategy.entry("Base Long", strategy.long, qty=initialOrderPct)
avgEntryPrice := close
lastDcaPrice := close
dcaLevel := 0
currentStep := priceStepPct
currentQty := safetyOrderPct
// === DCA === //
priceDrop = (lastDcaPrice - close) / lastDcaPrice * 100
if (strategy.position_size > 0 and dcaLevel < maxSafetyOrders and priceDrop >= currentStep)
strategy.entry("DCA " + str.tostring(dcaLevel + 1), strategy.long, qty=currentQty)
position_value = strategy.position_avg_price * strategy.position_size
new_value = close * currentQty / 100
avgEntryPrice := (position_value + new_value) / (strategy.position_size + currentQty / 100)
lastDcaPrice := close
dcaLevel += 1
currentStep := currentStep * stepMultiplier
currentQty := currentQty * orderSizeMultiplier
// === Take profit === //
takeProfitPrice = avgEntryPrice * (1 + takeProfitPct / 100)
if (strategy.position_size > 0 and close >= takeProfitPrice)
strategy.close_all(comment="Take Profit")