Penunjuk Bill Williams
liquidity reversalThis script detects liquidity sweeps and confirms reversals based on price action. It looks for:
- A sweep of a recent high or low
- A reversal candle closing back inside range
- (Optional) Confirmation via market structure break (MSB)
When confirmed, it plots:
- BUY signals after low sweep + bullish break
- SELL signals after high sweep + bearish break
Works on any timeframe. Designed for MNQ scalping during NY open.
DCA Strategy on Steroids for CryptoThis strategy getting only in Long position for Crypto
Using Fast and Slow moving Averages and Stochastic RSI to get in Long position
Fast and Slow moving Averages - cross-under - I Prefer - or opposite for Bull Market
Stochastic RSI cross-over - 5 and Trend Determined by the Fast moving Average
There is no Stop loss is not for one with small tolerance to getting under
Fast and Slow moving Averages and Stochastic RSI Parameters can be adjust
The bot Use Safe Trades and Price Deviation Determined from the User
Max Safe Trades = 10
Take profit Parameters can be adjust in %
Pepe-USDC is just a example What the bot Can do
Pro Market Toolkit (TH) v2.4 — S/R + Zones + ATR Bands + Alertsรายละเอียด (ภาษาไทย):
อินดิเคเตอร์ชุดเครื่องมือครบวงจรสำหรับนักเทรด
คำนวณ แนวรับ–แนวต้าน (Support / Resistance) อัตโนมัติจากสวิง (Pivot High/Low)
สร้าง Supply/Demand Zones จาก ATR เพื่อหาพื้นที่กลับตัวสำคัญ
วาดเส้น Moving Average และ ATR Bands เพื่อประเมินแนวโน้มและความผันผวน
แสดงสัญญาณ Breakout และ Bounce/Reject อย่างชัดเจนบนกราฟ
รองรับ Alerts สำหรับ 4 เงื่อนไขสำคัญ: Breakout ขึ้น/ลง, Demand Bounce, Supply Reject
มีตารางแสดง Trend และค่า ATR ปัจจุบัน
เหมาะสำหรับผู้ที่ต้องการดูแนวโน้ม, หาจุดเข้า/ออก และรับการแจ้งเตือนอัตโนมัติ โดยไม่ต้องเฝ้ากราฟตลอดเวลา
Description (English):
A comprehensive trading toolkit indicator for professional traders.
Automatically detects Support/Resistance levels using swing pivots
Generates Supply/Demand Zones based on ATR to highlight potential reversal areas
Plots Moving Average and ATR Bands for trend and volatility analysis
Displays clear signal markers for Breakouts and Zone Bounces/Rejects
Provides Alerts for 4 key conditions: Breakout Up/Down, Demand Bounce, Supply Reject
Includes an on-chart table showing the current Trend and ATR value
Ideal for traders who want automatic key levels, zones, and signal alerts without the need to monitor the chart constantly.
DRKSCALPER Strategycoded by Russian coders
this indicators is based coded by buy and sell via price action and fundamental analysis
Smart Money Breakout Signals [GILDEX]Introducing the Smart Money Breakout Signals, a cutting-edge trading indicator designed to identify key structural shifts and breakout opportunities in the market. This tool leverages a blend of smart money concepts like Break of Structure (BOS) and Change of Character (CHoCH) to provide traders with actionable insights into market direction and potential entry or exit points.
Key Features:
✨ Market Structure Analysis: Automatically detects and labels BOS and CHoCH for trend confirmation and reversals.
🎨 Customizable Visualization: Tailor bullish and bearish colors for breakout lines and signals to suit your preferences.
📊 Dynamic Take-Profit Targets: Displays three tiered take-profit levels based on breakout volatility.
🔔 Real-Time Alerts: Stay ahead of the game with notifications for bullish and bearish breakouts.
📋 Performance Dashboard: Monitor signal statistics, including win rates and total signals, directly on your chart.
How to Use:
Add the Indicator: Add the script to your favourites ⭐ and customize settings like market structure horizon and confirmation type.
Indicador Millo SMA20-SMA200-AO-RSI M1This indicator is designed for scalping in 1-minute timeframes on crypto pairs, combining trend direction, momentum, and oscillator confirmation.
Logic:
Trend Filter:
Only BUY signals when price is above the SMA200.
Only SELL signals when price is below the SMA200.
Entry Trigger:
BUY: Price crosses above the SMA20.
SELL: Price crosses below the SMA20.
Confirmation Window:
After the price cross, the Awesome Oscillator (AO) must cross the zero line in the same direction within a maximum of N bars (configurable, default = 4).
RSI must be > 50 for BUY and < 50 for SELL at the moment AO confirms.
Cooldown:
A cooldown period (configurable, default = 10 bars) prevents multiple signals of the same type in a short time, reducing noise in sideways markets.
Features:
Works on any crypto pair and can be used in other markets.
Adjustable confirmation window, RSI threshold, and cooldown.
Alerts ready for BUY and SELL conditions.
Can be converted into a strategy for backtesting with TP/SL.
Suggested Use:
Pair: BTC/USDT M1 or similar high-liquidity asset.
Combine with manual support/resistance or higher timeframe trend analysis.
Recommended to confirm entries visually and with additional confluence before trading live.
Calculateur Position Size Multi-ActifsThe Multi-Asset Position Size Calculator v6 is a fully customizable Pine Script indicator designed to help you determine the optimal position size based on your risk tolerance across any market: Forex, stocks, crypto, futures indices, or commodities. Features include:
Asset Type Selector: Choose between Forex, Stocks, Crypto, Futures Indices, or Commodities
Account Capital & Risk: Set your total account size and risk percentage per trade
Entry Price & Stop-Loss: Configure your entry and stop-loss levels directly
Automatic or Custom Pip/Point Value: Automatically calculates pip/point value by asset class or enter your own
Contract Size Adjustment: Define contract sizes (e.g., 100,000 units for Forex, 1 for stocks/crypto)
Margin & Leverage Display: View your used leverage and position value in real time
Risk Alerts: Warnings for invalid inputs, high leverage (>10×), and asset-specific risk settings (e.g., crypto leverage)
Integrated Table Interface: On-chart table with adjustable position and text size
Optional Price Level Drawing: Display entry and stop-loss lines on the chart
Trade any market confidently with precise, asset-tailored position sizing and risk management.
Nova Futures PRO (SAFE v6) — HTF + Choppiness + CooldownNova Futures PRO (SAFE v6) — HTF + Choppiness + Cooldown
Fractal Suite: MTF Fractals + BOS/CHOCH + OB + FVG + Targets Kese Way
Fractals (Multi-Timeframe): Automatically detects both current-timeframe and higher-timeframe Bill Williams fractals, with customizable left/right bar settings.
Break of Structure (BOS) & CHoCH: Marks structural breaks and changes of character in real time.
Liquidity Sweeps: Identifies sweep patterns where price takes out a previous swing high/low but closes back within range.
Order Blocks (OB): Highlights the last opposite candle before a BOS, with customizable extension bars.
Fair Value Gaps (FVG): Finds 3-bar inefficiencies with a minimum size filter.
Confluence Zones: Optionally require OB–FVG overlap for high-probability setups.
Entry, Stop, and Targets: Automatically calculates entry price, stop loss, and up to three take-profit targets based on risk-reward ratios.
Visual Dashboard: Mini on-chart table summarizing structure, last swing points, and settings.
Alerts: Set alerts for new fractals, BOS events, and confluence-based trade setups.
Multi Timeframe 7 Bollinger Bands by CSPMulti Timeframe 7 Bollinger Bands by CSP IT SHOW 1MT,5MT,10MT,1HR,D, W,M BOLLINGER BAND IN ASINGLE CHART.
BuySell-byALHELWANI🔱 BuySell-byALHELWANI | مؤشر التغيرات الاتجاهية الذكية
BuySell-byALHELWANI هو مؤشر احترافي متقدّم يرصد نقاط الانعكاس الحقيقية في حركة السوق، باستخدام خوارزمية تعتمد على تحليل القمم والقيعان الهيكلية للسعر (Structure-Based Detection) وليس على مؤشرات تقليدية.
المؤشر مبني على مكتبة signalLib_yashgode9 القوية، مع تخصيص كامل لأسلوب العرض والتنبيهات.
⚙️ ما يقدمه المؤشر:
🔹 إشارات واضحة للشراء والبيع تعتمد على كسر هيكل السوق.
🔹 تخصيص مرن للعمق والانحراف وخطوات التراجع (Backstep) لتحديد الدقة المطلوبة.
🔹 علامات ذكية (Labels) تظهر مباشرة على الشارت عند كل نقطة قرار.
🔹 تنبيهات تلقائية فورية عند كل تغير في الاتجاه (Buy / Sell).
🧠 الآلية المستخدمة:
DEPTH_ENGINE: يتحكم في مدى عمق النظر لحركة السعر.
DEVIATION_ENGINE: يحدد المسافة المطلوبة لتأكيد نقطة الانعكاس.
BACKSTEP_ENGINE: يضمن أن كل إشارة تستند إلى تغير هيكلي حقيقي في الاتجاه.
📌 المميزات:
✅ لا يعيد الرسم (No Repaint)
✅ يعمل على كل الأطر الزمنية وكل الأسواق (فوركس، مؤشرات، كريبتو، أسهم)
✅ تصميم بصري مرن (ألوان، حجم، شفافية)
✅ يدعم الاستخدام في السكالبينغ والسوينغ
ملاحظة:
المؤشر لا يعطي إشارات عشوائية، بل يستند إلى منطق السعر الحقيقي عبر تتبع التغيرات الحركية للسوق.
يُفضّل استخدامه مع خطة تداول واضحة وإدارة رأس مال صارمة.
🔱 BuySell-byALHELWANI | Smart Reversal Detection Indicator
BuySell-byALHELWANI is a high-precision, structure-based reversal indicator designed to identify true directional shifts in the market. Unlike traditional indicators, it doesn't rely on lagging oscillators but uses real-time swing analysis to detect institutional-level pivot points.
Powered by the robust signalLib_yashgode9, this tool is optimized for traders who seek clarity, timing, and strategic control.
⚙️ Core Engine Features:
🔹 Accurate Buy/Sell signals generated from structural highs and lows.
🔹 Adjustable sensitivity using:
DEPTH_ENGINE: Defines how deep the algorithm looks into past swings.
DEVIATION_ENGINE: Sets the deviation required to confirm a structural change.
BACKSTEP_ENGINE: Controls how many bars are validated before confirming a pivot.
🧠 What It Does:
🚩 Detects market structure shifts and confirms them visually.
🏷️ Plots clear Buy-point / Sell-point labels directly on the chart.
🔔 Sends real-time alerts when a directional change is confirmed.
🎯 No repainting – what you see is reliable and final.
✅ Key Benefits:
Works on all timeframes and all asset classes (FX, crypto, indices, stocks).
Fully customizable: colors, label size, transparency.
Ideal for scalping, swing trading, and strategy automation.
High visual clarity with minimal noise.
🔐 Note:
This script is designed for serious traders.
It highlights real market intent, especially when used with trendlines, zones, and volume analysis.
Pair it with disciplined risk management for best results.
Kalman Supertrend (High vs Low) Bands by Skyito V2Inspired by BackQuant's Kalman Hull Supertrend, this upgraded version replaces the typical Kalman-close method with Kalman-filtered High and Low sources. This approach provides clearer trend visualization and helps confirm potential breakouts or reversals using clean, directional candle signals.
The core logic revolves around BB (Band Buy) and SS (Band Sell) signals:
BB appears only when a candle fully breaks above both Kalman High and Low bands.
SS appears when a candle fully breaks below both bands.
These clean triggers help avoid false signals and are excellent for capturing high-probability trend shifts.
✅ The Supertrend line is also included and can be toggled on or off — useful for those who prefer early trend detection or confirmation.
🆕 Why the SMA Band was Included
To complement the Kalman band system, a Moving Average Band (default: SMA 200) is added:
It helps detect the long-term trend direction.
Candles are colored green when above the SMA band and red when below.
This visual cue strengthens trend confidence and adds an extra layer for filtering trades.
The MA band and coloring can be turned on or off based on preference.
This tool is built for traders who want a clean trend-following and breakout confirmation system. It can be used as a standalone strategy or paired with price action, volume, or support/resistance tools.
Kalman Supertrend (High vs Low) Bands Inspired by BackQuant, this script modifies the original Kalman Hull Supertrend by replacing the close price with High and Low sources. This creates clearer trend definition and better trend tracking.
This is one of the best trend indicators that can be used for trend trading or to capture reversals with high clarity.
Key Features:
Kalman High/Low Bands — Smooths market noise while separating bullish and bearish zones.
BB & SS Alerts — Triggered only when the entire candle closes outside both bands, helping filter out false breakouts.
Supertrend (optional) — Can be toggled on/off to monitor potential short-term or early trend shifts.
Customizable Display — Show/hide bands, fills, and live candle coloring for chart clarity.
Reversal Insight:
For 4H and Daily charts, reversal signals appear to be quite accurate when the price retests the trend bands before continuing the move.
How to Use:
BB appears when a candle fully closes above both High/Low Kalman bands — possible bullish breakout.
SS appears when a candle fully closes below both bands — possible bearish breakdown.
Supertrend toggle can confirm shorter-term moves or early reversals.
Credit to the original script BackQuant
Martin Strategy - No Loss Exit v3Martin Strategy - No Loss Exit v3Martin Strategy - No Loss Exit v3Martin Strategy - No Loss Exit v3
Live Market - Performance MonitorLive Market - Performance Monitor – Study Material & Usage Guide
Overview:
The Live Market - Performance Monitor is a multi-layered TradingView indicator that assists traders in identifying high-probability setups by combining key technical elements: order block detection, dynamic trendline analysis, volume and volatility filtering, signal validation, and ATR-based target projection. This guide provides the essential logic, formulas, and practical steps to help users apply the system effectively.
________________________________________
Key Functional Features and Formulas
________________________________________
1. Order Block Detection
The indicator identifies price zones where strong institutional buying or selling has likely occurred, based on candle sequences.
• User Input: Number of consecutive candles to define relevance (e.g., 3–7 bars)
• Validation Formula:
• Price Move % = |Close(n) - Close(1)| / Close(n) × 100
• Bullish Order Block: A bearish candle followed by consecutive bullish candles
• Bearish Order Block: A bullish candle followed by consecutive bearish candles
Only valid zones that meet a minimum price move threshold are retained and plotted.
________________________________________
2. Trendline Logic
Trendlines are dynamically plotted using price pivots.
• Pivot Calculation: Highs and lows over a lookback period (e.g., 10 bars)
• Trendline Slope:
• Slope = (Pivot_new - Pivot_old) / (Time_new - Time_old)
• Trendline Projection:
• Projected Price = StartPrice + Slope × (CurrentTime - StartTime)
These lines act as dynamic support/resistance zones and are used to confirm breakout trades.
________________________________________
3. Volume and ATR Filters
Signals are filtered using real-time volume and volatility analysis to eliminate low-quality setups.
• Average Volume:
• AvgVol = SMA(Volume, 20)
• Volume Spike Condition:
• Volume > AvgVol × VolumeThreshold
• ATR (Volatility Filter) – Calculated using 14-bar period:
• (High - Low) > ATR × ATRMultiplier
When both filters are passed, the market is considered active and valid for trade.
________________________________________
4. Signal Generation Logic
• Bullish Signal: Triggered when:
o Price breaks above a resistance zone or bullish order block
o Volume and ATR filters confirm activity
o Trend alignment: EMA9 > EMA21 > EMA50
• Bearish Signal: Triggered under opposite conditions:
o Price breaks below a support zone or bearish order block
o Trend alignment: EMA9 < EMA21 < EMA50
Labels such as "BUY" or "SELL" appear on the chart at the trigger candle.
________________________________________
5. Target and Stop Loss Projection
The script dynamically calculates TP (take profit) and SL (stop loss) levels based on the ATR.
• For Long Trades:
• TP = High + (ATR × 2)
• SL = Low - (ATR × 1)
• For Short Trades:
• TP = Low - (ATR × 2)
• SL = High + (ATR × 1)
These levels are plotted on the chart and adjust as price evolves.
________________________________________
6. Performance Tracking
The script automatically tracks wins and losses for each signal based on TP/SL outcomes.
• Win Rate Formula:
• Win Rate (%) = (Number of Wins / Total Signals) × 100
This is useful for evaluating the system over time and adjusting risk or position sizing.
________________________________________
Practical Usage Steps
1. Apply the Indicator
o Add to your chart via Pine Editor or Indicators menu.
o Configure all input parameters including OB periods, pivot lookback, volume threshold, and ATR multiplier.
2. Signal Monitoring
o Wait for a "BUY" or "SELL" label to appear on the chart.
o Confirm alignment using:
EMA trend stacking (e.g., EMA9 > EMA21 > EMA50)
RSI/MACD momentum
Volume and ATR filters
3. Trade Execution
o Enter the trade on the candle following the signal.
o Use the plotted TP/SL lines to manage the trade.
o Monitor price action; exit if trend shifts or targets are achieved.
4. Review Performance
o Use the win rate and PnL counters to monitor your success.
o Analyze losing trades for trend or filter failures and optimize settings accordingly.
________________________________________
Alerts
The script includes alert support for:
• Signal Triggers: BUY or SELL label detection
• Take Profit / Stop Loss Hits: Automatically notifies when TP or SL is reached
These can be configured for push, email, or webhook delivery via TradingView alert settings.
________________________________________
Disclaimer from aiTrendview
This tool and the content provided by aiTrendview.com are for educational and research purposes only. They do not constitute investment advice, trading recommendations, or financial guidance. All forms of trading involve significant risk. Past performance does not guarantee future outcomes. Users are fully responsible for their trading decisions, including risk management, position sizing, and due diligence. It is strongly advised to test all strategies on a demo account before applying them to live capital. Consult a licensed financial advisor if necessary.
Signal Strength Technical AnalysisSignal Strength Technical Analysis – Study Material & Usage Guide
Overview:
This tool is a multi-layered TradingView indicator developed to help traders identify high-probability trade setups using order block detection, dynamic trendlines, volume and volatility filters, and ATR-based target projections. This guide outlines each feature, its formulaic foundation, and how to use the tool effectively in live markets.
________________________________________
Key Features and How to Use Them
1. Order Block Detection:
The script identifies institutional-level buying/selling zones using sequences of directional candles.
• You define the number of consecutive candles to qualify an order block.
• A move qualifies as an order block if:
• Price Move % = |Close(n) - Close(1)| / Close(n) × 100 ≥ Threshold
• Bullish Order Block: A down candle followed by multiple up candles.
• Bearish Order Block: An up candle followed by multiple down candles.
These blocks are plotted and used for trade entry confirmation and support/resistance analysis.
________________________________________
2. Trendline Logic:
Support and resistance lines are drawn dynamically using pivots.
• Pivot highs/lows are identified over a user-defined period (e.g., 10 bars).
• Trendline slope is calculated using:
• Slope = (Pivot_new - Pivot_old) / (Time_new - Time_old)
• Current projected support or resistance:
• Price = StartPrice + Slope × (CurrentTime - StartTime)
Breakouts beyond these levels are interpreted as potential trade signals when confirmed by other filters.
________________________________________
3. Volume and ATR Filters:
These filters help eliminate weak or low-conviction signals.
• Average Volume:
• AvgVol = SMA(Volume, 20)
• Volume Spike Detection:
• Volume > AvgVol × VolumeThreshold
• ATR Volatility Filter (ATR over 14 bars):
• (High - Low) > ATR × ATRMultiplier
If both filters pass, the market is considered active and eligible for trade setup.
________________________________________
4. Signal Generation Logic:
• Bullish Signal: Triggered when:
o Price breaks above resistance or a bullish order block
o Volume and ATR filters are passed
o Trend is confirmed: EMA9 > EMA21 > EMA50
• Bearish Signal: Triggered when:
o Price breaks below support or a bearish order block
o Volume and ATR filters are passed
o Trend is confirmed: EMA9 < EMA21 < EMA50
________________________________________
5. Target and Stop Loss Projection:
Based on the Average True Range (ATR):
• For Long Trades:
• TP = High + (ATR × 2)
• SL = Low - (ATR × 1)
• For Short Trades:
• TP = Low - (ATR × 2)
• SL = High + (ATR × 1)
Targets and stops are plotted on the chart and update dynamically.
________________________________________
6. Trade Management and Win Rate Calculation:
• Once in a trade, the script monitors price:
o Hits TP → Recorded as win
o Hits SL → Recorded as loss
• Win Rate Calculation:
• Win Rate = (Wins / Total Signals) × 100%
This helps track the strategy's live effectiveness and improve decision-making.
________________________________________
How to Use the Indicator – Practical Steps
1. Setup
o Add the indicator to your TradingView chart
o Configure OB periods, trendline pivots, volume and ATR multipliers
o Adjust display preferences
2. Wait for Signal
o Look for a “BUY” or “SELL” label to appear
o Confirm with:
EMA trend alignment
RSI and MACD momentum
Volume and ATR filters
3. Execute Trade
o Enter on the next bar after confirmation
o Use the plotted TP/SL levels as risk management
o Adjust position sizing according to your trading rules
4. Manage Trade
o Monitor PnL and win rate live
o Exit manually or let price hit TP/SL
o Respect the indicator’s environment reading (avoid trading in low-volatility or sideways zones)
________________________________________
Alerts and Automation
• The script includes built-in alert conditions for:
o Buy/Sell signal confirmation
o Take-profit level reached
o Stop-loss triggered
Enable alerts in TradingView to receive real-time notifications to your mobile, email, or connected services.
________________________________________
Disclaimer from aiTrendview
This tool is provided for educational and research purposes only. It is not intended as financial advice or an investment recommendation. Trading in financial markets involves substantial risk. Past performance does not guarantee future results. The user alone is responsible for all trading decisions, including risk management and strategy selection. We strongly recommend testing this tool on a demo account before applying it to real capital and consulting a licensed financial advisor where necessary.
Fixed 4H BTC/Altcoins Correlation for Scalping
Fixed 4H Timeframe: The calculation is hardcoded to the 4-hour timeframe. This ensures the correlation value remains stable and relevant for structural analysis while you trade on lower timeframes.
Clean On-Screen Display: Instead of a separate plot line that can clutter the chart, the indicator displays the correlation value in a clean, simple table in the top-right corner.
Dynamic Coloring: The correlation value is color-coded for quick visual assessment:
Green: Strong correlation (> 0.70)
Yellow: Moderate correlation (0.30 to 0.70)
Red: Weak or negative correlation (< 0.30)
Customizable Inputs: Users can easily configure the BTC symbol (e.g., BINANCE:BTCUSDT, COINBASE:BTCUSD), the correlation lookback period (Length), and the price source (Source) to match their reference indicators or preferences.
Add the indicator to your chart (for example, a 5-minute chart of any altcoin).
The table in the top-right corner will immediately display the altcoin's current correlation to BTC, based on 4-hour data.
Use this value to gauge market sentiment. A high positive correlation suggests the altcoin is likely to follow BTC's moves. A low or negative correlation suggests the altcoin is moving independently.
For perfect synchronization with another standard correlation indicator, go to the script's settings (⚙️ icon) and ensure the Length and Source parameters are identical to your reference indicator.
This tool aims to bridge the gap between high-frequency trading and high-timeframe market structure, providing a crucial piece of information in a simple, stable, and accessible format.
Manadi Buy/Sell Strategy EMA + MACD + RSI + AlertsIt is a strategy / indicator of buy and sell special crypto for 15 min to 1 h time frame.
used with RSI, Macd, and Ema cros 9/21
SMC Structures and FVGสวัสดีครับ! ผมจะอธิบายอินดิเคเตอร์ "SMC Structures and FVG + MACD" ที่คุณให้มาอย่างละเอียดในแต่ละส่วน เพื่อให้คุณเข้าใจการทำงานของมันอย่างถ่องแท้ครับ
อินดิเคเตอร์นี้เป็นการผสมผสานแนวคิดของ Smart Money Concept (SMC) ซึ่งเน้นการวิเคราะห์โครงสร้างตลาด (Market Structure) และ Fair Value Gap (FVG) เข้ากับอินดิเคเตอร์ MACD เพื่อใช้เป็นตัวกรองหรือตัวยืนยันสัญญาณ Choch/BoS (Change of Character / Break of Structure)
1. ภาพรวมอินดิเคเตอร์ (Overall Purpose)
อินดิเคเตอร์นี้มีจุดประสงค์หลักคือ:
ระบุโครงสร้างตลาด: ตีเส้นและป้ายกำกับ Choch (Change of Character) และ BoS (Break of Structure) บนกราฟโดยอัตโนมัติ
ผสานการยืนยันด้วย MACD: สัญญาณ Choch/BoS จะถูกพิจารณาก็ต่อเมื่อ MACD Histogram เกิดการตัดขึ้นหรือลง (Zero Cross) ในทิศทางที่สอดคล้องกัน
แสดง Fair Value Gap (FVG): หากเปิดใช้งาน จะมีการตีกล่อง FVG บนกราฟ
แสดงระดับ Fibonacci: คำนวณและแสดงระดับ Fibonacci ที่สำคัญตามโครงสร้างตลาดปัจจุบัน
ปรับตาม Timeframe: การคำนวณและการแสดงผลทั้งหมดจะปรับตาม Timeframe ที่คุณกำลังใช้งานอยู่โดยอัตโนมัติ
2. ส่วนประกอบหลักของโค้ด (Code Breakdown)
โค้ดนี้สามารถแบ่งออกเป็นส่วนหลัก ๆ ได้ดังนี้:
2.1 Inputs (การตั้งค่า)
ส่วนนี้คือตัวแปรที่คุณสามารถปรับแต่งได้ในหน้าต่างการตั้งค่าของอินดิเคเตอร์ (คลิกที่รูปฟันเฟืองข้างชื่ออินดิเคเตอร์บนกราฟ)
MACD Settings (ตั้งค่า MACD):
fast_len: ความยาวของ Fast EMA สำหรับ MACD (ค่าเริ่มต้น 12)
slow_len: ความยาวของ Slow EMA สำหรับ MACD (ค่าเริ่มต้น 26)
signal_len: ความยาวของ Signal Line สำหรับ MACD (ค่าเริ่มต้น 9)
= ta.macd(close, fast_len, slow_len, signal_len): คำนวณค่า MACD Line, Signal Line และ Histogram โดยใช้ราคาปิด (close) และค่าความยาวที่กำหนด
is_bullish_macd_cross: ตรวจสอบว่า MACD Histogram ตัดขึ้นเหนือเส้น 0 (จากค่าลบเป็นบวก)
is_bearish_macd_cross: ตรวจสอบว่า MACD Histogram ตัดลงใต้เส้น 0 (จากค่าบวกเป็นลบ)
Fear Value Gap (FVG) Settings:
isFvgToShow: (Boolean) เปิด/ปิดการแสดง FVG บนกราฟ
bullishFvgColor: สีสำหรับ Bullish FVG
bearishFvgColor: สีสำหรับ Bearish FVG
mitigatedFvgColor: สีสำหรับ FVG ที่ถูก Mitigate (ลดทอน) แล้ว
fvgHistoryNbr: จำนวน FVG ย้อนหลังที่จะแสดง
isMitigatedFvgToReduce: (Boolean) เปิด/ปิดการลดขนาด FVG เมื่อถูก Mitigate
Structures (โครงสร้างตลาด) Settings:
isStructBodyCandleBreak: (Boolean) หากเป็น true การ Break จะต้องเกิดขึ้นด้วย เนื้อเทียน ที่ปิดเหนือ/ใต้ Swing High/Low หากเป็น false แค่ไส้เทียนทะลุก็ถือว่า Break
isCurrentStructToShow: (Boolean) เปิด/ปิดการแสดงเส้นโครงสร้างตลาดปัจจุบัน (เส้นสีน้ำเงินในภาพตัวอย่าง)
pivot_len: ความยาวของแท่งเทียนที่ใช้ในการมองหาจุด Pivot (Swing High/Low) ยิ่งค่าน้อยยิ่งจับ Swing เล็กๆ ได้, ยิ่งค่ามากยิ่งจับ Swing ใหญ่ๆ ได้
bullishBosColor, bearishBosColor: สีสำหรับเส้นและป้าย BOS ขาขึ้น/ขาลง
bosLineStyleOption, bosLineWidth: สไตล์ (Solid, Dotted, Dashed) และความหนาของเส้น BOS
bullishChochColor, bearishChochColor: สีสำหรับเส้นและป้าย CHoCH ขาขึ้น/ขาลง
chochLineStyleOption, chochLineWidth: สไตล์ (Solid, Dotted, Dashed) และความหนาของเส้น CHoCH
currentStructColor, currentStructLineStyleOption, currentStructLineWidth: สี, สไตล์ และความหนาของเส้นโครงสร้างตลาดปัจจุบัน
structHistoryNbr: จำนวนการ Break (Choch/BoS) ย้อนหลังที่จะแสดง
Structure Fibonacci (จากโค้ดต้นฉบับ):
เป็นชุด Input สำหรับเปิด/ปิด, กำหนดค่า, สี, สไตล์ และความหนาของเส้น Fibonacci Levels ต่างๆ (0.786, 0.705, 0.618, 0.5, 0.382) ที่จะถูกคำนวณจากโครงสร้างตลาดปัจจุบัน
2.2 Helper Functions (ฟังก์ชันช่วยทำงาน)
getLineStyle(lineOption): ฟังก์ชันนี้ใช้แปลงค่า String ที่เลือกจาก Input (เช่น "─", "┈", "╌") ให้เป็นรูปแบบ line.style_ ที่ Pine Script เข้าใจ
get_structure_highest_bar(lookback): ฟังก์ชันนี้พยายามหา Bar Index ของแท่งเทียนที่ทำ Swing High ภายในช่วง lookback ที่กำหนด
get_structure_lowest_bar(lookback): ฟังก์ชันนี้พยายามหา Bar Index ของแท่งเทียนที่ทำ Swing Low ภายในช่วง lookback ที่กำหนด
is_structure_high_broken(...): ฟังก์ชันนี้ตรวจสอบว่าราคาปัจจุบันได้ Break เหนือ _structureHigh (Swing High) หรือไม่ โดยพิจารณาจาก _highStructBreakPrice (ราคาปิดหรือราคา High ขึ้นอยู่กับการตั้งค่า isStructBodyCandleBreak)
FVGDraw(...): ฟังก์ชันนี้รับ Arrays ของ FVG Boxes, Types, Mitigation Status และ Labels มาประมวลผล เพื่ออัปเดตสถานะของ FVG (เช่น ถูก Mitigate หรือไม่) และปรับขนาด/ตำแหน่งของ FVG Box และ Label บนกราฟ
2.3 Global Variables (ตัวแปรทั่วทั้งอินดิเคเตอร์)
เป็นตัวแปรที่ประกาศด้วย var ซึ่งหมายความว่าค่าของมันจะถูกเก็บไว้และอัปเดตในแต่ละแท่งเทียน (persists across bars)
structureLines, structureLabels: Arrays สำหรับเก็บอ็อบเจกต์ line และ label ของเส้น Choch/BoS ที่วาดบนกราฟ
fvgBoxes, fvgTypes, fvgLabels, isFvgMitigated: Arrays สำหรับเก็บข้อมูลของ FVG Boxes และสถานะต่างๆ
structureHigh, structureLow: เก็บราคาของ Swing High/Low ที่สำคัญของโครงสร้างตลาดปัจจุบัน
structureHighStartIndex, structureLowStartIndex: เก็บ Bar Index ของจุดเริ่มต้นของ Swing High/Low ที่สำคัญ
structureDirection: เก็บสถานะของทิศทางโครงสร้างตลาด (1 = Bullish, 2 = Bearish, 0 = Undefined)
fiboXPrice, fiboXStartIndex, fiboXLine, fiboXLabel: ตัวแปรสำหรับเก็บข้อมูลและอ็อบเจกต์ของเส้น Fibonacci Levels
isBOSAlert, isCHOCHAlert: (Boolean) ใช้สำหรับส่งสัญญาณ Alert (หากมีการตั้งค่า Alert ไว้)
2.4 FVG Processing (การประมวลผล FVG)
ส่วนนี้จะตรวจสอบเงื่อนไขการเกิด FVG (Bullish FVG: high < low , Bearish FVG: low > high )
หากเกิด FVG และ isFvgToShow เป็น true จะมีการสร้าง box และ label ใหม่เพื่อแสดง FVG บนกราฟ
มีการจัดการ fvgBoxes และ fvgLabels เพื่อจำกัดจำนวน FVG ที่แสดงตาม fvgHistoryNbr และลบ FVG เก่าออก
ฟังก์ชัน FVGDraw จะถูกเรียกเพื่ออัปเดตสถานะของ FVG (เช่น การถูก Mitigate) และปรับการแสดงผล
2.5 Structures Processing (การประมวลผลโครงสร้างตลาด)
Initialization: ที่ bar_index == 0 (แท่งเทียนแรกของกราฟ) จะมีการกำหนดค่าเริ่มต้นให้กับ structureHigh, structureLow, structureHighStartIndex, structureLowStartIndex
Finding Current High/Low: highest, highestBar, lowest, lowestBar ถูกใช้เพื่อหา High/Low ที่สุดและ Bar Index ของมันใน 10 แท่งล่าสุด (หรือทั้งหมดหากกราฟสั้นกว่า 10 แท่ง)
Calculating Structure Max/Min Bar: structureMaxBar และ structureMinBar ใช้ฟังก์ชัน get_structure_highest_bar และ get_structure_lowest_bar เพื่อหา Bar Index ของ Swing High/Low ที่แท้จริง (ไม่ใช่แค่ High/Low ที่สุดใน lookback แต่เป็นจุด Pivot ที่สมบูรณ์)
Break Price: lowStructBreakPrice และ highStructBreakPrice จะเป็นราคาปิด (close) หรือราคา Low/High ขึ้นอยู่กับ isStructBodyCandleBreak
isStuctureLowBroken / isStructureHighBroken: เงื่อนไขเหล่านี้ตรวจสอบว่าราคาได้ทำลาย structureLow หรือ structureHigh หรือไม่ โดยพิจารณาจากราคา Break, ราคาแท่งก่อนหน้า และ Bar Index ของจุดเริ่มต้นโครงสร้าง
Choch/BoS Logic (ส่วนสำคัญที่ถูกผสานกับ MACD):
if(isStuctureLowBroken and is_bearish_macd_cross): นี่คือจุดที่ MACD เข้ามามีบทบาท หากราคาทำลาย structureLow (สัญญาณขาลง) และ MACD Histogram เกิด Bearish Zero Cross (is_bearish_macd_cross เป็น true) อินดิเคเตอร์จะพิจารณาว่าเป็น Choch หรือ BoS
หาก structureDirection == 1 (เดิมเป็นขาขึ้น) หรือ 0 (ยังไม่กำหนด) จะตีเป็น "CHoCH" (เปลี่ยนทิศทางโครงสร้างเป็นขาลง)
หาก structureDirection == 2 (เดิมเป็นขาลง) จะตีเป็น "BOS" (ยืนยันโครงสร้างขาลง)
มีการสร้าง line.new และ label.new เพื่อวาดเส้นและป้ายกำกับ
structureDirection จะถูกอัปเดตเป็น 1 (Bullish)
structureHighStartIndex, structureLowStartIndex, structureHigh, structureLow จะถูกอัปเดตเพื่อกำหนดโครงสร้างใหม่
else if(isStructureHighBroken and is_bullish_macd_cross): เช่นกันสำหรับขาขึ้น หากราคาทำลาย structureHigh (สัญญาณขาขึ้น) และ MACD Histogram เกิด Bullish Zero Cross (is_bullish_macd_cross เป็น true) อินดิเคเตอร์จะพิจารณาว่าเป็น Choch หรือ BoS
หาก structureDirection == 2 (เดิมเป็นขาลง) หรือ 0 (ยังไม่กำหนด) จะตีเป็น "CHoCH" (เปลี่ยนทิศทางโครงสร้างเป็นขาขึ้น)
หาก structureDirection == 1 (เดิมเป็นขาขึ้น) จะตีเป็น "BOS" (ยืนยันโครงสร้างขาขึ้น)
มีการสร้าง line.new และ label.new เพื่อวาดเส้นและป้ายกำกับ
structureDirection จะถูกอัปเดตเป็น 2 (Bearish)
structureHighStartIndex, structureLowStartIndex, structureHigh, structureLow จะถูกอัปเดตเพื่อกำหนดโครงสร้างใหม่
การลบเส้นเก่า: d.delete_line (หากไลบรารีทำงาน) จะถูกเรียกเพื่อลบเส้นและป้ายกำกับเก่าออกเมื่อจำนวนเกิน structHistoryNbr
Updating Structure High/Low (else block): หากไม่มีการ Break เกิดขึ้น แต่ราคาปัจจุบันสูงกว่า structureHigh หรือต่ำกว่า structureLow ในทิศทางที่สอดคล้องกัน (เช่น ยังคงเป็นขาขึ้นและทำ High ใหม่) structureHigh หรือ structureLow จะถูกอัปเดตเพื่อติดตาม High/Low ที่สุดของโครงสร้างปัจจุบัน
Current Structure Display:
หาก isCurrentStructToShow เป็น true อินดิเคเตอร์จะวาดเส้น structureHighLine และ structureLowLine เพื่อแสดงขอบเขตของโครงสร้างตลาดปัจจุบัน
Fibonacci Display:
หาก isFiboXToShow เป็น true อินดิเคเตอร์จะคำนวณและวาดเส้น Fibonacci Levels ต่างๆ (0.786, 0.705, 0.618, 0.5, 0.382) โดยอิงจาก structureHigh และ structureLow ของโครงสร้างตลาดปัจจุบัน
Alerts:
alertcondition: ใช้สำหรับตั้งค่า Alert ใน TradingView เมื่อเกิดสัญญาณ BOS หรือ CHOCH
plot(na):
plot(na) เป็นคำสั่งที่สำคัญในอินดิเคเตอร์ที่ไม่ได้ต้องการพล็อต Series ของข้อมูลบนกราฟ (เช่น ไม่ได้พล็อตเส้น EMA หรือ RSI) แต่ใช้วาดอ็อบเจกต์ (Line, Label, Box) โดยตรง
การมี plot(na) ช่วยให้ Pine Script รู้ว่าอินดิเคเตอร์นี้มีเอาต์พุตที่แสดงผลบนกราฟ แม้ว่าจะไม่ได้เป็น Series ที่พล็อตตามปกติก็ตาม
3. วิธีใช้งาน
คัดลอกโค้ดทั้งหมด ที่อยู่ในบล็อก immersive ด้านบน
ไปที่ TradingView และเปิดกราฟที่คุณต้องการ
คลิกที่เมนู "Pine Editor" ที่อยู่ด้านล่างของหน้าจอ
ลบโค้ดเดิมที่มีอยู่ และ วางโค้ดที่คัดลอกมา ลงไปแทน
คลิกที่ปุ่ม "Add to Chart"
อินดิเคเตอร์จะถูกเพิ่มลงในกราฟของคุณโดยอัตโนมัติ คุณสามารถคลิกที่รูปฟันเฟืองข้างชื่ออินดิเคเตอร์บนกราฟเพื่อเข้าถึงหน้าต่างการตั้งค่าและปรับแต่งตามความต้องการของคุณได้
Hello! I will explain the "SMC Structures and FVG + MACD" indicator you provided in detail, section by section, so you can fully understand how it works.This indicator combines the concepts of Smart Money Concept (SMC), which focuses on analyzing Market Structure and Fair Value Gaps (FVG), with the MACD indicator to serve as a filter or confirmation for Choch (Change of Character) and BoS (Break of Structure) signals.1. Overall PurposeThe main purposes of this indicator are:Identify Market Structure: Automatically draw lines and label Choch (Change of Character) and BoS (Break of Structure) on the chart.Integrate MACD Confirmation: Choch/BoS signals will only be considered when the MACD Histogram performs a cross (Zero Cross) in the corresponding direction.Display Fair Value Gap (FVG): If enabled, FVG boxes will be drawn on the chart.Display Fibonacci Levels: Calculate and display important Fibonacci levels based on the current market structure.Adapt to Timeframe: All calculations and displays will automatically adjust to the timeframe you are currently using.2. Code BreakdownThis code can be divided into the following main sections:2.1 Inputs (Settings)This section contains variables that you can adjust in the indicator's settings window (click the gear icon next to the indicator's name on the chart).MACD Settings:fast_len: Length of the Fast EMA for MACD (default 12)slow_len: Length of the Slow EMA for MACD (default 26)signal_len: Length of the Signal Line for MACD (default 9) = ta.macd(close, fast_len, slow_len, signal_len): Calculates the MACD Line, Signal Line, and Histogram using the closing price (close) and the specified lengths.is_bullish_macd_cross: Checks if the MACD Histogram crosses above the 0 line (from negative to positive).is_bearish_macd_cross: Checks if the MACD Histogram crosses below the 0 line (from positive to negative).Fear Value Gap (FVG) Settings:isFvgToShow: (Boolean) Enables/disables the display of FVG on the chart.bullishFvgColor: Color for Bullish FVG.bearishFvgColor: Color for Bearish FVG.mitigatedFvgColor: Color for FVG that has been mitigated.fvgHistoryNbr: Number of historical FVG to display.isMitigatedFvgToReduce: (Boolean) Enables/disables reducing the size of FVG when mitigated.Structures (โครงสร้างตลาด) Settings:isStructBodyCandleBreak: (Boolean) If true, the break must occur with the candle body closing above/below the Swing High/Low. If false, a wick break is sufficient.isCurrentStructToShow: (Boolean) Enables/disables the display of the current market structure lines (blue lines in the example image).pivot_len: Lookback length for identifying Pivot points (Swing High/Low). A smaller value captures smaller, more frequent swings; a larger value captures larger, more significant swings.bullishBosColor, bearishBosColor: Colors for bullish/bearish BOS lines and labels.bosLineStyleOption, bosLineWidth: Style (Solid, Dotted, Dashed) and width of BOS lines.bullishChochColor, bearishChochColor: Colors for bullish/bearish CHoCH lines and labels.chochLineStyleOption, chochLineWidth: Style (Solid, Dotted, Dashed) and width of CHoCH lines.currentStructColor, currentStructLineStyleOption, currentStructLineWidth: Color, style, and width of the current market structure lines.structHistoryNbr: Number of historical breaks (Choch/BoS) to display.Structure Fibonacci (from original code):A set of inputs to enable/disable, define values, colors, styles, and widths for various Fibonacci Levels (0.786, 0.705, 0.618, 0.5, 0.382) that will be calculated from the current market structure.2.2 Helper FunctionsgetLineStyle(lineOption): This function converts the selected string input (e.g., "─", "┈", "╌") into a line.style_ format understood by Pine Script.get_structure_highest_bar(lookback): This function attempts to find the Bar Index of the Swing High within the specified lookback period.get_structure_lowest_bar(lookback): This function attempts to find the Bar Index of the Swing Low within the specified lookback period.is_structure_high_broken(...): This function checks if the current price has broken above _structureHigh (Swing High), considering _highStructBreakPrice (closing price or high price depending on isStructBodyCandleBreak setting).FVGDraw(...): This function takes arrays of FVG Boxes, Types, Mitigation Status, and Labels to process and update the status of FVG (e.g., whether it's mitigated) and adjust the size/position of FVG Boxes and Labels on the chart.2.3 Global VariablesThese are variables declared with var, meaning their values are stored and updated on each bar (persists across bars).structureLines, structureLabels: Arrays to store line and label objects for Choch/BoS lines drawn on the chart.fvgBoxes, fvgTypes, fvgLabels, isFvgMitigated: Arrays to store FVG box data and their respective statuses.structureHigh, structureLow: Stores the price of the significant Swing High/Low of the current market structure.structureHighStartIndex, structureLowStartIndex: Stores the Bar Index of the start point of the significant Swing High/Low.structureDirection: Stores the status of the market structure direction (1 = Bullish, 2 = Bearish, 0 = Undefined).fiboXPrice, fiboXStartIndex, fiboXLine, fiboXLabel: Variables to store data and objects for Fibonacci Levels.isBOSAlert, isCHOCHAlert: (Boolean) Used to trigger alerts in TradingView (if alerts are configured).2.4 FVG ProcessingThis section checks the conditions for FVG formation (Bullish FVG: high < low , Bearish FVG: low > high ).If FVG occurs and isFvgToShow is true, a new box and label are created to display the FVG on the chart.fvgBoxes and fvgLabels are managed to limit the number of FVG displayed according to fvgHistoryNbr and remove older FVG.The FVGDraw function is called to update the FVG status (e.g., whether it's mitigated) and adjust its display.2.5 Structures ProcessingInitialization: At bar_index == 0 (the first bar of the chart), structureHigh, structureLow, structureHighStartIndex, and structureLowStartIndex are initialized.Finding Current High/Low: highest, highestBar, lowest, lowestBar are used to find the highest/lowest price and its Bar Index of it in the last 10 bars (or all bars if the chart is shorter than 10 bars).Calculating Structure Max/Min Bar: structureMaxBar and structureMinBar use get_structure_highest_bar and get_structure_lowest_bar functions to find the Bar Index of the true Swing High/Low (not just the highest/lowest in the lookback but a complete Pivot point).Break Price: lowStructBreakPrice and highStructBreakPrice will be the closing price (close) or the Low/High price, depending on the isStructBodyCandleBreak setting.isStuctureLowBroken / isStructureHighBroken: These conditions check if the price has broken structureLow or structureHigh, considering the break price, previous bar prices, and the Bar Index of the structure's starting point.Choch/BoS Logic (Key Integration with MACD):if(isStuctureLowBroken and is_bearish_macd_cross): This is where MACD plays a role. If the price breaks structureLow (bearish signal) AND the MACD Histogram performs a Bearish Zero Cross (is_bearish_macd_cross is true), the indicator will consider it a Choch or BoS.If structureDirection == 1 (previously bullish) or 0 (undefined), it will be labeled "CHoCH" (changing structure direction to bearish).If structureDirection == 2 (already bearish), it will be labeled "BOS" (confirming bearish structure).line.new and label.new are used to draw the line and label.structureDirection will be updated to 1 (Bullish).structureHighStartIndex, structureLowStartIndex, structureHigh, structureLow will be updated to define the new structure.else if(isStructureHighBroken and is_bullish_macd_cross): Similarly for bullish breaks. If the price breaks structureHigh (bullish signal) AND the MACD Histogram performs a Bullish Zero Cross (is_bullish_macd_cross is true), the indicator will consider it a Choch or BoS.If structureDirection == 2 (previously bearish) or 0 (undefined), it will be labeled "CHoCH" (changing structure direction to bullish).If structureDirection == 1 (already bullish), it will be labeled "BOS" (confirming bullish structure).line.new and label.new are used to draw the line and label.structureDirection will be updated to 2 (Bearish).structureHighStartIndex, structureLowStartIndex, structureHigh, structureLow will be updated to define the new structure.Deleting Old Lines: d.delete_line (if the library works) will be called to delete old lines and labels when their number exceeds structHistoryNbr.Updating Structure High/Low (else block): If no break occurs, but the current price is higher than structureHigh or lower than structureLow in the corresponding direction (e.g., still bullish and making a new high), structureHigh or structureLow will be updated to track the highest/lowest point of the current structure.Current Structure Display:If isCurrentStructToShow is true, the indicator draws structureHighLine and structureLowLine to show the boundaries of the current market structure.Fibonacci Display:If isFiboXToShow is true, the indicator calculates and draws various Fibonacci Levels (0.786, 0.705, 0.618, 0.5, 0.382) based on the structureHigh and structureLow of the current market structure.Alerts:alertcondition: Used to set up alerts in TradingView when BOS or CHOCH signals occur.plot(na):plot(na) is an important statement in indicators that do not plot data series directly on the chart (e.g., not plotting EMA or RSI lines) but instead draw objects (Line, Label, Box).Having plot(na) helps Pine Script recognize that this indicator has an output displayed on the chart, even if it's not a regularly plotted series.3. How to UseCopy all the code in the immersive block above.Go to TradingView and open your desired chart.Click on the "Pine Editor" menu at the bottom of the screen.Delete any existing code and paste the copied code in its place.Click the "Add to Chart" button.The indicator will be added to your chart automatically. You can click the gear icon next to the indicator's name on the chart to access the settings window and customize it to your needs.I hope this explanation helps you understand this indicator in detail. If anything is unclear, or you need further adjustments, please let me know.
COT INDEX
// Users & Producers: Commercial Positions
// Large Specs (Hedge Fonds): Non-commercial Positions
// Retail: Non-reportable Positions
//@version=5
int weeks = input.int(26, "Number of weeks", minval=1)
int upperExtreme = input.int(80, "Upper Threshold in %", minval=50)
int lowerExtreme = input.int(20, "Lower Threshold in %", minval=1)
bool hideCurrentWeek = input(true, "Hide the current week until market close")
bool markExtremes = input(false, "Mark long and short extremes")
bool showSmallSpecs = input(true, "Show small speculators index")
bool showProducers = input(true, "Show producers index")
bool showLargeSpecs = input(true, "Show large speculators index")
indicator("COT INDEX", shorttitle="COT INDEX", format=format.percent, precision=0)
import TradingView/LibraryCOT/2 as cot
// Function to fix some symbols.
var string Root_Symbol = syminfo.root
var string CFTC_Code_fixed = cot.convertRootToCOTCode("Auto")
if Root_Symbol == "HG"
CFTC_Code_fixed := "085692"
else if Root_Symbol == "LBR"
CFTC_Code_fixed := "058644"
// Function to request COT data for Futures only.
dataRequest(metricName, isLong) =>
tickerId = cot.COTTickerid('Legacy', CFTC_Code_fixed, false, metricName, isLong ? "Long" : "Short", "All")
value = request.security(tickerId, "1D", close, ignore_invalid_symbol = true)
if barstate.islastconfirmedhistory and na(value)
runtime.error("Could not find relevant COT data based on the current symbol.")
value
// Function to calculate net long positions.
netLongCommercialPositions() =>
commercialLong = dataRequest("Commercial Positions", true)
commercialShort = dataRequest("Commercial Positions", false)
commercialLong - commercialShort
netLongLargePositions() =>
largeSpecsLong = dataRequest("Noncommercial Positions", true)
largeSpecsShort = dataRequest("Noncommercial Positions", false)
largeSpecsLong - largeSpecsShort
netLongSmallPositions() =>
smallSpecsLong = dataRequest("Nonreportable Positions", true)
smallSpecsShort = dataRequest("Nonreportable Positions", false)
smallSpecsLong - smallSpecsShort
calcIndex(netPos) =>
minNetPos = ta.lowest(netPos, weeks)
maxNetPos = ta.highest(netPos, weeks)
if maxNetPos != minNetPos
100 * (netPos - minNetPos) / (maxNetPos - minNetPos)
else
na
// Calculate the Commercials Position Index.
commercialsIndex = calcIndex(netLongCommercialPositions())
largeSpecsIndex = calcIndex(netLongLargePositions())
smallSpecsIndex = calcIndex(netLongSmallPositions())
// Conditional logic based on user input
plotValueCommercials = hideCurrentWeek ? (timenow >= time_close ? commercialsIndex : na) : (showProducers ? commercialsIndex : na)
plotValueLarge = hideCurrentWeek ? (timenow >= time_close ? largeSpecsIndex : na) : (showLargeSpecs ? largeSpecsIndex : na)
plotValueSmall = hideCurrentWeek ? (timenow >= time_close ? smallSpecsIndex : na) : (showSmallSpecs ? smallSpecsIndex : na)
// Plot the index and horizontal lines
plot(plotValueCommercials, "Commercials", color=color.blue, style=plot.style_line, linewidth=2)
plot(plotValueLarge, "Large Speculators", color=color.red, style=plot.style_line, linewidth=1)
plot(plotValueSmall, "Small Speculators", color=color.green, style=plot.style_line, linewidth=1)
hline(upperExtreme, "Upper Threshold", color=color.green, linestyle=hline.style_solid, linewidth=1)
hline(lowerExtreme, "Lower Threshold", color=color.red, linestyle=hline.style_solid, linewidth=1)
/// Marking extremes with background color
bgcolor(markExtremes and (commercialsIndex >= upperExtreme or largeSpecsIndex >= upperExtreme or smallSpecsIndex >= upperExtreme) ? color.new(color.gray, 90) : na, title="Upper Threshold")
bgcolor(markExtremes and (commercialsIndex <= lowerExtreme or largeSpecsIndex <= lowerExtreme or smallSpecsIndex <= lowerExtreme) ? color.new(color.gray, 90) : na, title="Lower Threshold")