Chiến lược Pine Script®
Chỉ báo và chiến lược
SPY 200SMA +4% Entry -3% Exit TQQQ/QLD/GLDM THREE PHASE STRATEGYWanted to take a look at all of the individual trades and provide a series of options to balance performance and risk. This post is expanding on my previous one - www.reddit.com
Here is the data and the backtesting splitting the strategy into three primary phases with multiple options and exact trade dates to help people easily backtest other combinations - docs.google.com (Three Tabs with the three phases)
If you just want my personal recommendations this would be what I will be using -
PHASE 1 (Strategy BUY signal triggers when SPY price crosses +4% over the SPY 200SMA) = 100% TQQQ
If trade lasts 366 days (Long Term Cap Gains) go to PHASE 2
If SPY price crosses below -3% SPY 200SMA go to PHASE 3
PHASE 2 (PHASE 1 lasts 366 days) = Deleverage and diversify into 50% QLD & 50% GLDM
PHASE 3 (Strategy SELL signal triggers when SPY price crosses -3% below the SPY 200SMA) = Defensive posture with 50% SGOV & 50% GLDM
As market degrades start selling SGOV and buying QQQ until 50% QQQ & 50% GLDM
TradingView Script for the THREE PHASE STRATEGY (imgur.com):
//
@version=
5
strategy("SPY 200SMA +4% Entry -3% Exit Strategy",
overlay=true,
default_qty_type=strategy.percent_of_equity,
default_qty_value=100)
// === Inputs ===
smaLength = input.int(200, title="SMA Period", minval=1)
entryThreshold = input.float(0.04, title="Entry Threshold (%)", step=0.01)
exitThreshold = input.float(0.03, title="Exit Threshold (%)", step=0.01)
startYear = input.int(1995, "Start Year")
startMonth = input.int(1, "Start Month")
startDay = input.int(1, "Start Day")
// === Time filter ===
startTime = timestamp(startYear, startMonth, startDay, 0, 0)
isAfterStart = time >= startTime
// === Calculations ===
sma200 = ta.sma(close, smaLength)
upperThreshold = sma200 * (1 + entryThreshold)
lowerThreshold = sma200 * (1 - exitThreshold)
// === Strategy Logic ===
enterLong = close > upperThreshold
exitLong = close < lowerThreshold
if isAfterStart
if enterLong and strategy.position_size == 0
strategy.entry("Buy", strategy.long)
if exitLong and strategy.position_size > 0
strategy.close("Buy")
// === 366-Day Marker Logic (Uninterrupted) ===
var
int
targetTime = na
// 1. Capture entry time only when a brand new position starts
if strategy.position_size > 0 and strategy.position_size == 0
targetTime := time + (366 * 24 * 60 * 60 * 1000)
// 2. IMPORTANT: If position is closed or a sell signal hits, reset the timer to "na"
if strategy.position_size == 0
targetTime := na
// 3. Trigger only if we are still in the trade and hit the timestamp
isAnniversary = not na(targetTime) and time >= targetTime and time < targetTime
// === Visuals ===
p_sma = plot(sma200, title="200 SMA", color=color.rgb(255, 0, 242))
p_upper = plot(upperThreshold, title="Entry Threshold (+4%)", color=color.rgb(0, 200, 0))
p_lower = plot(lowerThreshold, title="Exit Threshold (-3%)", color=color.rgb(255, 0, 0))
fill(p_sma, p_upper, color=color.new(color.green, 80), title="Entry Zone")
// Draw marker only if 366 days passed without a sell
if isAnniversary
label.new(bar_index, high, "366 DAYS - PHASE 2", style=label.style_label_down, color=color.yellow, textcolor=color.black, size=size.small)
// === Entry/Exit Labels ===
newOpen = strategy.position_size > 0 and strategy.position_size == 0
newClose = strategy.position_size == 0 and strategy.position_size > 0
if newOpen
label.new(x=bar_index, y=low * 0.97, text="BUY - PHASE 1", xloc=xloc.bar_index, yloc=yloc.price, color=color.lime, style=label.style_label_up, textcolor=color.black, size=size.small)
if newClose
label.new(x=bar_index, y=high * 1.03, text="SELL - PHASE 3", xloc=xloc.bar_index, yloc=yloc.price, color=color.red, style=label.style_label_down, textcolor=color.white, size=size.small)
200 SMA SPY Trading Range Bands Script:
//
@version=
5
indicator("200 SMA SPY Trading Range Bands", overlay=true)
// === Settings ===
smaLength = input.int(200, title="SMA Length")
mult1 = input.float(1.09, title="Multiplier 1 (9% Over)")
mult2 = input.float(1.15, title="Multiplier 2 (15% Over)")
// === Calculations ===
smaValue = ta.sma(close, smaLength)
line9Over = smaValue * mult1
line15Over = smaValue * mult2
// === Plotting ===
plot(smaValue, title="200 SMA", color=color.gray, linewidth=1, style=plot.style_linebr)
plot(line9Over, title="9% Over 200 SMA", color=color.rgb(255, 145, 0), linewidth=1)
plot(line15Over, title="15% Over 200 SMA", color=color.rgb(38, 1, 1), linewidth=2)
Chiến lược Pine Script®
Thuan_Bot_Scap V2Apply the Script: Open the Pine Editor, paste the code, and click "Add to Chart" to initialize the strategy on your desired timeframe.
Set the Timeframe: For optimal scalping results, this strategy is best utilized on lower timeframes such as 1-minute or 5-minute charts.
Configure RSI Parameters: Adjust the RSI Length and extreme levels (Oversold/Overbought) in the settings menu to match the current market volatility.
Manage Trade Values: Customize your Take Profit (TP) and Stop Loss (SL) values under the "Trade Settings" group to align with your risk management plan.
Monitor the Dashboard: Use the on-screen Dashboard to track real-time performance metrics, including the total number of closed trades and historical win rate.
Identify Entry Signals: Look for the horizontal signal lines and visual boxes; a Green box represents a Long position, while a Red box indicates a Short position.
Verify Visual Levels: Ensure the TP (Green Label) and SL (Red Label) are correctly positioned relative to your Entry (Blue Label) on the active candle.
Adjust Dashboard Placement: You can change the Dashboard’s position (e.g., Top Right or Bottom Left) in the inputs to prevent it from obstructing price action.
Observe Price Action Patterns: The strategy triggers entries based on a combination of RSI momentum and candle formations like Pin Bars or Engulfing patterns.
Analyze Historical Performance: Use the built-in "Strategy Tester" tab at the bottom of TradingView to review how the parameters performed during past market conditions.
Chiến lược Pine Script®
Takashi Kotegawa Dip Reversal StrategyYou can use this alongside my other indicator to see if a stock is good with the indicator.
Chiến lược Pine Script®
Long & Short Trading Strategy This strategy trades both long and short positions based on EMA (Exponential Moving Average) and ATR (Average True Range). The strategy uses 100% of equity per trade and displays visual entry and stop-loss lines on the chart.
Backtest Configuration
The strategy allows users to define a custom backtest period through input parameters for start and end dates (day, month, year). The default period runs from January 1, 2005, to December 31, 9999, with a time-based filter ensuring trades only execute within the specified range.
Core Strategy Parameters
Two key configurable parameters control the strategy: EMA/ATR Length ((CUSTOMIZATION ALLOWED)) and ATR Multiplier ((CUSTOMIZATION ALLOWED)). These determine the calculation of the bull and bear trigger levels around the moving average.
Stop Loss Management
The strategy implements a fixed stop loss system measured in points (CUSTOMIZATION ALLOWED). This applies to both long and short positions, with separate exit commands for each position type to manage risk.
Visual Line Customization
Users can customize the appearance of entry and stop-loss lines, including their length in candles (default 15), line width (1-4), and colors. Entry lines default to blue, while stop-loss lines default to red.
Chiến lược Pine Script®
SPY Quant ML + Session Filter Strategy [CocoChoco]S&P 500 Quant: Machine Learning & Mean Reversion (Session-Filtered)
Overview
This is a professional-grade quantitative strategy designed specifically for the S&P 500. It combines classical statistical mean reversion (Z-Score) with a modern Machine Learning filter and rigorous institutional-grade risk management.
The strategy is optimized for traders who prioritize high win rates and capital preservation, specifically avoiding the "gap risk" associated with holding positions overnight.
Core Methodology
1. Statistical Entry (The Z-Score Engine)
The strategy identifies "oversold" conditions in a bullish context. It calculates the Z-Score of the price relative to its 20-period Mean (SMA). By default, it looks for a -1.2 Standard Deviation extension, signaling a high-probability "dip" ripe for a snap-back to the mean.
2. Trend & ML Filters
To avoid "catching a falling knife," the strategy uses two layers of confirmation:
Trend Filter: Only takes Long positions when the price is above the 200-period SMA, ensuring we only buy dips in a confirmed uptrend.
ML Correlation Filter: A Machine Learning-inspired module that analyzes the correlation between RSI and Volatility (ATR). It only permits entries when market internal dynamics suggest a reversal is technically "healthy."
3. Institutional Risk Management
This script is built for "safety-first" automation:
Hard Stop Loss: Fixed at 1.5% to protect against sudden market shocks.
Active Trailing: A dual-trigger trailing stop. It activates once the price touches the 20 SMA (The Mean) OR once a trade reaches a 0.50% profit threshold. This ensures near-winners are protected and large runners are captured.
Intraday Circuit Breaker: Includes a Max Daily Drawdown (2%) limit. If hit, the script automatically closes losing positions and halts trading for the day, while allowing winning positions to continue.
Key Features
Session-Specific: Tailored for the US Trading Session (UTC/NY times).
Zero Overnight Risk: Automatically flattens all positions before the market close (16:00 NY Time).
Holiday Intelligence: Hard-coded logic for US Market Holidays and Early Closes (2026–2028), ensuring the bot doesn't get stuck in illiquid holiday markets.
Hourly Entry Cap: Limits entries to one per hour to prevent over-concentration during a single price leg.
How to Use
Timeframe: I suggest you use it on the 5-minute or 1-hour timeframe for optimal results.
Instrument: Designed for the S&P 500, but highly effective on SPY, IVV, and ES (Futures).
Pyramiding: Designed to handle up to 3 concurrent positions, allowing the strategy to scale into a move as the Z-Score deepens.
Automation Ready
This script is fully compatible with webhook-based automation tools. All signals (Entry, SL, Trail, Market Close, and Daily Limit) are clearly labeled in the Alert comments for seamless execution. I haven't tasted it though. This is not financial advice. Please perform your own tests and manage your risk.
Disclaimer
Past performance does not guarantee future results. This script is a tool for quantitative analysis and should be used as part of a broader diversified trading plan.
Chiến lược Pine Script®
US30 AsianRange 1900-0000 LIMIT OCO (1pct risk) 120 fib 30/150asian sweep at the 120 fib, aiming for 150 pips long and short buy limits set, once one is hit for the day cancel the opposite limit straight away
Chiến lược Pine Script®
High Breakout PRO Huy Hoang Trader
High Breakout PRO - Strategy Description
## 🚀 Overview
**High Breakout PRO** is a professional-grade Trend Following strategy designed to capture major market moves while strictly managing risk. Built on the core philosophy of "Price Action Breakouts," this script enhances the classic Donchian Channel breakout method with modern risk management tools like the **Hybrid Exit** and **EMA Trend Filter**.
This strategy is optimized for **Gold (XAUUSD)**, **Bitcoin (BTC)**, and **Major Stocks (AAPL, AMZN)** on **H4 and Daily** timeframes.
## 💎 Key Features
1. **Trend Filter (EMA):** Only takes long positions when the price is above the 200-period EMA. This filters out counter-trend noise and significantly improves winning probability.
2. **Hybrid Exit Mechanism ("Holy Grail"):** A unique dynamic trailing stop that combines:
* **Price Structure:** Uses the lowest low of the last Y bars (Donchian Support).
* **Volatility:** Uses ATR-based trailing (Chandelier Exit logic).
* *Logic:* The system automatically chooses the **tighter** (higher) stop level between the two, ensuring you lock in profits rapidly during strong volatility while giving the trade room to breathe during accumulation.
3. **Professional Visuals:** A refined "Wealth & Earth" themes (Gold/Silver/Brown) specifically designed to reduce eye strain and provide clear, professional signal visibility without chart clutter.
## 🛠 Strategy Logic
### entry rules
* **Breakout:** Price closes above the Highest High of the last `X` bars (Default: 20).
* **Trend Confirmation:** Closing Price > EMA 200 (Configurable).
### Exit Rules
* **Dynamic Stop Loss:** The trade is closed when price breaches the **Hybrid Trailing Stop**.
* The Trailing Stop never moves down. It only moves up as price increases.
* It effectively adapts to both slow-grinding trends and explosive spikes.
## ⚙️ Best Settings (Recommended)
* **Timeframe:** H4 (Swing Trading) or Daily (Position Trading).
* **Entry Period (X):** 20
* **Exit Period (Y):** 10
* **Trend Filter:** ON (EMA 200)
* **Risk Management:** Hybrid Mode (ATR Multiplier 3.0)
## ⚠️ Disclaimer
This strategy follows trends. It may experience drawdowns during choppy/sideways markets. Always use proper risk management (position sizing) and backtest on your specific asset before live trading.
---
*Developed by Huy Hoang Trader. Empowering traders with institutional-grade tools.*
Contact for work: www.facebook.com
Chiến lược Pine Script®
Blockcircle MTE V3 - Momentum Trading EngineOVERVIEW
This BLOCKCIRCLE MOMENTUM TRADING ENGINE (MTE V3) answers a question most trading systems ignore: is the broader market environment actually favorable for the trade you are about to take? Rather than applying indicators directly to price and hoping conditions align, the MTE V3 first evaluates macro market regime through a proprietary scoring system, then confirms entries with traditional momentum filters only after macro conditions pass.
WHAT MAKES THIS TRADING ENGINE DIFFERENT AND ORIGINAL
Standard momentum strategies apply RSI or similar oscillators to a single asset and generate signals when thresholds are crossed. This fails to account for whether the overall market supports the trade direction. A long signal on an altcoin means little if Bitcoin dominance is rising and crypto is underperforming equities.
This engine solves that problem with a two-layer filtering system:
Layer One is the proprietary Altcoin Market Scorecard. It pulls Heikin-Ashi data for 11 symbols, including Bitcoin dominance, stablecoin flows, the Dollar Index, and crypto performance relative to the S&P 500, Nasdaq, and Russell 2000. Each symbol receives a proprietary weight between 2.5 and 20 based on its historical correlation with altcoin momentum. The algorithm evaluates candle direction and swing structure to assign bullish, bearish, or neutral status to each metric, producing a composite score from 0 to 100 that represents overall market risk appetite.
Layer Two applies technical filters only after macro conditions pass. Eighteen indicator slots cover RSI, MFI, CMF, a proprietary T3-smoothed CCI oscillator, price change percentage, and candle color. Each slot supports custom symbols, custom timeframes, Heikin-Ashi mode, lookback scanning, and multi-bar confirmation.
The Synergy: entries require BOTH layers to pass. The scorecard prevents entering trades during unfavorable macro regimes. The technical layer prevents chasing extended moves when macro conditions are favorable. Neither layer alone produces the same filtering quality as both together.
Additional proprietary elements include pivot-based trend-line break detection with automatic construction and volume-confirmed breaks; a six-method exit system combining fixed stops, trailing stops, opposite signal exits, scorecard deterioration exits, and time-based exits; and an on-chart performance table that calculates Sharpe ratio, Sortino ratio, and drawdown from monthly equity returns.
HOW TO USE
Enable the Altcoin Market Scorecard and set a score threshold. Higher thresholds for longs require stronger macro confirmation and reduce trade frequency. Add one or two technical conditions, such as RSI below 30 for long entries, to filter for oversold readings on the asset. The combination ensures you only enter when both macro regime and asset momentum align.
Test configurations across multiple date ranges using the performance table. Sharpe ratios above 1.0 and profit factors above 1.5 generally indicate robust setups. Adjust stop-loss and trailing-stop parameters based on asset volatility.
Here is a simple example of how you would modify the exit criteria for when to go LONG vs when to go SHORT
DISCLAIMER
This strategy is for educational and informational purposes only. It does not constitute financial advice. Trading involves risk, and past performance does not guarantee future results. Only trade with capital you can afford to lose.
Chiến lược Pine Script®
Chiến lược Pine Script®
Shock Gap Bot [Enhanced]Shock Gap bot this to provide entry for pre market stocks , so you can get the bounce back
Chiến lược Pine Script®
Testthis is a test script
bool newClosed = strategy.closedtrades > strategy.closedtrades
if newClosed
int last = strategy.closedtrades - 1
// 最新平仓 trade 的关键信息
string eid = strategy.closedtrades.entry_id(last)
float epx = strategy.closedtrades.entry_price(last)
string xid = strategy.closedtrades.exit_id(last)
float xpx = strategy.closedtrades.exit_price(last)
float pnl = strategy.closedtrades.profit(last) // 注意:单位是策略币种/合约计价(受 commission 等影响)
// 判断是不是“止损”触发(看 exit_id)
bool isStop = str.startswith(xid, "S_SL_")
string msg = "CLOSED TRADE (new) " +"entry: " + eid + " @ " + str.tostring(epx) + " " +"exit : " + xid + " @ " + str.tostring(xpx) + " " +"pnl : " + str.tostring(pnl) + " " +"isStop=" + str.tostring(isStop)
label.new(bar_index, high, msg, style=label.style_label_down, textalign=text.align_left)
Chiến lược Pine Script®
Marvis Gold 10.0Overview Marvis Gold 10.0 is a specialized trend-following system designed specifically for the unique volatility characteristics of Gold (GLD / XAUUSD). Unlike high-frequency scalpers that get eaten alive by spread and commission, this strategy prioritizes Efficiency. It sits on the sidelines during noise and strikes aggressively only when a high-probability trend is confirmed.
Core Philosophy: "Earn the Right to Risk" The defining feature of this engine is its Profit-Driven Position Sizing.
Safety Mode: The strategy begins every campaign with a defensive posture to protect initial capital.
Beast Mode: Only after the strategy has secured a "Safety Buffer" of realized profits does it unlock its full dynamic leverage capabilities. This allows the account to compound rapidly during strong bull runs while remaining conservative during drawdowns.
Key Features
Trend Pyramiding (The Compounder)
We do not average down. We do not catch falling knives.
Marvis 10.0 adds to winning positions only when the trend accelerates. This asymmetric approach ensures that our winning trades are significantly larger than our losing trades.
Macro & Momentum Filtration
A dual-layer filter system prevents the strategy from trading during choppy, sideways markets. It requires both Macro Trend alignment and immediate Momentum confirmation before executing a signal.
Intraday Crash Protection (The Circuit Breaker)
Black swan events happen. The strategy includes a hard-coded "Panic Exit" that monitors intraday volatility tick-by-tick. If a liquidity crash occurs, the strategy liquidates positions instantly to preserve capital, regardless of technical indicators.
No Repainting
All entry and exit signals are calculated on confirmed bar closes (except the emergency Crash Protection). What you see on the backtest is exactly how the logic executes live.
Performance Profile
High Profit Factor: Designed to achieve a high return per dollar risked.
Low Frequency: Reduces commission drag by holding trades for days or weeks.
Objective: Outperform standard "Buy & Hold" returns by avoiding major bear market drawdowns.
How to Use
Asset: Best suited for GLD .
Timeframe: Optimized for the Daily (1D) chart.
Alerts: Compatible with "Order Fills Only" for automation.
Disclaimer: Past performance is not indicative of future results. Gold is a volatile asset class. This script is for educational purposes and quantitative analysis only; use it at your own risk.
Chiến lược Pine Script®
Quantum X Strategy (with Alert.)Quantum X Strategy — Expanded Description
Quantum X Strategy is a carefully structured market-participation framework designed to initiate trades only when strong directional alignment is detected across multiple independent market dimensions.
Unlike reactive or single-indicator systems, this strategy evaluates the broader market context to ensure participation only under conditions with a higher probability of meaningful directional movement.
Random or partial signals are ignored, with the system prioritizing structured, high-quality opportunities over trade frequency.
Structural Design
The strategy’s decision-making process is based on a multi-dimensional analysis of price behavior:
Directional Alignment: Multiple independent market behaviors are evaluated collectively to determine bullish or bearish intent.
Weighted Contribution: Each component contributes independently to an internal alignment score. Trades are considered only when the combined state reaches a meaningful threshold.
Quality Filtering: Low-quality, ambiguous, or unstable conditions are filtered out to reduce exposure during uncertain market phases.
This structure ensures that no single condition can trigger a trade on its own, maintaining discipline, consistency, and robustness in execution.
Trade Dynamics
Trade Activation: Trades are initiated only when internal alignment reaches a significant level of directional consensus. Partial or weak signals are ignored.
Trade Closure & Reversal: Positions are dynamically closed when alignment weakens or when a directional bias reversal is detected. The system is designed to reverse positions rather than stack trades.
Market Inactivity: During periods of indecision, low volatility, or insufficient directional clarity, the strategy remains inactive to avoid overtrading.
Backtesting Context
The strategy is restricted to post-January 2025 market data to ensure relevance to current volatility structures and market behavior.
Older regimes are intentionally excluded to maintain realistic and contemporary performance evaluation.
Intended Use
Instrument: MIDCAPNIFTY Futures
Timeframe: 15-Minute
Application: Intraday trading and short-term directional participation
Position Size: 1 lot (120 quantity)
Initial Capital (Backtest Reference): ₹10,000
Risk Management: Designed to be used alongside independent stop-loss, position sizing, and capital allocation rules defined by the user
Strict adherence to the system’s signals is recommended. Manual overrides may compromise the integrity of the framework.
Dhan In-Built Execution (Usage Summary)
This strategy supports alert-based automated execution via Dhan, using TradingView webhooks.
TradingView generates alerts only
Order execution is handled externally via Dhan’s system
TradingView does not place trades directly
Futures Quantity Logic (Important)
MIDCAPNIFTY 1 lot = 120 quantity
Because the strategy uses reversal logic:
If you want to trade 1 lot, set quantity = 2
One quantity is used to exit the existing position
The second quantity creates the new reversed position
Contract Symbol Mapping
Current month: MIDCPNIFTY1!
Next month: MIDCPNIFTY2!
Far month: MIDCPNIFTY3!
To trade a different expiry, simply replace the symbol in the input field accordingly.
Intellectual Property Notice
The internal scoring model, alignment logic, weighting structure, and activation thresholds are intentionally abstracted to protect the originality and intellectual property of the strategy.
This prevents direct replication while still allowing conceptual understanding for evaluation and moderation.
Disclaimer
This strategy is provided strictly for educational, research, and backtesting purposes only.
Market conditions change over time, and past performance does not guarantee future results.
Users are solely responsible for forward testing, capital deployment, risk control, and compliance with broker and platform rules before using the strategy in live environments.
Moderator-Friendly Expanded Summary
Instrument & Timeframe: MIDCAPNIFTY, 15-Minute
Start Date: January 2025 onward
Position Size: 1 lot (120 quantity)
Initial Capital: ₹10,000
Commission & Slippage: 0.01% commission, 2-point slippage
Trade Logic: Multi-dimensional internal alignment model
Trade Activation: Only when strong directional consensus is achieved
Trade Closure: Alignment deterioration or trend bias reversal
Market Inactivity: Passive during low-information or ambiguous phases
Execution: Alert-based, via third-party (Dhan) webhook system
Risk Management: User-defined stop-loss and capital allocation required
IP Protection: Internal logic abstracted
Purpose: Educational, research, and demonstration use only
Chiến lược Pine Script®
TSLA ORB + VWAP + Squeeze Momentum (v6)The optimization logic (what to tweak first)
Since your problem is profit too low, optimize in this exact order:
Chiến lược Pine Script®
Session Liquidity Reversion Strategy (Asia Range False Breakout)Overview
This strategy is based on a session-driven liquidity hypothesis rather than a simple indicator combination.
During the Asian trading session, many markets enter a low-liquidity equilibrium, forming a relatively narrow price range. When higher-volume participants enter during the London and New York sessions, price often performs false expansions beyond this Asian range before reverting back toward fair value.
This script systematically identifies and trades those failed session expansions.
Core Concept
The strategy operates in three distinct phases:
Asia Session Range Formation
The high and low of the Asian session are recorded.
This range represents a temporary balance area formed under reduced participation.
Range Locking
Once the Asian session ends, the range is frozen.
No repainting or forward-looking calculations are used.
False Breakout Detection & Reversion
During the London/New York session, price must break beyond the Asia range and fail to hold.
A momentum filter (RSI) confirms rejection strength.
Trades are entered only after price closes back inside the range, targeting reversion rather than continuation.
This approach avoids chasing breakouts and instead focuses on liquidity traps and failed expansions.
Risk Management & Assumptions
Risk parameters are intentionally conservative and realistic:
Position sizing uses percentage of equity
Default risk per trade is approximately 2%
Stop losses are ATR-based, adapting to volatility
Risk-to-reward is fixed and configurable
Realistic commission and slippage are included
One trade per session is allowed to avoid over-exposure
No martingale, grid, or averaging logic is used.
Usage Notes
Recommended timeframes: 5m – 30m
Designed for: Forex, Indices, Crypto
Performance will vary by instrument and session volatility
All parameters are configurable for research and optimization
This strategy is intended for educational and research purposes, demonstrating how session-based liquidity behavior can be tested systematically using Pine Script.
Chiến lược Pine Script®
ETH Scalping Bot V2.1(normal) [Tori System]🚀 ETH Scalping Strategy v2.1 (Major Update) "Stop Gambling. Start Automating."
Are you tired of emotional trading and staring at charts 24/7? This is the v2.1 Updated Version of my high-winrate scalping strategy. We have significantly improved the logic to make it safer and more profitable in volatile markets.
This strategy is designed for fully automated trading via alerts (Signal -> Whop -> Execution).
💎 What's New in v2.1? (Update Log)
1. ⚡ "Fast Fail-Loss" Logic Added We introduced a smart cut-loss mechanism.
Previously, the bot might hold a losing position hoping for a reversal.
Now: If the momentum fades or a false breakout is detected, the bot instantly closes the trade to minimize drawdown. Small losses, Big wins.
2. 🛡️ Enhanced Stability We optimized the parameters to filter out market noise (chop). The equity curve is now much smoother and safer for long-term compounding.
🔥 Key Features
✅ No Repainting: What you see in the backtest is what you get in real-time. ✅ High Net Profit: Optimized for compounding growth (See the backtest results above). ✅ Automated Ready: Perfect for connecting with Binance/Bybit via 3rd party tools. ✅ Risk Management: Built-in Stop Loss and Trailing Profit logic.
🤖 How to get Access?
This script is Invite-Only. To start automating your trading with this strategy, please check the link in my Signature below or visit my Profile.
👉 Check the "Signature" section below 👇 (Or click my profile name to find the website link)
⚠️ Disclaimer
Past performance does not guarantee future results.
This script is for educational purposes. Always test with paper trading first.
Cryptocurrency trading involves high risk.
Chiến lược Pine Script®
Swing Strategy Feature Set B [theEccentricTrader]█ OVERVIEW
This swing strategy is part of a broader research and exploration framework designed to encourage users to experiment with a variety of technical concepts and evaluate the comparative effectiveness of different strategy configurations. For example, users can first configure a core strategy as a benchmark, then iteratively test a range of feature configurations as additional entry conditions and compare their performance against one another and against the core strategy.
Feature Set B includes concepts beginning with the letter "B" and forms part of a larger swing strategy suite that covers a wide range of technical concepts. The objective of the suite is not curve-fitting, but rather structured experimentation, exploration and statistical validation (or invalidation) of technical concepts.
Concepts exclusive to the feature set are as follows:
Balance of Power
Bollinger Bands
█ OPERATIONAL
Initial Capital
The initial capital is defined as a monetary value denominated in a given base currency.
The default initial capital is set to 100,000.
The default base currency is set to the selected symbol's default base currency.
Users can adjust the initial capital and select an alternative base currency via strategy Settings/Properties.
Risk as Percentage of Equity
The equity is defined as the sum of initial capital, net profit and open profit.
The risk is defined as a percentage of equity per-trade. As a result, net profit outcomes are subject to compounding effects over time.
The default risk is set to 1% of equity.
Users can adjust the strategy's per-trade risk via strategy Settings/Inputs/STRATEGY.
For further information on how the risk is applied in practice, refer to the position sizing section below.
Unit of Value
The unit of value is defined as a decimal precision factor that converts user-defined point or pip distances into actual price units used by the selected symbol.
Different symbols express price movement using different conventions. For example, some symbols are quoted directly in whole price points, while others use pips or fractional point increments. The unit of value provides a normalisation layer that allows all distance-based logic in the strategy to operate consistently across symbols.
Examples:
A unit of value of 1 corresponds to a price increment of 1.0.
A unit of value of 10 corresponds to a price increment of 0.1.
A unit of value of 100 corresponds to a price increment of 0.01.
A unit of value of 1000 corresponds to a price increment of 0.001.
A unit of value of 10000 corresponds to a price increment of 0.0001.
Users should consult their broker’s published symbol specifications to confirm how price movement is defined for the symbols they intend to backtest. Incorrect configuration of the unit of value may result in misaligned stop distances, targets and/or risk calculations.
The default unit of value is set to 1.
Users can adjust the unit of value via strategy Settings/Inputs/STRATEGY.
Stop Buffer
The stop buffer is defined as the number of points or pips beyond a stop loss level required for the level to be considered clearly breached.
The default stop buffer is set to 0 points/pips.
Users can adjust the stop buffer via strategy Settings/Inputs/STRATEGY.
Risk Range
The risk range is defined as the difference between the entry price and the stop loss price (inclusive of the stop buffer) for any given trade.
Position Sizing
Position sizing determines the quantity of contracts, shares or units opened for each trade based on the user-defined risk and the selected symbol’s pricing structure.
"syminfo.pointvalue" is a built-in Pine Script variable that defines the number of underlying units contained within a single contract for any given symbol, and is critical for accurate position size calculations.
The position size is calculated as follows:
The risk range is multiplied by the syminfo.pointvalue to convert the price movement into its monetary equivalent.
The user-defined risk amount (expressed as a percentage of equity) is divided by this monetary risk per unit to determine the position size.
This ensures that each trade risks a consistent proportion of account equity regardless of point or pip based quoting conventions, symbol price scale or contract specifications.
While the strategy targets a fixed percentage of equity risk per-trade, the exact risk applied cannot always be matched precisely due to symbol-specific constraints such as contract sizing and margin requirements. In these cases, the strategy opens the largest permissible position that does not violate operational constraints, resulting in a realised risk that is as close as possible to the user-defined risk without exceeding it.
For further information on the syminfo.pointvalue variable, please refer to:
www.tradingview.com
Margin
The margin is defined as the minimum percentage of a position’s notional value that must be covered by the strategy’s available equity in order for TradingView's strategy tester to simulate opening and maintaining that position. For example, a margin setting of 25% means the simulated account must hold equity equal to at least 25% of the position’s notional value in order to enter or maintain that trade, the remaining 75% is considered provided by the simulated broker.
A lower margin percentage allows the account to open larger positions relative to its equity, because the required equity portion is smaller. Conversely, a higher margin percentage demands more of the account's equity be committed to any given position.
When the account’s equity falls below the required margin, the strategy tester emulates a margin call event, in which the broker emulator forcibly closes or reduces positions so that remaining positions no longer exceed available equity relative to the margin requirement. This behaviour is documented as part of TradingView’s margin/leverage feature for strategies.
Margin settings in a strategy are used solely for simulation purposes and do not automatically match any broker’s real-world margin requirements (which can vary by broker, asset class and symbol). Users should consult their broker’s published specifications for further details.
The default margin is set to 25% for both long and short positions.
Users can adjust the margin for long and short positions independently via strategy Settings/Properties/MARGIN.
For further information on the strategy tester's margin functionality, please refer to:
www.tradingview.com
www.tradingview.com
Pyramiding
The pyramiding count is defined as the maximum number of open positions permitted at any one time. TradingView's strategy tester does not facilitate hedging, as such, long entries will close any open short positions and short entries will close any open long positions.
The default pyramiding count is set to 100.
Users can adjust the pyramiding count via strategy Settings/Properties.
For further information on TradingView's strategy tester and broker emulator, please refer to:
www.tradingview.com
Spread
The spread is defined as the difference between a given symbol's bid (buy) price and ask (sell) price.
Typical spreads vary by broker and symbol. Some brokers offer fixed spreads on certain symbols, while others offer variable spreads that fluctuate with market conditions. Users should consult their broker's published specifications for further details.
Commission
The commission is defined as a transaction cost applied by a broker and may be expressed as a percentage of position size, a per-contract fee or a fixed fee per-transaction.
Commission structures vary by broker and symbol. Some brokers charge no explicit commission and instead generate revenue through the spread or other indirect sources, while others will typically apply one of the three aforementioned commission types, depending on the product offered. Users should consult their broker's published specifications for further details.
The default commission is set to 0.005% of position size.
Users can select and adjust the commission type via strategy Settings/Properties/COST SIMULATION.
█ CORE STRATEGY
Green and Red Candles
A green candle is defined as a candle that closes at or above its open price and a red candle is defined as a candle that closes below its open price.
Swing Highs and Swing Lows
A swing high is defined as a green candle, or a series of consecutive green candles, followed by a single red candle that completes the swing and forms the peak.
A swing low is defined as a red candle, or a series of consecutive red candles, followed by a single green candle that completes the swing and forms the trough.
Peak and Trough Prices
The peak price of a complete swing high is either the high of the red candle that completes the swing high or the high of the preceding green candle, depending on which is higher.
The trough price of a complete swing low is either the low of the green candle that completes the swing low or the low of the preceding red candle, depending on which is lower.
Fixed Reward-to-Risk
Fixed reward-to-risk is defined as a user-defined reward multiple for a given unit of risk.
Variable Reward-to-Risk
Variable reward-to-risk is defined as a path-dependent reward multiple for a given unit of risk.
Swing High Swing Low (SHSL) Strategy
The SHSL strategy uses swing lows for core long entry conditions and swing highs for core short entry conditions. The strategy is designed for standard OHLC candlestick charts only and will not behave as intended on other chart types.
All entries are processed at candle close and use the candle close price for the entry price.
Long stop losses are anchored to the most recent trough and short stop losses are anchored to the most recent peak.
Users can choose between long-only and short-only configurations, or alternatively simulate trades in both directions (long-short). However, when the "Both" option is selected, long entries will close any open short positions and short entries will close any open long positions (as mentioned in the pyramiding sub-section above). This can and will result in variable reward-to-risk outcomes.
The default direction is set to "Long" for a long-only configuration.
The default exit type is set to "Target" for a fixed reward-to-risk configuration.
Long targets are determined by adding a user-defined multiple of the risk range to the entry price and short targets are determined by subtracting a user-defined multiple of the risk range from the entry price.
Even when using a fixed reward-to-risk configuration, realised reward-to-risk outcomes may vary due to market gaps, particularly when positions are held across session boundaries or market closures. Gaps can cause stop losses or exits to be executed at prices materially different from those implied by the strategy’s static distance calculations. Users who wish to minimise gap-related variability may consider applying the close at end of session filter (see core filters section below), accepting that this introduces its own form of reward-to-risk variability.
The default reward-to-risk is set to 1.
Users can adjust strategy parameters via strategy Settings/Inputs/STRATEGY. Selecting a non-target exit type removes profit targets and renders the reward-to-risk input inactive.
Trailing Stop Loss
A trailing stop loss is defined as an exit type that dynamically moves a stop loss level in a favourable direction when a predefined condition is met. For example, a predefined point move or the formation of a higher trough or lower peak.
Risk Range Trailing Stop Loss
The risk range trailing stop loss is defined as a trailing stop mechanism that activates once price has moved favourably by one full risk range. Upon activation, the stop loss is moved to breakeven and subsequently trails favourable price movement by the risk range into profit.
Users can apply this exit type by selecting "Trail" via strategy Settings/Inputs/STRATEGY.
Trend Trailing Stop Loss
The trend trailing stop loss is defined as a trailing stop mechanism that dynamically moves a stop loss level to newly formed higher troughs (for longs) or lower peaks (for shorts).
Users can apply this exit type by selecting "Trend Trail" via strategy Settings/Inputs/STRATEGY.
Candle Trailing Stop Loss
The candle trailing stop loss is defined as a trailing stop mechanism that dynamically moves a stop loss level to newly formed higher candle lows (for longs) or lower candle highs (for shorts).
Users can apply this exit type by selecting "Candle Trail" via strategy Settings/Inputs/STRATEGY.
Opposing Candle Colour Close
The opposing candle colour close exit type is defined as an exit condition that closes any long positions when a new red candle forms and closes any short positions when a new green candle forms.
Users can apply this exit type by selecting "Opposing Candle" via strategy Settings/Inputs/STRATEGY.
█ CORE FILTERS
Minimum Risk Range Filter
The minimum risk range filter is defined as an entry filter that invalidates trade signals with a risk range below a user-defined threshold.
The default minimum risk range is set to 4 points/pips.
Users can adjust the minimum risk range via strategy Settings/Inputs/RISK RANGE FILTER.
It is recommended that users set the minimum risk range at least 1–2 points/pips above the selected symbol’s spread to invalidate trades that would be completely impractical under realistic trading conditions.
Time Zone
The time zone is defined using either an IANA region identifier (e.g. Europe/London, America/New_York) or a fixed UTC/GMT offset (e.g. UTC+1, GMT-05:30). Fixed offsets do not account for daylight saving time.
The default time zone is set to Europe/London.
Users can change the time zone via strategy Settings/Inputs/TIME ZONE.
For further information on time zone configuration, please refer to:
data.iana.org
en.wikipedia.org
Session Filter
The session filter is defined as an entry filter that invalidates trade signals that fall outside a user-defined intraday trading session, with session start and end times bound to the strategy time zone.
TradingView candle timestamps represent the candle open time, not the candle close time. As a result, session boundaries are evaluated based on when a candle opens, even though entries and exits are processed at candle close.
To avoid trades being entered or held beyond the intended session end, users should configure the session end time at least one full timeframe period earlier than the desired practical session close. For example, on a 5-minute chart with a desired session end at 22:00, the session should typically be configured to end at 21:55. This ensures that no new trades are taken at the final session close and that any session-dependent exit logic is applied before the session ends in practice.
When using custom or non-standard timeframes where the desired session end does not align cleanly with candle boundaries, it is recommended that users set the session end two full timeframe periods earlier than the desired session end. This provides an additional safety buffer, ensuring the strategy avoids taking trades near the session boundary.
By default, the session filter is set to false and the default session is set to "2300-2155".
Users can apply the session filter and adjust session boundaries via strategy Settings/Inputs/SESSION FILTER.
Close At End of Session Filter
The close at end of session filter is defined as an exit filter that closes all open positions when the active trading session ends, provided that the session filter is appropriately configured and applied.
When enabled, the strategy monitors the session filter state and detects the transition from an active session to an inactive session. All open trades are closed on the first candle that falls outside the defined session window. This ensures that no positions are carried beyond the user-defined trading session.
The close at end of session filter operates independently of entry conditions and other exit types. When enabled, it will force the closure of all open positions at session end regardless of the selected exit configuration.
Enabling the close at end of session filter can result in variable reward-to-risk outcomes. Because positions are forcibly closed at session end regardless of stop loss or target placement, exits may occur at prices that differ from those implied by the fixed reward-to-risk configuration. This behaviour is intentional and reflects a design trade-off between enforcing strict session boundaries and allowing trades to reach their predefined directional objectives, regardless of how severely distorted the realised reward-to-risk outcomes could be in the event of price gaps.
By default, the close at end of session filter is set to false.
Users can apply the close at end of session filter via strategy Settings/Inputs/CLOSE AT END OF SESSION FILTER.
Users should also ensure that the session filter is applied and that session boundaries are configured appropriately with respect to candle timestamp behaviour, as described in the session filter section above.
Sample Period Filter
The sample period filter is defined as an entry filter that invalidates trade signals that fall outside a user-defined date-time range, with start and end date-times bound to the strategy time zone.
TradingView candle timestamps represent the candle open time, not the candle close time. As a result, sample period boundaries are evaluated based on when a candle opens, even though entries and exits are processed at candle close.
To avoid trades being entered beyond the intended sample period end, users should configure the sample period end date-time at least one full timeframe period earlier than the desired practical sample period end date-time. For example, on a 5-minute chart with a desired end date-time of 01/01/2026 22:00, the end date-time should typically be configured to 01/01/2026 21:55.
The default sample period start and end date-times are set to 01/01/1900 00:00 and 01/01/3000 00:00, respectively.
Users can adjust the sample period via strategy Settings/Inputs/SAMPLE PERIOD FILTER.
█ GENERIC FILTERS
Generic Filter Behaviour
Unless otherwise stated:
"None" inputs return true.
Filters return true only when their selected condition is satisfied.
Minimum Percentage Change Positive-Flat/Negative Filter
The minimum percentage change filter is an entry filter that measures the relative change of a time-series value over a configurable historical window and applies a directional threshold condition, invalidating trade signals that do not meet the directional threshold criteria.
The filter compares the current value to its value n bars ago and computes the percentage difference. A signal returns true only if this percentage change satisfies both:
The selected directional requirement.
The user-defined minimum percentage change magnitude.
"Positive-Flat" direction logic:
Accepts values that have increased or remained unchanged, provided the percentage change is greater than or equal to the minimum threshold.
"Negative" direction logic:
Accepts values that have decreased, provided the magnitude of the decrease meets or exceeds the minimum threshold.
When the minimum threshold is set to 0%, the filter behaves as a pure directional check:
"Positive-Flat" accepts ≥ 0% changes.
"Negative" accepts < 0% changes only.
Basic and Multi-Part Trend Filters
Basic and multi-part trend filters are defined as entry filters that evaluate changes in time-series values from one period to the next and invalidate trade signals that do not satisfy a user-defined trend condition.
Basic trends operate independently of prior trend state, whereas multi-part trends are defined by the presence or absence of preceding trend sequences. The multi-part trend states are distinguished numerically and the conditions are bound to a user-defined trend count.
"Basic Uptrend" returns true when a time-series value is greater than the preceding value. For example, a basic volume uptrend filter returns true if the most recent candle's volume is greater than the preceding candle's volume.
"Basic Downtrend" returns true when a time-series value is less than the preceding value. For example, a basic volume downtrend filter returns true if the most recent candle's volume is less than the preceding candle's volume.
"Uptrend" returns true while a multi-part uptrend state is valid. The uptrend state begins when a new basic uptrend forms following a basic downtrend and remains valid until a new basic downtrend forms. The user-defined trend count will determine which multi-part trend condition is selected. For example, if the user-defined trend count is set to 3, then only 3-part uptrend conditions will return true.
"Downtrend" returns true while a multi-part downtrend state is valid. The downtrend state begins when a new basic downtrend forms following a basic uptrend and remains valid until a new basic uptrend forms. The user-defined trend count will determine which multi-part trend condition is selected. For example, if the user-defined trend count is set to 3, then only 3-part downtrend conditions will return true.
Close Above-Equal/Below Filter
The close price above-equal/below filter is defined as an entry filter that evaluates the most recent candle close price relative to a given time-series value and invalidates trade signals that do not satisfy a user-defined directional condition.
"Above-Equal" returns true when the most recent candle close price is greater than or equal to any given time-series value.
"Below" returns true when the most recent candle close price is less than any given time-series value.
Basic and Exclusive Rejection Filters
The basic rejection filter is defined as an entry filter that evaluates swing-based wick or body rejections of a given price level and invalidates trade signals that do not satisfy the rejection criteria.
For long trades, "Rejection" returns true when all three of the following conditions are met:
The previous candle open is above a given rejection price.
The trough price is less than or equal to a given rejection price.
The green candle that completes the swing closes above a given rejection price.
For short trades, "Rejection" returns true when all three of the following conditions are met:
The previous candle open is below a given rejection price.
The peak price is greater than or equal to a given rejection price.
The red candle that completes the swing closes below a given rejection price.
The exclusive rejection filter is defined as an entry filter that meets basic rejection filter criteria for only one user-defined price level from a set of given price levels. If the rejection criteria is met for more than one of the given price levels the filter will return false.
Minimum and Maximum Boundary Filters
Minimum and maximum boundary filters are defined as entry filters used to constrain time-series values to predefined minimum and/or maximum thresholds, invalidating trade signals that do not satisfy a user-defined threshold criteria. The filters consist of two independent threshold components, minimum (above-equal) and maximum (below-equal), which may be applied individually or together.
When both components are applied simultaneously the filters act as a value range constraint, invalidating trade signals that fall outside of the specified bounds.
"Above-Equal" returns true when the evaluated value is greater than or equal to the user-defined minimum boundary.
"Below-Equal" returns true when the evaluated value is less than or equal to the user-defined maximum boundary.
█ FEATURE SET B SPECIFIC FILTERS
All feature set specific indicators use the same calculations as the built-in TradingView indicators unless otherwise stated in the relevant filter sub-section. While users do not need to apply the indicators for the strategy to function, they can of course apply the relevant indicators as visual aids if they so desire.
For further information on how to apply built-in TradingView indicators, please refer to:
www.tradingview.com
Balance of Power (BOP) Filters
Minimum and maximum boundary filter (see generic filters section above) defaults are as follows:
Apply above-equal filter is set to false.
Above-equal threshold is set to -1.
Apply below-equal filter is set to false.
Below-equal threshold is set to 1.
The BOP minimum percent change positive-flat/negative filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The BOP trend filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
Due to the way BOP is calculated and the structure of the core entry conditions, basic uptrend and basic downtrend modes are intentionally omitted for the BOP trend filter, as they would be trivially satisfied for long and short entries respectively. Consequently, downtrend evaluation is redundant for long trades and uptrend evaluation is redundant for short trades.
Users can apply the BOP filters and adjust filter parameters via strategy Settings/Inputs/BALANCE OF POWER (BOP) FILTERS.
Bollinger Bands (BB) Filters
The default BB inputs are as follows:
Source is set to "Close".
Length is set to 20.
Standard deviation is set to 2.
Users can adjust the BB inputs via strategy Settings/Inputs/BOLLINGER BANDS (BB).
The BB bandwidth increasing/decreasing filter is defined as an entry filter that evaluates whether the distance between the upper and lower BB is expanding or contracting over a configurable lookback period.
The default BB bandwidth increasing/decreasing filter mode is set to "None".
Users can apply up to three independent close above-equal/below filters (see generic filters section above), one for each BB (upper, middle, lower).
The default mode for all three close above-equal/below BB filters is set to "None".
The BB rejection filter is defined as an exclusive rejection filter (see generic filters section above) that will only return true if the user-defined BB is rejected exclusive of the other two BBs.
The default BB rejection filter mode is set to "None".
Users can apply the BB filters and adjust filter parameters via strategy Settings/Inputs/BB FILTERS.
█ ALERTS
Users can set alerts for any given strategy configuration via the alerts dialogue box.
Users must first ensure that the correct condition (the strategy title) is selected from the first drop-down list in the alert dialogue box's condition field.
Default alert messages have been configured for both entries and exits so that users can more effectively distinguish between long and short entries and exits while using long-short configurations.
To get alerts for both entries and exits the user should change the value in the condition field's second drop-down list from "Order fills only and alert() function calls" to "Order fills only". When using "Order fills only" with long-short configurations, it is recommended that users define their alert via the alert name field and use only the default {{strategy.order.alert_message}} call in the alert message field.
Alert conditions generated by "Order fills only" are evaluated after entry conditions have been satisfied and operational constraints (risk, position size and margin requirements) have been applied. As such, trade signals that would result in position sizes exceeding the simulated account's margin constraints will not generate alerts.
To get alerts for entries only the user should change the value in the condition field's second drop-down list from "Order fills only and alert() function calls" to "alert() function calls only".
The default alert messages generated by "Order fills only" are as follows:
"long entry".
"long exit".
"short entry".
"short exit".
The default alert messages generated by "alert() function calls only" are as follows:
"long entry".
"short entry".
Alert conditions generated by "alert() function calls only" are operational-constraint-agnostic and will generate alerts whenever entry conditions are satisfied, regardless of the simulated account's margin constraints.
For further information on setting and managing alerts, please refer to:
www.tradingview.com
www.tradingview.com
www.tradingview.com
█ LIMITATIONS AND CONSIDERATIONS
Backtesting
Backtest results should always be interpreted cautiously. Strategy performance can vary significantly across time periods and sample sets. While strong historical performance does not guarantee future results, poor historical performance reliably indicates a weak strategy when sample sizes are statistically meaningful.
Statistical Significance and Path-Dependent Outcomes (Overfitting)
In statistical practice, sample sizes of 100 observations are sometimes cited as a rough lower bound for certain forms of basic significance testing. In the context of trading strategy evaluation, such sample sizes are rarely sufficient to produce results that are meaningfully reliable or replicable. Based on practical experience, sample sizes closer to 1,000 observations or more are generally required before performance characteristics begin to stabilise. As a general rule, larger sample sizes increase the reliability and replicability of observed results.
Path dependence refers to situations in which outcomes are determined not only by initial conditions, but by the specific and unique sequence of price movements over a given time period.
Even with large sample sizes, favourable net profit outcomes should be interpreted with caution when they are primarily driven by either variable reward-to-risk configurations or fixed reward-to-risk configurations that employ unrealistically high reward multiples. In both cases, performance is often strongly influenced by path-dependent effects, making such outcomes less reliable and less replicable.
Fixed reward-to-risk configurations are generally less susceptible to path dependence when the reward multiple is kept within reasonable bounds. However, empirical studies and practitioner research suggest that reward multiples above approximately 3:1 increasingly exhibit the same path-dependent characteristics observed in variable reward-to-risk strategies.
Bar Magnifier
Due to the limitations of OHLC data, intra-bar price movement cannot be precisely determined.
When both stop loss and target levels are reached within the same candle, assumptions are made by the strategy tester.
Pine Script's bar magnifier partially mitigates this limitation by evaluating lower-timeframe data. However, this feature is available only to TradingView Premium users and remains inherently limited.
For further information on the bar magnifier functionality, please refer to:
www.tradingview.com
www.tradingview.com
TradingView Premium users can enable bar magnifier via strategy Settings/Properties/FILL ORDERS.
Processing Orders at Candle Close
Backtests cannot accurately account for slippage between signal generation and trade execution.
A practical mitigation is to use fixed-distance stop losses and targets rather than absolute price levels, a feature supported by many brokers and APIs.
Empirical Probabilities
Empirical probabilities are derived directly from observed outcomes rather than from theoretical models or assumed distributions. In the context of trading, they are calculated by measuring the relative frequency of events (such as wins and losses) across a large sample of historical trades.
Unlike conditional or model-based probabilities, empirical probabilities make no assumptions. Their validity relies primarily on sample size and the consistency of the rules used to generate observations, making them particularly relevant for trading systems evaluated under the law of large numbers.
Empirical probabilities are most useful for comparative analysis, such as assessing how different configurations, filters or exit mechanisms alter the statistical behaviour of a strategy under identical conditions. They are not intended to represent true predictive probabilities or to imply stable future performance.
To study empirical probabilities for comparative purposes, it is recommended that users set commission and both long and short margin values to 0% in order to maximise sample size. However, users should not interpret any resulting profits as realistic. Setting commission and margin (in particular) to 0% produces highly distorted outcomes that are not representative of realistic live trading conditions.
█ DISCLAIMER
This Pine Script strategy is provided for educational purposes only and does not constitute financial advice in any form.
Chiến lược Pine Script®
OTE PRO FuturesOTE PRO – Futures HighFreq PRO (SMC)
OTE PRO is a Smart Money Concepts (SMC)–based futures strategy designed to capture institutional displacement moves followed by precise Optimal Trade Entry (OTE) retracements.
The strategy focuses on identifying intent, liquidity displacement, and premium/discount re-entries rather than indicators or lagging signals.
Market StrucLogic
ture
A Market Structure Shift (MSS) is confirmed when price breaks internal structure
- The MSS candle must show strong body expansion relative to ATR, filtering weak or engineered breaks
. MSS defines the directional bias and activates the setup window
Displacement & Liquidity Expansion
- Following MSS, the strategy waits for impulsive displacement
- Displacement is validated by:
- Large candle range relative to ATR
- Optional volume expansion (institutional participation filter)
- This displacement defines the dealing range used for execution
Optimal Trade Entry (OTE)
- After displacement, the impulse high/low is locked
- Entry is placed in the 0.618 Fibonacci retracement zone
- A configurable tolerance accounts for fast, high-frequency market conditions
- If price fails to retrace within the allowed time window, the setup is invalidated
Risk & Trade Management
- Stop Loss: Protected structure (origin of the displacement)
- Partial Take Profit: 50% at the 0.382 Fibonacci level
- Final Take Profit: Liquidity target at the displacement high/low
- All risk parameters are fixed at entry to prevent dynamic repainting
Additional Context
- 200 EMA plotted for higher-timeframe directional awareness
- ATR normalization ensures consistency across instruments
- MSS markers visualize structural shifts clearly
Usage Notes
- Built for futures markets and lower timeframes
- Performs best during high-liquidity sessions
- Not designed for ranging or low-volatility environments
Chiến lược Pine Script®
OTE PROOTE PRO – Futures HighFreq PRO (SMC)
OTE PRO is a Smart Money Concepts (SMC)–based futures strategy designed to capture institutional displacement moves followed by precise Optimal Trade Entry (OTE) retracements.
- The strategy focuses on identifying intent, liquidity displacement, and premium/discount re-entries rather than indicators or lagging signals.
Market Structure Logic
- A Market Structure Shift (MSS) is confirmed when price breaks internal structure
- The MSS candle must show strong body expansion relative to ATR, filtering weak or engineered breaks
- MSS defines the directional bias and activates the setup window
Displacement & Liquidity Expansion
- Following MSS, the strategy waits for impulsive displacement
- Displacement is validated by:
- Large candle range relative to ATR
- Optional volume expansion (institutional participation filter)
- This displacement defines the dealing range used for execution
Optimal Trade Entry (OTE)
- After displacement, the impulse high/low is locked
- Entry is placed in the 0.618 Fibonacci retracement zone
- A configurable tolerance accounts for fast, high-frequency market conditions
- If price fails to retrace within the allowed time window, the setup is invalidated
Risk & Trade Management
- Stop Loss: Protected structure (origin of the displacement)
- Partial Take Profit: 50% at the 0.382 Fibonacci level
- Final Take Profit: Liquidity target at the displacement high/low
- All risk parameters are fixed at entry to prevent dynamic repainting
Additional Context
- 200 EMA plotted for higher-timeframe directional awareness
- ATR normalization ensures consistency across instruments
- MSS markers visualize structural shifts clearly
Usage Notes
- Built for futures markets and lower timeframes
- Performs best during high-liquidity sessions
- Not designed for ranging or low-volatility environments
Chiến lược Pine Script®
ORB System Builder v1.5TradeX ORB System Builder v1.5 — Configurable Opening Range Breakout Framework
TradeX ORB System Builder is a configurable Opening Range Breakout (ORB) strategy framework designed to allow users to construct, test, and evaluate their own ORB-based rule sets.
This is not a single preset trading strategy.
Instead, it functions as a system-building tool that allows users to define how entries, exits, and risk logic are applied around an opening range using a structured and repeatable rule engine.
All logic is developed in-house and operates under a unified internal framework to ensure consistent behavior across instruments and timeframes.
Core Concept & Originality
The script is built around a modular ORB engine that separates:
• range construction
• breakout detection
• execution method
• risk logic
• trade limits
Rather than using a fixed ORB template, the framework allows users to study how different breakout definitions and risk models behave under the same structured logic.
This differs from standard ORB scripts by allowing users to modify execution behavior and risk management rules without altering the underlying range logic, enabling controlled experimentation inside one framework.
Entry Logic
Users can select between two internally coded breakout execution methods:
Entry on Cross of the Range
A trade is triggered when price crosses the defined opening range boundary intrabar.
Entry on Close Outside the Range
A trade is triggered only when a candle closes fully outside the defined range.
Both methods follow the same internal range calculation rules, allowing users to compare breakout behavior while preserving a consistent structure.
Range & Session Configuration
The framework provides precise control over how the opening range and trading session are defined:
• Range start time (hour, minute, second)
• Range end time (hour, minute, second)
• Trade start time (hour and minute)
• Trade end time (hour and minute)
• End-of-day cutoff time
• Time zone selection
An optional setting allows users to include or exclude U.S. market holidays from testing to prevent distorted datasets.
These controls allow users to define exactly which market session is being tested and ensure reproducible backtesting conditions.
Risk & Trade Management Logic
Trade behavior is governed by user-defined risk parameters, including:
• Risk allocation per trade
• Stop loss placement based on candle structure or as a percentage of the opening range
• Take profit targets defined using risk-to-reward multiples
• Optional break-even adjustment based on achieved risk-to-reward
• Maximum long trades per day
• Maximum short trades per day
• Maximum winning trades per day
• Maximum losing trades per day
This structure allows users to study how different risk models interact with the same breakout logic while enforcing controlled exposure and trade frequency.
Visualization & Diagnostic Tools
The script includes optional visual and diagnostic components to assist configuration and testing:
• Debug panel displaying active input settings
• Adjustable panel position and text size
• Customizable opening range line color, width, and style
Position fills can be enabled or disabled, with adjustable:
• Profit fill color
• Loss fill color
• Transparency
• Label size
These tools are intended to help users visually verify system behavior and ensure inputs are being applied as intended.
Strategy Properties & Backtesting
This script is published as a strategy for structured backtesting and evaluation.
Users should:
• Use realistic account sizes
• Apply realistic commission and slippage
• Select datasets that generate sufficient trade samples (ideally more than 100 trades)
• Avoid excessive risk per trade
Default settings are provided for demonstration and framework testing only.
Users are responsible for configuring position sizing, commissions, slippage, and session parameters appropriate to their market and timeframe.
Development Process
The ORB System Builder was initially prototyped using Python-based simulations to evaluate variations in:
• breakout execution logic
• timing rules
• session structure
• risk management behavior
The most consistent and stable rule sets were then implemented in Pine Script as a configurable framework rather than a single fixed strategy.
Intended Use
This script is designed for:
• strategy research
• ORB rule development
• controlled backtesting
• comparative model testing
It is not intended as a pre-optimized trading system.
Disclaimer
TradeX ORB System Builder is a proprietary TradeX Labs system-building framework.
It is provided for educational and research purposes only.
It does not guarantee profitability and is not financial advice.
Default configurations are illustrative only.
Users must adjust the system based on their own instruments, sessions, and risk tolerance.
This script enables users to define their own ORB-based logic and does not represent a pre-optimized or preset trading strategy.
Chiến lược Pine Script®
Box Theory PROBox Theory PRO is a rule-based, multi-system trading framework designed to analyze intraday market structure using volatility expansion, session context, and higher-timeframe alignment.
This script extends traditional Box Theory beyond static visual levels by integrating multiple trade systems, confirmation logic, and performance statistics into a single, structured decision-support tool.
Box Theory PRO emphasizes structured trade selection, risk-defined execution, and repeatable market behavior across varying market conditions, rather than focusing on any single performance metric.
Core Systems
Box-based structural analysis using prior session high and low levels
ATR-based volatility expansion and contraction detection
Manipulation, continuation, and structure-based trade systems
Multi-timeframe alignment across 5-minute, 1-hour, and 4-hour levels
Optional Supertrend and EMA filters for directional bias
Configurable take-profit, stop-loss, and time-based exits
Built-in performance statistics for informational analysis by individual system
Important: While calculations may occur during bar formation for display and internal tracking, all trade signals are confirmed and finalized on candle close only. No intrabar or tick-based execution logic is used.
Intended Use
Box Theory PRO is designed for:
Index products, futures, and other liquid intraday markets
Traders seeking structured, rules-driven decision logic
Backtesting, market study, and discretionary execution support
This script does not connect to any brokerage and does not place trades automatically.
Recommended Starting Preset
For new users:
Chart timeframe
15-minute
Enabled systems
Manipulation: ON
Box: ON
1H / 4H: Optional or OFF for beginners
Filters
EMA filter: ON
Supertrend: ON
ATR-based exits: ON
Session filters: ON
This preset prioritizes structural clarity and learning over trade frequency. It is not optimized for any specific market.
Timeframe Behavior Notes
Higher timeframes (15-minute charts and above) typically exhibit cleaner volatility structure and reduced noise
Lower timeframes may generate more trade opportunities but can experience reduced consistency during choppy or low-liquidity periods
Users are encouraged to evaluate multiple timeframes and select configurations aligned with their trading style and risk tolerance
Performance Notes
Performance will vary depending on market, timeframe, and enabled systems
Box Theory PRO is designed to support structured decision-making rather than maximize win rate alone
Focus is placed on:
Risk-defined execution
Structured trade selection
Consistency across changing market conditions
Users should evaluate multiple metrics—including drawdown, trade frequency, and risk-to-reward ratios—through both backtesting and forward testing.
Historical behavior does not guarantee future results.
Access
Box Theory PRO is offered as a TradingView invite-only script.
Subscription management and billing are handled externally.
Ongoing Updates
The script may receive periodic updates, refinements, and feature improvements to reflect evolving market conditions and user feedback.
Disclaimer
For educational and informational purposes only.
Not financial or investment advice. Trading involves risk; past performance is not indicative of future results.
Use at your own discretion.
Step-by-Step Guide to Using Box Theory PRO
Step 1: Understand the Framework
On your chart (recommended 1-minute or 5-minute for precision, with sufficient historical data):
Daily Box
Yellow box based on previous day high (PDH) and low (PDL)
PDH displayed as a red line, PDL as a green line
Box extends a fixed number of bars to the right
Midline displayed as a dashed line
Opening Range (OR)
Locked to the first 15 minutes of the session (09:30–09:45 EST by default)
OR High (blue), OR Low (purple)
“Strong Opening” flagged when OR exceeds a configurable percentage of daily ATR
Swings and Pivots
Pivot levels derived from price structure
Hourly swing highs/lows from 1-hour data
Higher-timeframe swing levels from 4-hour data
Trend Filters and Overlays
EMA overlays (20, 50, 200) for trend context
Bollinger Bands for volatility expansion and contraction
VWAP with daily reset
Supertrend as an optional directional filter
Manipulation Detection
Identifies large 15-minute candles relative to daily ATR
Labels “Bull Manip” or “Bear Manip” when thresholds are exceeded
Entry and Exit Signals
Strategy-labeled entries (e.g., MANIP LONG, BOX SHORT, OR LONG)
Exit labels displayed when TP, SL, or time-based exits occur
Independent performance statistics provided for informational purposes
Sessions
Optional overlays for London, New York, Tokyo, and Sydney
Session-based trade filtering available
Tables
ATR table
Performance table
Information table
Trades are simulated within TradingView’s Strategy Tester only. No pyramiding is used. Position sizing is fixed unless modified. Ensure chart timeframe, session settings, display toggles, and historical data are properly loaded.
Step 2: Customize Settings
Core visual options (box display, extensions, pivots)
Strategy toggles (Manipulation, Box, 1H, 4H, OR)
Filters (EMA, Supertrend, session filters)
Per-strategy exit logic (fixed or ATR-based TP/SL, maximum hold time)
Futures mode for tick-based instruments
Alerts for entry and exit signals
Appearance options for labels, tables, and colors
Strategy Tester properties (capital, commission, slippage)
Step 3: Interpret and Use
Daily Box: evaluate reactions at prior session levels
Manipulation strategies: observe volatility expansion followed by confirmation
OR strategies: focus on early-session structure
Entries occur only when confirmation and filter conditions are met
Exits occur via TP, SL, or time-based logic
Emphasis is placed on consistency, drawdown control, and structural alignment rather than any single performance statistic
Step 4: Alerts
Alerts are added through TradingView’s strategy alert conditions
Alerts fire on confirmed bar close only
Alerts provide notification only and do not execute trades
Step 5: Troubleshooting
No signals: verify enabled systems, session filters, and loaded historical data
Cluttered chart: disable unused overlays or tables
Futures instruments: confirm tick value and futures mode settings
Intraday focus: behavior may vary outside regular session hours
Chiến lược Pine Script®
Auto Decision Box PRO Auto Decision Box PRO
Auto Decision Box PRO is a rule-based market structure framework that identifies balance, expansion, breakout continuations, and failed breakout reversals using adaptive volatility and higher-timeframe structure logic.
The indicator automatically builds decision zones (“boxes”) after impulse moves and consolidation, then analyzes how price reacts around these zones to generate structured breakout and reversal signals.
By defining clear rules for balance, expansion, confirmation, and failure, this framework reduces subjectivity and allows traders to study repeatable market behavior.
Core Logic
Automatically builds structure boxes after impulse moves and periods of balance
Adaptive logic adjusts box size based on current volatility
Supports both breakout continuation and failed breakout reversal entries
Higher-timeframe box construction with lower-timeframe execution
Optional VWAP + EMA trend alignment and Supertrend filtering
Detects fake breakouts with delayed failure confirmation
Optional volume filter for breakout strength
Configurable ATR-based or fixed-value risk management
Optional RTH session filtering
All entries are confirmed by candle close; no discretionary drawing required
Strategy Behavior
Breakout entries occur only after confirmed structure breaks
Reversal entries trigger only after defined breakout failure behavior
Fake breakouts are filtered and can trigger early exits
Logic adapts dynamically to changing volatility conditions
Designed for structured decision-making, not prediction
This script does not place trades automatically; it is intended for analysis, backtesting, and discretionary execution support
Intended Use
Futures, indices, and liquid intraday markets
Traders seeking structure-based decision zones
Study breakout vs. rejection behavior
Backtesting and rules-driven execution frameworks
Access
Auto Decision Box is offered as a TradingView invite-only script.
Subscription management and billing are handled externally.
Ongoing Development
This script is actively maintained and updated with:
Continued logic refinement
Structural improvements
Additional filters and confirmations
Quality-of-life updates based on user feedback
Disclaimer
For educational and informational purposes only.
Not financial advice. Trading involves risk; past performance is not indicative of future results.
Use at your own discretion.
Step-by-Step Guide to Using Auto Decision Box PRO
Step 1: Understand What the Strategy Shows
Decision Box: Orange high/low lines with translucent fill, based on 15m “balance bars” after impulses. Box size uses ATR(20) and adapts to volatility. Manual override is available.
Supertrend (optional): Red = bearish, lime = bullish. Acts as entry filter.
Signals & Labels:
Breakout entries: BRC LONG / BRC SHORT
Reversal entries: REV LONG / REV SHORT
Rejection labels: LBR / SBR (optional)
Bar colors indicate failed breakouts (optional)
Static daily label: “Auto Decision Box” reminder
Trades: Simulated only (pyramiding=1, fixed quantity=1). Exits based on TP/SL.
Stats Table: Shows trades, wins/losses, and percentages for educational purposes.
Filters: Session limits, trend, Supertrend, volume, fake break detection.
Boxes form automatically after impulse → balance periods.
Step 2: Customize Settings
Box setup: Timeframe, ATR, impulse multiplier
Balance bars: Adaptive/manual override
Session filter: Enable/disable, set minutes after open
Modes: Breakouts & reversals
Risk management: ATR-based TP/SL or fixed values
Filters: Trend, Supertrend, volume, fake break
Appearance: Show/hide signals, labels
Strategy tab: Adjust quantity, capital, commission for backtesting
Step 3: Interpret and Use
Breakouts: Confirmed cross above box high → long; below low → short
Reversals: Fade fake breakouts (brief break above/below then reject)
Entries only during filtered sessions
Exits occur on TP/SL or failure detection
Focus on studying structure and behavior; performance varies by market and timeframe
Step 4: Alerts
Alerts available for entries and rejections
Add alerts via right-click → Add Alert → Select strategy → Frequency: Once per bar
Notifications via app/email
Step 5: Troubleshooting
No boxes/signals? Verify 15m data, session, and filters
Missing labels/colors? Enable in settings
Backtest skewed? Include commission/slippage
Limitations: Intraday/RTH focus; pyramiding=1
Chiến lược Pine Script®






















