siam RSI Crossอินดิเคเตอร์ "Siam RSI Cross" ช่วยระบุจุดตัดระหว่าง RSI และ SMA ในโซน overbought (เหนือ 70) และ oversold (ใต้ 30)
- เส้นปะสีเหลืองและจุดสีแดง: RSI ตัดขึ้นใต้ระดับ 30 (โซน oversold)
- เส้นปะสีขาวและจุดสีเขียว: RSI ตัดลงเหนือระดับ 70 (โซน overbought)
- ปรับแต่งได้: ความยาว RSI (MA 1) และ SMA (MA 2)
- รองรับการแจ้งเตือนสำหรับสัญญาณซื้อ/ขาย
สรุปการทำงานของสคริปต์:
1. วัตถุประสงค์หลัก:
อินดิเคเตอร์นี้ใช้ RSI (Relative Strength Index) และ SMA (Simple Moving Average) ของ RSI เพื่อระบุจุดตัด (crossover และ crossunder) ในโซน overbought (เหนือ 70) และ oversold (ใต้ 30)
แสดงสัญญาณด้วย:
เส้นปะแนวตั้ง: เพื่อระบุจุดตัดในโซนที่กำหนด
จุดสี: เพื่อเน้นจุดตัดให้ชัดเจนยิ่งขึ้น
การแจ้งเตือน: เพื่อให้ผู้ใช้ตั้งค่าแจ้งเตือนใน TradingView ได้
2. องค์ประกอบของอินดิเคเตอร์:
เส้น RSI: คำนวณจาก ta.rsi(close, len1) โดย len1 (ค่าเริ่มต้น 34) เป็นความยาวที่ผู้ใช้กำหนดได้ แสดงเป็นเส้นสีน้ำเงิน
เส้น SMA ของ RSI: คำนวณจาก ta.sma(sh, len2) โดย len2 (ค่าเริ่มต้น 68) เป็นความยาวที่ผู้ใช้กำหนดได้ แสดงเป็นเส้นสีเขียว
เส้นแนวนอน: ที่ระดับ 30 (Oversold) และ 70 (Overbought) เป็นเส้นสีเทาแบบปะ
การเติมสีระหว่างเส้น 30 และ 70: ใช้สีน้ำเงินโปร่งใส (opacity 80)
การเติมสีระหว่าง RSI และ SMA:
สีเขียวอ่อน (lime) เมื่อ RSI > SMA
สีแดงเมื่อ RSI < SMA
3. เงื่อนไขและการแสดงสัญญาณ:
RSI ตัดขึ้น (Crossover) ใต้เส้น 30:
เงื่อนไข: RSI ตัดขึ้นผ่าน SMA (ta.crossover(sh, ln)) และ RSI < 30 (sh < 30)
เส้นปะแนวตั้งสีเหลือง: วาดจากระดับ 0 ถึง 100 ในหน้าต่าง RSI ด้วย line.new
จุดสีแดง: วาดที่ระดับ RSI (sh) ตรงจุดตัด ด้วย plotshape (รูปวงกลม, ขนาดเล็ก)
RSI ตัดลง (Crossunder) เหนือเส้น 70:
เงื่อนไข: RSI ตัดลงผ่าน SMA (ta.crossunder(sh, ln)) และ RSI > 70 (sh > 70 and sh > 70)
เส้นปะแนวตั้งสีขาว: วาดจากระดับ 0 ถึง 100 ในหน้าต่าง RSI ด้วย line.new
จุดสีเขียว: วาดที่ระดับ RSI (sh) ตรงจุดตัด ด้วย plotshape (รูปวงกลม, ขนาดเล็ก)
หมายเหตุ: เงื่อนไข sh > 70 and sh > 70 ช่วยให้แน่ใจว่าการตัดลงเกิดในโซน overbought และป้องกันการตรวจจับที่ผิดพลาด
4. การแจ้งเตือน (Alert Conditions):
สัญญาณซื้อทั่วไป: เมื่อ RSI ตัดขึ้นผ่าน SMA (ta.crossover(sh, ln)) ชื่อ: "Buy", ข้อความ: "RSI Cross. Buy Signal"
สัญญาณขายทั่วไป: เมื่อ RSI ตัดลงผ่าน SMA (ta.crossunder(sh, ln)) ชื่อ: "Sell", ข้อความ: "RSI Cross. Sell Signal"
สัญญาณตัดขึ้นใต้ 30: ชื่อ: "Buy Cross Below 30", ข้อความ: "RSI Cross Up Below 30"
สัญญาณตัดลงเหนือ 70: ชื่อ: "Sell Cross Above 70", ข้อความ: "RSI Cross Down Above 70"
ผู้ใช้สามารถตั้งค่าการแจ้งเตือนใน TradingView โดยเลือกเงื่อนไขเหล่านี้
5. การตั้งค่าที่ผู้ใช้ปรับได้:
len1: ความยาวของ RSI (ค่าเริ่มต้น: 34) ปรับได้ผ่านอินพุต "MA 1"
len2: ความยาวของ SMA (ค่าเริ่มต้น: 68) ปรับได้ผ่านอินพุต "MA 2"
6. การแสดงผล:
อินดิเคเตอร์แสดงในหน้าต่างแยก (ไม่ทับบนชาร์ตราคา) เนื่องจาก overlay=false
เส้นแนวตั้งและจุดสีทั้งหมดปรากฏในหน้าต่าง RSI โดย:
เส้นปะแนวตั้งครอบคลุมช่วง 0 ถึง 100
จุดสีแดงและสีเขียวอยู่ที่ระดับ RSI ตรงจุดตัด
Summary of the Script's Functionality:
1. Main Objective:
The indicator uses the Relative Strength Index (RSI) and a Simple Moving Average (SMA) of the RSI to identify crossover and crossunder points in the overbought (above 70) and oversold (below 30) zones.
It displays signals using:
Dashed vertical lines: To mark crossover/crossunder points in the specified zones.
Colored dots: To highlight the crossover/crossunder points more clearly.
Alerts: To allow users to set up notifications in TradingView.
2. Components of the Indicator:
RSI Line: Calculated using ta.rsi(close, len1), where len1 (default: 34) is a user-defined length, displayed as a blue line.
SMA of RSI: Calculated using ta.sma(sh, len2), where len2 (default: 68) is a user-defined length, displayed as a green line.
Horizontal Lines: At levels 30 (Oversold) and 70 (Overbought), shown as dashed gray lines.
Fill Between 30 and 70: Filled with a translucent blue color (opacity 80).
Fill Between RSI and SMA:
Light green (lime) when RSI > SMA.
Red when RSI < SMA.
3. Conditions and Signal Display:
RSI Crossover Below 30:
Condition: RSI crosses above SMA (ta.crossover(sh, ln)) and RSI < 30 (sh < 30).
Yellow Dashed Vertical Line: Drawn from level 0 to 100 in the RSI window using line.new.
Red Dot: Plotted at the RSI level (sh) at the crossover point using plotshape (circle shape, small size).
RSI Crossunder Above 70:
Condition: RSI crosses below SMA (ta.crossunder(sh, ln)) and RSI > 70 (sh > 70 and sh > 70).
White Dashed Vertical Line: Drawn from level 0 to 100 in the RSI window using line.new.
Green Dot: Plotted at the RSI level (sh) at the crossunder point using plotshape (circle shape, small size).
Note: The condition sh > 70 and sh > 70 ensures that the crossunder occurs in the overbought zone and prevents false detections.
4. Alert Conditions:
General Buy Signal: When RSI crosses above SMA (ta.crossover(sh, ln)), Name: "Buy", Message: "RSI Cross. Buy Signal".
General Sell Signal: When RSI crosses below SMA (ta.crossunder(sh, ln)), Name: "Sell", Message: "RSI Cross. Sell Signal".
Crossover Below 30 Signal: Name: "Buy Cross Below 30", Message: "RSI Cross Up Below 30".
Crossunder Above 70 Signal: Name: "Sell Cross Above 70", Message: "RSI Cross Down Above 70".
Users can set up alerts in TradingView by selecting these conditions.
5. User-Adjustable Settings:
len1: RSI length (default: 34), adjustable via the "MA 1" input.
len2: SMA length (default: 68), adjustable via the "MA 2" input.
6. Display:
The indicator is displayed in a separate window (not overlaid on the price chart) due to overlay=false.
All vertical lines and colored dots appear in the RSI window:
Dashed vertical lines span from 0 to 100.
Red and green dots are placed at the RSI level at the crossover/crossunder points.
Fundamental Analysis
My-Indicator - Global Liquidity & Money Supply M2 + Time OffsetThis script is designed to visualize a global liquidity and money supply index by combining data from various regions and, optionally, central bank activity. Visualizing this data on a chart allows you to see how central banks are intervening in the financial system and how the total amount of money in the economy is changing. Let’s take a look at how it works:
Central Bank Liquidity
Shows the actions of central banks (e.g. FED, ECB) providing short-term cash to commercial banks. If you see spikes or a steady increase in these indicators, it may suggest that liquidity is being increased through intervention, which often stimulates the market.
Money Supply
M2 money supply is a monetary aggregate that includes M1 (cash and current deposits) plus savings deposits, small term deposits, and other financial instruments that, while not as liquid as M1, can be quickly converted into cash. As a result, M2 provides a broader picture of the available money in the economy, which is useful for analyzing market conditions and potential economic trends.
How does it help investors?
It allows you to quickly see when central banks are injecting additional liquidity, which could signal higher prices.
It allows you to see trends in the money supply, which informs potential changes in inflation and the economic cycle.
Combining both sets of data provides a more complete picture – both in the short and long term – which makes it easier to predict upcoming price movements.
This allows investors to better respond to changes in central bank policy and broader monetary trends, increasing their chances of making better investment decisions.
Data Collection
The script retrieves money supply data for key markets such as the USA (USM2), Europe (EUM2), China (CNM2), and Japan (JPM2). It also offers additional money supply series for other markets—like Canada (CAM2), Great Britain (GBM2), Russia (RUM2), Brazil (BRM2), Mexico (MXM2), and New Zealand (NZM2)—with extra options (e.g., Australia, India, Korea, Indonesia, Malaysia, Sweden) disabled by default. Moreover, you can enable data for central bank liquidity (such as FED, RRP, TGA, ECB, PBC, BOJ, and other central banks), which are also disabled by default.
Index Calculation
The indicator calculates the index by adding together all the enabled money supply series (and the central bank data if activated) and then scales the sum by dividing it by 1,000,000,000,000 (one trillion). This scaling makes the resulting values more manageable and easier to read on the chart.
Time Offset Feature
A key feature of the script is the time offset. With the input parameter "Time Offset (days)", the user can shift the plotted index line by a specific number of days. The script converts the given offset in days into a number of bars based on the current chart's timeframe. This allows you to adjust for the delay between liquidity changes and their effect on asset prices.
Overall, the indicator plots a line on your chart representing the global liquidity and money supply index, allowing you to visually monitor trends and better understand how liquidity and central bank actions may influence market movements.
What makes this script different from others?
Every supported market—both major regions (USA, Eurozone, China, Japan, etc.) and additional ones—is available. You can toggle each series on or off, so you can view only Money Supply data, only Central Bank Liquidity, or any custom combination.
Separated Data Groups. Inputs are organized into clear groups (“Money Supply”, “Other Money Supply”, “Central Bank Liquidity”), making it easy to focus on just the data you need without clutter.
True Day‑Based Offset. This script converts your chosen “Time Offset (days)” into actual days regardless of timeframe. Whether you’re on a 5‑minute or daily chart, the index is always shifted by exactly the number of days you specify.
PEAD strategy█ OVERVIEW
This strategy trades the classic post-earnings announcement drift (PEAD).
It goes long only when the market gaps up after a positive EPS surprise.
█ LOGIC
1 — Earnings filter — EPS surprise > epsSprThresh %
2 — Gap filter — first regular 5-minute bar gaps ≥ gapThresh % above yesterday’s close
3 — Timing — only the first qualifying gap within one trading day of the earnings bar
4 — Momentum filter — last perfDays trading-day performance is positive
5 — Risk management
• Fixed stop-loss: stopPct % below entry
• Trailing exit: price < Daily EMA( emaLen )
█ INPUTS
• Gap up threshold (%) — 1 (gap size for entry)
• EPS surprise threshold (%) — 5 (min positive surprise)
• Past price performance — 20 (look-back bars for trend check)
• Fixed stop-loss (%) — 8 (hard stop distance)
• Daily EMA length — 30 (trailing exit length)
Note — Back-tests fill on the second 5-minute bar (Pine limitation).
Live trading: enable calc_on_every_tick=true for first-tick entries.
────────────────────────────────────────────
█ 概要(日本語)
本ストラテジーは決算後の PEAD を狙い、
EPS サプライズがプラス かつ 寄付きギャップアップ が発生した銘柄をスイングで買い持ちします。
█ ロジック
1 — 決算フィルター — EPS サプライズ > epsSprThresh %
2 — ギャップフィルター — レギュラー時間最初の 5 分足が前日終値+ gapThresh %以上
3 — タイミング — 決算当日または翌営業日の最初のギャップのみエントリー
4 — モメンタムフィルター — 過去 perfDays 営業日の騰落率がプラス
5 — リスク管理
• 固定ストップ:エントリー − stopPct %
• 利確:終値が日足 EMA( emaLen ) を下抜け
█ 入力パラメータ
• Gap up threshold (%) — 1 (ギャップ条件)
• EPS surprise threshold (%) — 5 (EPS サプライズ最小値)
• Past price performance — 20 (パフォーマンス判定日数)
• Fixed stop-loss (%) — 8 (固定ストップ幅)
• Daily EMA length — 30 (利確用 EMA 期間)
注意 — Pine の仕様上、バックテストでは寄付き 5 分足の次バーで約定します。
実運用で寄付き成行に合わせたい場合は calc_on_every_tick=true を有効にしてください。
────
ご意見や質問があればお気軽にコメントください。
Happy trading!
DDDDD: SET50 (40 Stocks) - % New 52W LowsDDDDD: SET50 - % New 52W Lows (40 Stocks)
This indicator measures the percentage of selected SET50 stocks making a new 52-week low, helping identify periods of extreme market fear that often align with long-term buying opportunities.
How It Works:
Tracks the daily closing prices of 40 major SET50 constituents.
A stock is counted when it closes at its lowest price over the past 252 trading days (approximately 1 year).
Calculates the percentage of new 52-week lows relative to 40 stocks.
Displays threshold lines to highlight levels of market panic.
📈 Threshold Levels:
Threshold Line Color Level (%) Interpretation Action
30% Threshold Orange 30% Early signs of stress Start monitoring opportunities
33% Threshold Yellow 33% Confirmed panic Consider gradual accumulation
50% Panic Zone Red 50% Extreme market panic Aggressive accumulation zone
📌 Important Notes:
Why not use the full 50 stocks?
Due to TradingView Pine Script's current technical limits, a script cannot request data for more than 40 symbols efficiently.
Therefore, this indicator uses 40 representative SET50 stocks to ensure optimal performance without exceeding system limits.
The selected stocks are diversified across major sectors to maintain reliability.
🔥 Key Insights:
Historically, spikes above 30%-50% of stocks making new lows have coincided with major market bottoms (e.g., 2011, 2020).
Higher simultaneous new lows = stronger potential for long-term recovery.
EMA Trend Trading Strategy - FullTrend Identification:
Uptrend when price > EMA150 on H4
Downtrend when price < EMA150 on H4
Entry Conditions:
For BUY: EMA36 > EMA54/89/150 + price tests an EMA + bullish candlestick pattern
For SELL: EMA36 < EMA54/89/150 + price tests an EMA + bearish candlestick pattern
Exit Conditions:
Close position when price crosses EMA150 on M15
Volume spike detection (colored purple)
Risk Management:
Stop loss at 1.5x ATR
Take profit at 3x ATR (risk-reward 1:2)
Visual Indicators:
EMAs plotted with different colors
Buy/sell signals marked with triangles
Trend direction indicator
Win rate display
Mongoose Capital Trailing Entry ProMongoose Capital | Trailing Entry Pro
Built for professional traders and macro desks. This system dynamically trails price using ATR (Average True Range) logic, enabling disciplined breakout entries without chasing price.
Key features:
• ATR-Based Dynamic Trail — adapts to volatility in real-time.
• Entry Buffer — configurable distance to minimize false triggers.
• TPO POC Anchoring — optional filter to only allow entries if price is aligned with session auction bias.
• Visual Trail Lines — Green (Long trail) and Red (Short trail).
• Real Trade Entry Markers — Plots BUY/SELL labels for trade visualization.
Best combined with Mongoose Capital’s auction theory frameworks (TPO Profile) for superior edge in volatile environments.
Recommended Use:
- Macro trend following
- Tactical breakout trading
- Liquidity hunt defense
This script is free and open-source. Built to institutional standards by Mongoose Capital.
Gold/Silver RatioOverview
This indicator displays the Gold/Silver Ratio by dividing the price of gold (XAUUSD) by the price of silver (XAGUSD) on the same timeframe. It is a widely used tool in macroeconomic and precious metals analysis, helping traders and investors evaluate the relative value of gold compared to silver.
📈 What it does
Plots the ratio between gold and silver prices as a line on the chart.
Displays two key horizontal levels:
Overbought level at 90 (dashed red line).
Oversold level at 70 (dashed green line).
Highlights the chart background to show extreme conditions:
Red shading when the ratio exceeds 90 (gold is likely overvalued relative to silver).
Green shading when the ratio drops below 70 (silver is likely overvalued relative to gold).
🧠 How to Use
When the ratio exceeds 90, it suggests that gold may be overbought or silver may be undervalued. Historically, these have been good times to consider shifting exposure from gold to silver.
When the ratio falls below 70, it may indicate silver is overbought or gold is undervalued.
This tool is best used in conjunction with technical analysis, macroeconomic trends, or RSI/Bollinger Bands applied to the ratio.
⚙️ Inputs
This version of the script uses OANDA's XAUUSD and XAGUSD pairs for spot gold and silver prices. You may edit the request.security() calls to change data sources (e.g., FXCM, FOREXCOM, or CFD tickers from your broker).
✅ Best For:
Macro traders
Commodity investors
Ratio and spread traders
Long-term portfolio reallocators
Coinbase BTC Premium by BIGTAKERBTC Premium Gap Analysis: Binance, Coinbase, Upbit
This indicator provides real-time analysis and visualization of the premium gap between the Binance BTCUSDT price and the BTC prices on Coinbase (BTCUSD) and Upbit (BTCKRW).
Key Features
Coinbase Premium Gap
Measures the price difference between Coinbase and Binance as a percentage.
To improve visibility, the Coinbase premium is visually amplified by 10x.
Upbit Premium Gap
Calculates the premium by comparing Upbit's BTCKRW price (converted into USD using the real-time USDKRW exchange rate) against Binance BTCUSDT.
Dynamic Color Coding
Premiums above 0% are displayed in lime green, indicating positive premiums.
Premiums below 0% are displayed in red, indicating discounts.
Real-Time Labels
Displays real-time premium values for both Coinbase and Upbit on the right side of the chart.
Additional Notes
Upbit premiums are adjusted for the USD/KRW exchange rate to ensure accurate USD-based comparison.
The Coinbase premium is magnified visually (10x) to better capture minor movements, while the actual premium value remains correctly displayed.
The indicator is optimized for traders who monitor global BTC market price disparities across major exchanges.
How to Use
Quickly track global BTC price discrepancies across Binance, Coinbase, and Upbit.
Detect "Kimchi Premium" conditions in the Korean market through Upbit premiums.
Analyze buying and selling pressure in North American markets through Coinbase premiums.
Global M2 [BizFing]MARKETSCOM:BITCOIN ECONOMICS:USM2
This is an indicator designed to show the correlation between the global M2 money supply and Bitcoin.
This indicator basically provides a Global M2 index by summing the M2 money supply data from the United States, South Korea, China, Japan, the EU, and the United Kingdom.
Furthermore, it is configured to allow you to add or remove the M2 data of desired countries within the settings.
I hope this proves to be a small aid in predicting the future price of Bitcoin.
If you have any questions or require any improvements while using it, please feel free to contact me.
Thank you.
TUF_LOGICTUF_LOGIC: Three-Value Logic for Pine Script v6
The TUF_LOGIC library implements a robust three-valued logic system (trilean logic) for Pine Script v6, providing a formal framework for reasoning about uncertain or incomplete information in financial markets. By extending beyond binary True/False states to include an explicit "Uncertain" state, this library enables more nuanced algorithmic decision-making, particularly valuable in environments characterized by imperfect information.
Core Architecture
TUF_LOGIC offers two complementary interfaces for working with trilean values:
Enum-Based API (Recommended): Leverages Pine Script v6's enum capabilities with Trilean.True , Trilean.Uncertain , and Trilean.False for improved type safety and performance.
Integer-Based API (Legacy Support): Maintains compatibility with existing code using integer values 1 (True), 0 (Uncertain), and -1 (False).
Fundamental Operations
The library provides type conversion methods for seamless interaction between integer representation and enum types ( to_trilean() , to_int() ), along with validation functions to maintain trilean invariants.
Logical Operators
TUF_LOGIC extends traditional boolean operators to the trilean domain with NOT , AND , OR , XOR , and EQUALITY functions that properly handle the Uncertain state according to the principles of three-valued logic.
The library implements three different implication operators providing flexibility for different logical requirements: IMP_K (Kleene's approach), IMP_L (Łukasiewicz's approach), and IMP_RM3 (Relevant implication under RM3 logic).
Inspired by Tarski-Łukasiewicz's modal logic formulations, TUF_LOGIC includes modal operators: MA (Modal Assertion) evaluates whether a state is possibly true; LA (Logical Assertion) determines if a state is necessarily true; and IA (Indeterminacy Assertion) identifies explicitly uncertain states.
The UNANIMOUS operator evaluates trilean values for complete agreement, returning the consensus value if one exists or Uncertain otherwise. This function is available for both pairs of values and arrays of trilean values.
Practical Applications
TUF_LOGIC excels in financial market scenarios where decision-making must account for uncertainty. It enables technical indicator consensus by combining signals with different confidence levels, supports multi-timeframe analysis by reconciling potentially contradictory signals, enhances risk management by explicitly modeling uncertainty, and handles partial information systems where some data sources may be unreliable.
By providing a mathematically sound framework for reasoning about uncertainty, TUF_LOGIC elevates trading system design beyond simplistic binary logic, allowing for more sophisticated decision-making that better reflects real-world market complexity.
Library "TUF_LOGIC"
Three-Value Logic (TUF: True, Uncertain, False) implementation for Pine Script.
This library provides a comprehensive set of logical operations supporting trilean logic systems,
including Kleene, Łukasiewicz, and RM3 implications. Compatible with Pine v6 enums.
method validate(self)
Ensures a valid trilean integer value by clamping to the appropriate range .
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The integer value to validate.
Returns: An integer value guaranteed to be within the valid trilean range.
method to_trilean(self)
Converts an integer value to a Trilean enum value.
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The integer to convert (typically -1, 0, or 1).
Returns: A Trilean enum value: True (1), Uncertain (0), or False (-1).
method to_int(self)
Converts a Trilean enum value to its corresponding integer representation.
Namespace types: series Trilean
Parameters:
self (series Trilean) : The Trilean enum value to convert.
Returns: Integer value: 1 (True), 0 (Uncertain), or -1 (False).
method NOT(self)
Negates a trilean integer value (NOT operation).
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The integer value to negate.
Returns: Negated integer value: 1 -> -1, 0 -> 0, -1 -> 1.
method NOT(self)
Negates a Trilean enum value (NOT operation).
Namespace types: series Trilean
Parameters:
self (series Trilean) : The Trilean enum value to negate.
Returns: Negated Trilean: True -> False, Uncertain -> Uncertain, False -> True.
method AND(self, comparator)
Logical AND operation for trilean integer values.
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The first integer value.
comparator (int) : The second integer value to compare with.
Returns: Integer result of the AND operation (minimum value).
method AND(self, comparator)
Logical AND operation for Trilean enum values following three-valued logic.
Namespace types: series Trilean
Parameters:
self (series Trilean) : The first Trilean enum value.
comparator (series Trilean) : The second Trilean enum value to compare with.
Returns: Trilean result of the AND operation.
method OR(self, comparator)
Logical OR operation for trilean integer values.
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The first integer value.
comparator (int) : The second integer value to compare with.
Returns: Integer result of the OR operation (maximum value).
method OR(self, comparator)
Logical OR operation for Trilean enum values following three-valued logic.
Namespace types: series Trilean
Parameters:
self (series Trilean) : The first Trilean enum value.
comparator (series Trilean) : The second Trilean enum value to compare with.
Returns: Trilean result of the OR operation.
method EQUALITY(self, comparator)
Logical EQUALITY operation for trilean integer values.
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The first integer value.
comparator (int) : The second integer value to compare with.
Returns: Integer representation (1/-1) indicating if values are equal.
method EQUALITY(self, comparator)
Logical EQUALITY operation for Trilean enum values.
Namespace types: series Trilean
Parameters:
self (series Trilean) : The first Trilean enum value.
comparator (series Trilean) : The second Trilean enum value to compare with.
Returns: Trilean.True if both values are equal, Trilean.False otherwise.
method XOR(self, comparator)
Logical XOR (Exclusive OR) operation for trilean integer values.
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The first integer value.
comparator (int) : The second integer value to compare with.
Returns: Integer result of the XOR operation.
method XOR(self, comparator)
Logical XOR (Exclusive OR) operation for Trilean enum values.
Namespace types: series Trilean
Parameters:
self (series Trilean) : The first Trilean enum value.
comparator (series Trilean) : The second Trilean enum value to compare with.
Returns: Trilean result of the XOR operation.
method IMP_K(self, comparator)
Material implication using Kleene's logic for trilean integer values.
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The antecedent integer value.
comparator (int) : The consequent integer value.
Returns: Integer result of Kleene's implication operation.
method IMP_K(self, comparator)
Material implication using Kleene's logic for Trilean enum values.
Namespace types: series Trilean
Parameters:
self (series Trilean) : The antecedent Trilean enum value.
comparator (series Trilean) : The consequent Trilean enum value.
Returns: Trilean result of Kleene's implication operation.
method IMP_L(self, comparator)
Logical implication using Łukasiewicz's logic for trilean integer values.
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The antecedent integer value.
comparator (int) : The consequent integer value.
Returns: Integer result of Łukasiewicz's implication operation.
method IMP_L(self, comparator)
Logical implication using Łukasiewicz's logic for Trilean enum values.
Namespace types: series Trilean
Parameters:
self (series Trilean) : The antecedent Trilean enum value.
comparator (series Trilean) : The consequent Trilean enum value.
Returns: Trilean result of Łukasiewicz's implication operation.
method IMP_RM3(self, comparator)
Logical implication using RM3 logic for trilean integer values.
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The antecedent integer value.
comparator (int) : The consequent integer value.
Returns: Integer result of the RM3 implication operation.
method IMP_RM3(self, comparator)
Logical implication using RM3 logic for Trilean enum values.
Namespace types: series Trilean
Parameters:
self (series Trilean) : The antecedent Trilean enum value.
comparator (series Trilean) : The consequent Trilean enum value.
Returns: Trilean result of the RM3 implication operation.
method MA(self)
Modal Assertion (MA) operation for trilean integer values.
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The integer value to evaluate.
Returns: 1 if the value is 1 or 0, -1 if the value is -1.
method MA(self)
Modal Assertion (MA) operation for Trilean enum values.
Namespace types: series Trilean
Parameters:
self (series Trilean) : The Trilean enum value to evaluate.
Returns: Trilean.True if value is True or Uncertain, Trilean.False if value is False.
method LA(self)
Logical Assertion (LA) operation for trilean integer values.
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The integer value to evaluate.
Returns: 1 if the value is 1, -1 otherwise.
method LA(self)
Logical Assertion (LA) operation for Trilean enum values.
Namespace types: series Trilean
Parameters:
self (series Trilean) : The Trilean enum value to evaluate.
Returns: Trilean.True if value is True, Trilean.False otherwise.
method IA(self)
Indeterminacy Assertion (IA) operation for trilean integer values.
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The integer value to evaluate.
Returns: 1 if the value is 0, -1 otherwise.
method IA(self)
Indeterminacy Assertion (IA) operation for Trilean enum values.
Namespace types: series Trilean
Parameters:
self (series Trilean) : The Trilean enum value to evaluate.
Returns: Trilean.True if value is Uncertain, Trilean.False otherwise.
method UNANIMOUS(self, comparator)
Evaluates the unanimity between two trilean integer values.
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The first integer value.
comparator (int) : The second integer value.
Returns: Integer value of self if both values are equal, 0 (Uncertain) otherwise.
method UNANIMOUS(self, comparator)
Evaluates the unanimity between two Trilean enum values.
Namespace types: series Trilean
Parameters:
self (series Trilean) : The first Trilean enum value.
comparator (series Trilean) : The second Trilean enum value.
Returns: Value of self if both values are equal, Trilean.Uncertain otherwise.
method UNANIMOUS(self)
Evaluates the unanimity among an array of trilean integer values.
Namespace types: array
Parameters:
self (array) : The array of integer values.
Returns: First value if all values are identical, 0 (Uncertain) otherwise.
method UNANIMOUS(self)
Evaluates the unanimity among an array of Trilean enum values.
Namespace types: array
Parameters:
self (array) : The array of Trilean enum values.
Returns: First value if all values are identical, Trilean.Uncertain otherwise.
RSI + MACD + Liquidity FinderLiquidity Finder: The liquidity zones are heuristic and based on volume and swing points. You may need to tweak the volumeThreshold and lookback to match the asset's volatility and timeframe.
Timeframe: This script works on any timeframe, but signals may vary in reliability (e.g., higher timeframes like 4H or 1D may reduce noise).
Customization: You can modify signal conditions (e.g., require only RSI or MACD) or add filters like trend direction using moving averages.
Backtesting: Use TradingView's strategy tester to evaluate performance by converting the indicator to a strategy (replace plotshape with strategy.entry/strategy.close).
Accurate Global M2 (Top10 GDP, FX-Stabilized)This script was created to solve the serious distortions found in other circulating "Global M2" indicators.
Many previous versions used noisy daily FX rates, unweighted country data, mixed liquidity categories (e.g., RRP, TGA), or aggregated low-quality sources, causing exaggerated or misleading charts.
This version fixes those problems by:
Using Top 10 global economies only (based on GDP).
GDP-weighting each country's M2 contribution.
Fetching monthly-averaged M2 data.
Applying monthly FX conversions to eliminate daily volatility noise.
Forward-shifting the M2 line (default 90 days) to study potential Bitcoin correlations.
Keeping the math clean, without mixing central bank liquidity tools with broad M2 aggregates.
As a result, this script provides a more realistic and stable representation of global M2 expansion in USD terms, more suitable for serious macroeconomic analysis and Bitcoin market correlation studies.
Sharpe Ratio Forced Selling StrategyThis study introduces the “Sharpe Ratio Forced Selling Strategy”, a quantitative trading model that dynamically manages positions based on the rolling Sharpe Ratio of an asset’s excess returns relative to the risk-free rate. The Sharpe Ratio, first introduced by Sharpe (1966), remains a cornerstone in risk-adjusted performance measurement, capturing the trade-off between return and volatility. In this strategy, entries are triggered when the Sharpe Ratio falls below a specified low threshold (indicating excessive pessimism), and exits occur either when the Sharpe Ratio surpasses a high threshold (indicating optimism or mean reversion) or when a maximum holding period is reached.
The underlying economic intuition stems from institutional behavior. Institutional investors, such as pension funds and mutual funds, are often subject to risk management mandates and performance benchmarking, requiring them to reduce exposure to assets that exhibit deteriorating risk-adjusted returns over rolling periods (Greenwood and Scharfstein, 2013). When risk-adjusted performance improves, institutions may rebalance or liquidate positions to meet regulatory requirements or internal mandates, a behavior that can be proxied effectively through a rising Sharpe Ratio.
By systematically monitoring the Sharpe Ratio, the strategy anticipates when “forced selling” pressure is likely to abate, allowing for opportunistic entries into assets priced below fundamental value. Exits are equally mechanized, either triggered by Sharpe Ratio improvements or by a strict time-based constraint, acknowledging that institutional rebalancing and window-dressing activities are often time-bound (Coval and Stafford, 2007).
The Sharpe Ratio is particularly suitable for this framework due to its ability to standardize excess returns per unit of risk, ensuring comparability across timeframes and asset classes (Sharpe, 1994). Furthermore, adjusting returns by a dynamically updating short-term risk-free rate (e.g., US 3-Month T-Bills from FRED) ensures that macroeconomic conditions, such as shifting interest rates, are accurately incorporated into the risk assessment.
While the Sharpe Ratio is an efficient and widely recognized measure, the strategy could be enhanced by incorporating alternative or complementary risk metrics:
• Sortino Ratio: Unlike the Sharpe Ratio, the Sortino Ratio penalizes only downside volatility (Sortino and van der Meer, 1991). This would refine entries and exits to distinguish between “good” and “bad” volatility.
• Maximum Drawdown Constraints: Integrating a moving window maximum drawdown filter could prevent entries during persistent downtrends not captured by volatility alone.
• Conditional Value at Risk (CVaR): A measure of expected shortfall beyond the Value at Risk, CVaR could further constrain entry conditions by accounting for tail risk in extreme environments (Rockafellar and Uryasev, 2000).
• Dynamic Thresholds: Instead of static Sharpe thresholds, one could implement dynamic bands based on the historical distribution of the Sharpe Ratio, adjusting for volatility clustering effects (Cont, 2001).
Each of these risk parameters could be incorporated into the current script as additional input controls, further tailoring the model to different market regimes or investor risk appetites.
References
• Cont, R. (2001) ‘Empirical properties of asset returns: stylized facts and statistical issues’, Quantitative Finance, 1(2), pp. 223-236.
• Coval, J.D. and Stafford, E. (2007) ‘Asset Fire Sales (and Purchases) in Equity Markets’, Journal of Financial Economics, 86(2), pp. 479-512.
• Greenwood, R. and Scharfstein, D. (2013) ‘The Growth of Finance’, Journal of Economic Perspectives, 27(2), pp. 3-28.
• Rockafellar, R.T. and Uryasev, S. (2000) ‘Optimization of Conditional Value-at-Risk’, Journal of Risk, 2(3), pp. 21-41.
• Sharpe, W.F. (1966) ‘Mutual Fund Performance’, Journal of Business, 39(1), pp. 119-138.
• Sharpe, W.F. (1994) ‘The Sharpe Ratio’, Journal of Portfolio Management, 21(1), pp. 49-58.
• Sortino, F.A. and van der Meer, R. (1991) ‘Downside Risk’, Journal of Portfolio Management, 17(4), pp. 27-31.
Sharpe & Sortino Ratio PROSharpe & Sortino Ratio PRO offers an advanced and more precise way to calculate and visualize the Sharpe and Sortino Ratios for financial assets on TradingView. Its main goal is to provide a scientifically accurate method for assessing the risk-adjusted performance of assets, both in the short and long term. Unlike TradingView’s built-in metrics, this script correctly handles periodic returns, uses optional logarithmic returns, properly annualizes both returns and volatility, and adjusts for the risk-free rate — all critical factors for truly meaningful Sharpe and Sortino calculations.
Users can customize the rolling analysis window (e.g., 252 periods for one year on daily data) and the long-term smoothing period (e.g., 1260 periods for five years). There’s also an option to select between linear and logarithmic returns and to manually input a risk-free rate if real-time data from FRED (the 3-Month T-Bill Rate via FRED:DGS3MO) is unavailable. Based on the chart’s timeframe (daily, weekly, or monthly), the script automatically adjusts the risk-free rate to a per-period basis.
The Sharpe Ratio is calculated by first determining the asset’s excess returns (returns after subtracting the risk-free return per period), then computing the average and standard deviation of those excess returns over the specified window, and finally annualizing these figures separately — in line with best scientific practices (Sharpe, 1994). The Sortino Ratio follows a similar approach but only considers negative returns, focusing specifically on downside risk (Sortino & Van der Meer, 1991).
To enhance readability, the script visualizes the ratios using a color gradient: strong negative values are shown in red, neutral values in yellow, and strong positive values in green. Additionally, the long-term averages for both Sharpe and Sortino are plotted with steady colors (teal and orange, respectively), making it easier to spot enduring performance trends.
Why calculating Sharpe and Sortino Ratios manually on TradingView is necessary?
While TradingView provides basic Sharpe and Sortino Ratios, they come with significant methodological flaws that can lead to misleading conclusions about an asset’s true risk-adjusted performance.
First, TradingView often computes volatility based on the standard deviation of price levels rather than returns (TradingView, 2023). This method is problematic because it causes the volatility measure to be directly dependent on the asset’s absolute price. For instance, a stock priced at $1,000 will naturally show larger absolute daily price moves than a $10 stock, even if their percentage changes are similar. This artificially inflates the measured standard deviation and, as a result, depresses the calculated Sharpe Ratio.
Second, TradingView frequently neglects to adjust for the risk-free rate. By treating all returns as risky returns, the computed Sharpe Ratio may significantly underestimate risk-adjusted performance, especially when interest rates are high (Sharpe, 1994).
Third, and perhaps most critically, TradingView doesn’t properly annualize the mean excess return and the standard deviation separately. In correct financial math, the mean excess return should be multiplied by the number of periods per year, while the standard deviation should be multiplied by the square root of the number of periods per year (Cont, 2001; Fabozzi et al., 2007). Incorrect annualization skews the Sharpe and Sortino Ratios and can lead to under- or overestimating investment risk.
These flaws lead to three major issues:
• Overstated volatility for high-priced assets.
• Incorrect scaling between returns and risk.
• Sharpe Ratios that are systematically biased downward, especially in high-price or high-interest environments.
How to properly calculate Sharpe and Sortino Ratios in Pine Script?
To get accurate results, the Sharpe and Sortino Ratios must be calculated using the correct methodology:
1. Use returns, not price levels, to calculate volatility. Ideally, use logarithmic returns for better mathematical properties like time additivity (Cont, 2001).
2. Adjust returns by subtracting the risk-free rate on a per-period basis to obtain true excess returns.
3. Annualize separately:
• Multiply the mean excess return by the number of periods per year (e.g., 252 for daily data).
• Multiply the standard deviation by the square root of the number of periods per year.
4. Finally, divide the annualized mean excess return by the annualized standard deviation to calculate the Sharpe Ratio.
The Sortino Ratio follows the same structure but uses downside deviations instead of standard deviations.
By following this scientifically sound method, you ensure that your Sharpe and Sortino Ratios truly reflect the asset’s real-world risk and return characteristics.
References
• Cont, R. (2001). Empirical properties of asset returns: stylized facts and statistical issues. Quantitative Finance, 1(2), pp. 223–236.
• Fabozzi, F.J., Gupta, F. and Markowitz, H.M. (2007). The Legacy of Modern Portfolio Theory. Journal of Investing, 16(3), pp. 7–22.
• Sharpe, W.F. (1994). The Sharpe Ratio. Journal of Portfolio Management, 21(1), pp. 49–58.
• Sortino, F.A. and Van der Meer, R. (1991). Downside Risk: Capturing What’s at Stake in Investment Situations. Journal of Portfolio Management, 17(4), pp. 27–31.
• TradingView (2023). Help Center - Understanding Sharpe and Sortino Ratios. Available at: www.tradingview.com (Accessed: 25 April 2025).
Quarterly Fundamentals Table by GauravThis Pine Script v3 overlay paints a compact, six‐column table in the top‐right of your chart that begins with your stock’s market capitalization and sector/industry, then lays out quarterly fundamentals—Sales, Sales QoQ%, PAT, PAT QoQ% and OPM%—across the most recent four fiscal quarters (dynamically labeled by month and year). It pulls data via request.financial(), formats large numbers into lakhs/crores, calculates quarter‐over‐quarter growth, and sizes text for clarity, giving swing traders an at‐a‐glance view of key fundamental trends alongside price action.
Heila's Advanced Buy/Sell Signal (Upgraded) - 100MA TouchI made it for myself, and it wouldn't be easy to lose if you just follow the signals.. but it's rather hard to see them.
AE - Aggregated Open InterestAggregated Open Interest
The Aggregated Open Interest indicator provides a comprehensive view of open interest across multiple cryptocurrency exchanges, allowing traders to monitor institutional positioning and market sentiment. By aggregating data from major exchanges like Binance, BitMEX, and Kraken, this indicator offers valuable insights into potential price movements and market shifts.
🔶 CALCULATION
The indicator processes open interest data through multiple analytical methods:
Exchange Aggregation: Collects and normalizes open interest data from multiple exchanges (Binance, BitMEX, Kraken) with proper currency normalization.
Multi-Mode Analysis: Calculates various metrics including raw open interest values, OI change, OI delta, volume-weighted delta, and OI RSI.
Divergence Detection: Uses pivot point analysis to identify divergences between price action and open interest movements.
Activity Assessment: Tracks bullish and bearish activity patterns by correlating open interest changes with price movements.
Formula:
- Aggregate OI = Sum of normalized open interest from selected exchanges
- OI Change = Current OI - Previous OI
- OI Delta = Net change in open interest across timeframes
- OI Delta × Volume = OI Delta weighted by relative volume
- OI RSI = Relative Strength Index applied to open interest values
- OI Heatmap = Multi-timeframe visualization of OI changes across 7 distinct periods
🔶 DETAILS
Visual Features:
Multiple Display Modes:
- Open Interest: Candlestick representation of aggregated open interest
- OI Change: Histogram showing period-to-period changes
- OI Delta: Histogram displaying net OI movements
- OI Delta × Volume: Volume-weighted OI delta for enhanced signals
- OI RSI: Oscillator showing overbought/oversold OI conditions
- OI Heatmap: Multi-timeframe visualization showing OI changes across 7 periods (3, 5, 8, 13,
21, 34, and 55 days)
- Divergence Detection: Color-coded markers (teal for bullish, red for bearish) highlighting - -
significant divergences between price and open interest
- Analysis Table: Real-time summary of key metrics including aggregate OI, recent changes, and
bullish/bearish activity
🔶 Interpretation:
Increasing Open Interest + Rising Price: Strong bullish trend confirmation
Increasing Open Interest + Falling Price: Strong bearish trend confirmation
Decreasing Open Interest + Rising Price: Weak bullish trend (potential reversal)
Decreasing Open Interest + Falling Price: Weak bearish trend (potential reversal)
Divergences: Signal potential trend exhaustion and reversals when price moves in one direction while open interest moves in the opposite direction
Heatmap: Provides at-a-glance insight into open interest trends across multiple timeframes, with green bars indicating rising OI and red bars indicating falling OI
🔶 EXAMPLES
Trend Confirmation: Rising open interest accompanying a price increase confirms strong bullish momentum with institutional backing.
- Example: During January-February 2025, rising OI during price advances confirms institutional
participation in the uptrend.
- Bearish Divergence: Price makes a higher high while open interest makes a lower high,
signaling potential trend reversal.
- Example: Red markers appear at market tops where price continues higher but open interest
fails to confirm, preceding significant corrections.
- Bullish Divergence: Price makes a lower low while open interest makes a higher low,
indicating potential bottoming.
- Example: Teal markers appear at market bottoms where price continues lower but open
interest fails to confirm, preceding significant rallies.
OI Heatmap Analysis: Multiple timeframes showing consistent red signals across short to long-term periods indicate strong institutional selling pressure.
Example: When all 7 periods (3-55 days) show red during a price uptrend, this signals institutional selling into retail strength, often preceding major corrections.
🔶 SETTINGS
Customization Options:
Data Sources: Toggle different exchanges (Binance USDT/USD/BUSD, BitMEX USD/USDT, Kraken USD)
Display Mode: Choose between Open Interest, OI Change, OI Delta, OI Delta × Volume, OI RSI, and OI Heatmap
Currency Units: Display in USD or base cryptocurrency (COIN)
Analysis Tools: Moving Average (length and color), RSI (length and color)
Divergence Detection: Enable/disable signals, adjust lookback period and threshold percentage, customize bullish/bearish divergence colors
OI Heatmap Colors: Customize bullish (green) and bearish (red) signal colors for the multi-timeframe heatmap visualization
The Aggregated Open Interest indicator provides traders with comprehensive insights into institutional positioning across major exchanges, helping identify potential trend continuations, reversals, and key market turning points driven by smart money movements. The addition of the OI Heatmap feature enables traders to quickly visualize open interest trends across multiple timeframes, providing valuable context for institutional positioning over different market cycles.
cktraderpro session high lowCK Session Tracker – Global Market Session Levels
The CK Session Tracker is a precision-built TradingView indicator designed to map out the most critical times in the market — the Asia, EU, and US sessions. This tool automatically plots the open, close, high, and low of each major session, giving traders a crystal-clear view of market structure, key liquidity zones, and session-based momentum shifts.
🔍 Features:
🕒 Automatic Session Markers – Visualize the exact open and close times of Asia, Europe, and US sessions directly on your chart.
📈 Session Highs & Lows – Instantly spot where price reacted during each session, helping identify breakouts, reversals, or liquidity grabs.
🌐 Global Market Awareness – Designed to adapt to futures, forex, and crypto across all time zones.
🎯 Smart Trading Zones – Use session data to pinpoint high-probability setups during overlaps or session handoffs.
Perfect for intraday traders, ICT strategy followers, and anyone focused on session-based movement. The CK Session Tracker gives you the edge of institutional timing — all on one chart.
MTF Trend vs Choppy Market + VolatilityIt shows trading and non trading zones. When it shows background green then it is trading zone and when it is red then non trending zone
Global Liquidity Index with Dynamic TimeframeThis is the M2 Global Money supply indicator with added functionality of moving the graph sideways (increment of days) in order to find a potential price correlation with any chart
BTC / USEU (FX-Adjusted)first version btc/k adjustable
filters out usd movments to see raw btc changes