(SM3) Volume Profile Tool-kit1st pine script. It is a work in progress. I use this to mark previous day high and low value areas as well as overnight volume profile for NYSE open strategy.
Indicators and strategies
NQ Points of Interest Suite (Fixed)Defines pre level of support and resistance
Daily MID LOW OPEN CLOSE
WEEKLY MID LOW OPEN CLOSE
MONTHLY MID LOW OPEN CLOSE
Bar Number IndicatorBar Number Indicator
This Pine Script indicator is designed to help intraday traders by automatically numbering candlesticks within a user-defined trading session. This is particularly useful for strategies that rely on specific bar counts (e.g., tracking the 1st, 18th, or 81st bar of the day).
Key Features:
Session-Based Counting: Automatically resets the count at the start of each new session (default 09:30 - 16:00).
Timezone Flexibility: Includes a dropdown to select your specific trading timezone (e.g., America/New_York), ensuring accurate session start times regardless of your local time or the exchange's default setting.
Smart Display Modes: Choose to show "All" numbers, or filter for "Odd" / "Even" numbers to keep your chart clean.
Custom Positioning: Easily place the numbers Above or Below the candlesticks.
Minimalist Design: Numbers are displayed as floating text without distracting background bubbles.
Volatility Value BandsThis indicator is a modern adaptation of Mark Helweg's original Value Charts concept, focused on visually displaying volatility zones and "extreme value" areas directly on the price chart. It does not replicate the original work but draws inspiration from the logic of normalizing price by volatility to highlight statistically stretched regions.
1. Introduction
This study displays three lines directly on the chart:
- a central reference line (base),
- an upper overvaluation band,
- and a lower undervaluation band.
The bands are calculated from the relationship between price, moving average, and volatility (via true range/ATR), following Mark Helweg's Value Charts concept but with a custom implementation and adjustable parameters for different assets and timeframes. This allows objectively visualizing when price is in a statistically extended region relative to its recent behavior.
2. Key Features
- Volatility-normalized base
The indicator converts price deviation into "value units" using a combination of moving average and smoothed volatility (true range/ATR), making levels comparable across different assets and time horizons.
- Auto-adjusting limits (optional)
An automatic mode can calculate upper and lower limits from recent value unit extremes, using a configurable sampling window and percentile, allowing bands to adapt to the current volatility regime without manual recalibration.
- Direct plot on price chart
The three lines (central, upper, and lower) are drawn directly on the main asset chart (`overlay`), making it easy to read context: it's clear when price "touches" or breaks the volatility bands without switching to a separate pane.
- Flexible parameters
Users can control:
- base moving average period (length)
- volatility factor (manual or automatic)
- independent windows for volatility and limits calculation
- limits mode (auto or manual) and percentile used
This allows adapting behavior to different markets (stocks, indices, forex, crypto).
3. How to Use
- Basic interpretation
- When price approaches or exceeds the upper band, it indicates a statistically overvalued zone where the asset is stretched upward relative to recent volatility.
- When price approaches or exceeds the lower band, it indicates a statistically undervalued zone.
- The central line serves as a reference for recent "average value," derived from the base moving average.
- Recommended initial setup
- Choose the Value Chart period (e.g., 144 bars) for the base.
- Enable automatic limits mode for coherent bands matching the asset's volatility.
- Adjust the limits window and percentile for tighter bands (more signals) or wider bands (fewer but more extreme).
- Best practices
- Use bands as context filters, not standalone buy/sell signals. Combine with trend, market structure, or other confirmation indicators.
- Avoid decisions solely because price touched a band; in strong trends, price can "walk the edge" for extended periods.
- Always follow TradingView community rules when publishing: clearly state in the description that the study is "inspired by Mark Helweg's Value Charts concept," without claiming official status, reproducing proprietary code, or violating copyrights.
Rolling Skewness & Kurtosis (Quant Lab)🔹 Skewness (Asymmetric Risk)
• Skew > 0 (green) → Right tail heavier:
• More frequent positive extreme movements
• Higher probability of pump/sharp rally
• Skew < 0 (red) → Left tail heavier:
• Higher risk of crash, dump, liquidation
• Skew ≈ 0 → Distribution is symmetrical, neither right nor left side is dominant
🔹 Excess Kurtosis (Intensity of Extreme Movements)
• Kurt > 0 → Fat tails:
• More extreme movements compared to a normal distribution
• Increased risk of unexpected large spikes, flash moves
• Kurt < 0 → Thin tail:
• More “calm” distribution, fewer extreme movements
This pair tells you:
“Which direction could this instrument explode in right now?
and has the intensity of extreme movements increased?”
Variance Ratio & Efficiency Ratio (Quant Lab)1️⃣ Variance Ratio (VR)
Formula:
VR ≈ Var(q-step returns) / (q × Var(1-step returns))
Interpretation:
• VR ≈ 1 → The market is like a random walk; neither trend nor mean-reversion is dominant.
• VR > 1 → Trend behavior is dominant.
• Trend-following systems (EMA, Supertrend, breakout) work better.
• VR < 1 → Mean-reversion is dominant.
• Range/reversal strategies (Z-score, Bollinger fade, RSI reversal) work better.
In short:
• VR > 1 → Trending market
• VR < 1 → Mean-reverting market
This tells you:
“Should I build a trend system or a mean-reversion system for this instrument?”
⸻
2️⃣ Efficiency Ratio (ER)
Formula logic:
ER = |Close_now – Close_n-bars-ago| / Σ|Close_i – Close_{i+1}|
In other words:
• Numerator → Net movement over N bars
• Denominator → Total noise over N bars
Interpretation:
• ER ≈ 1 → The price has moved in almost a straight line in one direction.
→ The trend is very efficient, noise is low.
• ER ≈ 0 → The price has fluctuated a lot but hasn't gone anywhere definitively.
→ A complete noise/range market.
This tells you:
“How clear is the trend in this last N bars, and how much noise is there?”
⸻
🔥 The intelligence provided by both together:
• VR > 1 and ER is high (0.6–1.0) →
➜ Strong, high-quality trend. Golden age for trend-following.
• VR > 1 but ER is low (0.2–0.4) →
➜ Trend exists but there is a lot of noise, many fake movements. • VR < 1 and ER is low →
➜ Net range / sideways market. Ideal for mean-reversion.
DR/IDR fractals break candle (ChadAnt)This indicator is an Opening Range Breakout (ORB) tool. It identifies the high and low price range established during a specific time window (e.g., the first hour of trading, 9:30–10:30 AM NY time). Once that time window closes, it watches for the price to "break out" of that range and projects profit targets based on the size of the initial range.
Key Features & How They Work
1. The Opening Range (The Box)
Time Window: The indicator waits for your specific start time (default 9:30 AM NY). It does not draw anything before this time.
The "Wicks": It tracks the absolute highest and lowest prices reached during this time (the Wicks). These act as your Breakout Triggers.
The "Body": It tracks the highest and lowest candle closes/opens during this time. This creates a shaded "zone" on your chart, representing the core area where most trading occurred.
Shading: To keep your chart clean, the background shading only appears during the forming time window.
2. Breakout Signals
Once the time window ends (e.g., 10:30 AM), the indicator "locks" the levels.
It then waits for a candle to move above the Wick High or below the Wick Low.
The Signal: When this happens, a label ("BREAK") appears on the chart.
Green Label: Bullish breakout (price went above the range).
Red Label: Bearish breakout (price went below the range).
Note: It only signals the first breakout of the day to avoid false alarms during choppy markets.
3. Extension Targets (Profit Levels)
When a breakout signal occurs, the indicator automatically draws target lines (extensions).
Calculation: These targets are based on the height of the "Body" zone (the shaded area).
Example: If your setting is 1.0, the indicator measures the height of the shaded body range and projects that exact distance above the breakout point. This is often used as a "Measured Move" target.
You can customize how many lines appear and how far apart they are (e.g., 0.5, 1.0, 1.5 times the range size).
4. Williams Fractals
During the opening range time, the indicator looks for specific price patterns called "Williams Fractals" (a 5-candle pattern that highlights potential turning points).
If a fractal peak or valley occurs inside your opening range, it marks it with a small triangle (▲ or ▼). Traders often use these as early signs of support or resistance forming inside the range.
5. Clean Visuals
Line Cutoff: You can set a "Stop Time" (e.g., 16:00 or 4:00 PM). The lines will stop drawing at that time so they don't clutter your chart overnight.
Gap Handling: The lines are programmed to break cleanly between days, so you don't see messy diagonal lines connecting yesterday's close to today's open.
Summary of Settings You Can Change
Session Time: When the range starts and ends.
Line Stop Time: When the lines should disappear for the day.
Visuals: Colors, line width, and style (solid, dotted, dashed).
Extensions: How many target lines to draw and the step size (e.g., 0.5x, 1.0x).
Fractals: Toggle the triangle icons on/off.
ATR R-LevelsATR-R Levels is built for clarity of risk management.
The script takes your account size, chosen risk %, and the market’s volatility, then turns all of that into exact stop-loss, take-profit, and position size so there’s no guessing.
It’s inspired by key principles from NNFX, especially ATR-based stop placement and fixed-risk position sizing, but redesigned for fast intraday crypto trading. You get the same consistency and discipline NNFX is known for, adapted to a much shorter timeframe.
ATR-R Levels gives you:
A volatility-based stop using ATR
A clean 2R (or custom R-multiple) target
Automatic position sizing based on your risk rules
A simple HUD showing ATR, entry, stop, TP, size, and risk
Optional net profit estimates after fees
Let me know what you think or if you use it!
Quality Detector (Buffett Style) + Beta [Solid]This indicator acts as an on-chart fundamental screener, designed to instantly evaluate the quality and financial health of a company directly on your price chart.
The concept is inspired by "Buffettology" principles: looking for large, profitable companies with low debt. Additionally, it includes a Beta calculation to assess market volatility risk.
The tool displays a panel in the bottom-right corner featuring four key metrics and a final verdict.
How it Works & Metrics Used
The script retrieves quarterly fundamental data ("FQ") and performs calculations to verify if the asset meets specific criteria.
1. Market Cap (Size)
What it is: The total market value of the company's outstanding shares.
Goal: To identify established, large-cap companies.
Default Threshold: Must be greater than $10 Billion.
2. ROE - Return on Equity (Quality)
What it is: A measure of financial performance calculated by dividing net income by shareholders' equity.
Goal: To find companies that are efficient at generating profits from shareholders' capital.
Default Threshold: Must be higher than 15%.
3. Total Debt to Equity (Health)
What it is: A ratio indicating the relative proportion of shareholders' equity and debt used to finance a company's assets.
Calculation: This script manually calculates this ratio by fetching TOTAL_DEBT and dividing it by TOTAL_EQUITY from fundamental data to ensure robustness across different symbols.
Goal: To ensure the company is not overly leveraged.
Default Threshold: Must be lower than 1.5.
4. Beta (Risk/Volatility)
What it is: A measure of a stock's volatility in relation to the overall market (S&P 500).
Calculation: It is calculated by comparing the asset's returns against SPY (S&P 500 ETF) returns over a 252-day period (approx. 1 trading year).
Goal: To understand if the stock is more volatile (Beta > 1) or less volatile (Beta < 1) than the market.
Note: Beta does not affect the final "Quality" score but serves as an extra risk indicator, highlighting in orange if Beta > 1.
The Verdict (Scoring System)
The indicator assigns a score from 0 to 3 based on the first three fundamental metrics (Size, ROE, and Debt/Equity).
If a metric passes the threshold, it gets a green background and +1 point.
If it fails, it gets a red background.
Final Verdict:
💎 QUALITY GEM: The company passed all 3 fundamental checks (Score = 3/3).
⚠️ DISCARD: The company failed one or more fundamental checks.
Settings
You can customize the thresholds to fit your own investment strategy in the indicator settings:
Minimum Market Cap (in Billions).
Minimum ROE (%).
Maximum Debt/Equity Ratio.
Disclaimer: This tool is for informational and educational purposes only. It relies on third-party fundamental data which may sometimes be delayed or unavailable. Do not base investment decisions solely on this indicator.
ATR + True RangeOne indicator for ATR & TR its a common indictor which can be used as one
instead of 2 different its is trial mode only not to be used with out other references
TedAlpha – Structure / FVG / OB Sessions:
Only looks for trades when price is inside your defined London or NY time blocks.
CHOCH:
Uses pivots to track swing highs/lows, then flags a bullish CHOCH when structure flips from LL/LH to HH/HL, and vice versa for bearish.
FVG:
Detects 3-candle imbalance and keeps the zone “active” for fvgLookback bars, then checks if price trades back into it.
Order Blocks:
On a CHOCH, grabs the last opposite candle (bearish before bull CHOCH = bullish OB, bullish before bear CHOCH = bearish OB) and marks its body as the OB zone.
Signal:
A valid long = bull CHOCH + in session + (price inside bullish FVG and/or bullish OB, depending on toggles).
Short is the mirror image.
RR 1:3:
SL uses the last swing low (for longs) or last swing high (for shorts), TP is auto-set at 3× that distance and plotted as lines.
Directional Movement Index (SHADED)Shaded red in between DMI lines when DMI- > DMI+
Shaded blue in between DMI lines when DMI+ > DMI-
Friday-Monday Pattern Backtest (Market Rebellion)Tests the "Friday-Monday Pattern" popularized by Tom Hougaard / Market Rebellion.
PATTERN LOGIC:
• When Friday's high is LOWER than Thursday's high (setup condition)
• Then Friday's low is often revisited on the following Monday
WHAT THIS INDICATOR SHOWS:
• Orange background highlights valid setup bars (Thu-Fri-Mon)
• Red horizontal line marks Friday's low (the target level)
• Green "SUCCESS" label = Monday hit Friday's low
• Red "FAIL" label = Monday did not reach Friday's low
• Stats table (top-right) shows total setups, successes, and success rate
USE THIS TO:
• Backtest the pattern on any daily chart (works best on indices, forex, futures)
• Verify the claimed "overwhelming" tendency statistically
• Identify which markets/timeframes show the highest success rate
CREDITS:
Pattern idea from Tom Hougaard / Market Rebellion: x.com
Indicator by BacktestBay for transparent pattern verification.
USAGE NOTES:
• Must be applied to DAILY charts
• Uses time_close("D") for accurate day-of-week detection on forex pairs
• No trading signals - purely for statistical backtesting
RSI with Multi-Level OB/OS (65/70 & 35/30)With a revised 65 and 35 level for higher probability of winning
Volume Heikin Ashi by CrugThis indicator combines the Heikin Ashi with classic volume candles.
It is useful to see the trend and "how much" volume it contains
1 - Select Volume Candles on the graph
i.postimg.cc
2- In setting remove the all the colors
i.postimg.cc
3- Insert the indicator
4- Using with momentum indicators (like Market liberator B, MACD, ...) it provides more precise and realistic data to plot divergences because it combines: classic japanese candle but with volumes. In the meantime it is easier to see the main trend
i.postimg.cc
EMA Market Regime & Real-Time Candle Projection System📌 EMA Market Regime & Real-Time Candle Projection System
EMA Market Regime & Parabolic Projection is a real-time market structure system designed to anticipate candle behavior before it fully forms, by dynamically projecting price levels based on trend strength, acceleration, and market expansion.
Unlike traditional indicators that react after the candle closes, this system continuously adapts to live price data to provide early insight into bullish, bearish, parabolic, and exhaustion phases.
🔍 Core Concept
The system operates on four key dimensions:
Market Structure
Uses a fast and a slow EMA to determine the dominant market regime (bullish or bearish).
Directional Momentum
Measures EMA slope to confirm directional commitment.
Acceleration & Parabolic Detection
Identifies true parabolic movements through acceleration analysis, filtering out weak or range-bound price action.
Expansion Validation
Confirms that movements are supported by genuine market expansion, reducing false signals.
By combining these elements, the indicator projects a dynamic price level in real time, effectively drawing a forward-looking guide that adapts as each candle evolves.
🧠 Real-Time Candle Projection
The projected line represents a dynamic equilibrium level derived from EMA structure and acceleration.
This allows traders to:
Anticipate continuation vs exhaustion
Visualize momentum shifts before candle close
Read potential candle direction and strength in real time
The projection is non-repainting and updates tick-by-tick during the candle’s formation.
🎯 Market Regime Classification
The system automatically classifies the market into distinct states:
Bullish Trend – Positive structure with controlled momentum
Bearish Trend – Negative structure with controlled momentum
Parabolic Expansion – Accelerated trend with strong continuation potential
Parabolic Exhaustion – Loss of acceleration signaling potential reversal or pullback
Neutral / Range – Low momentum and low expansion (no-trade zone)
Each state is visually encoded using subtle, professional coloring, ensuring price candles always remain the primary focus.
🛡️ Professional-Grade Filters
Anti-range and anti-fake breakout filtering
Cooldown logic to prevent repetitive signals
Slope normalization relative to volatility
Designed to remain readable on M1–M5 scalping and higher timeframes
⚙️ Designed For
Scalping & Intraday Trading
Real-time decision-making
Trend continuation & exhaustion timing
Prop-firm and professional trading environments
This system is intended as a market structure and timing tool, not a signal spam indicator.
⚠️ Disclaimer
This indicator does not predict the future and does not provide guaranteed results. It is designed to assist discretionary traders by improving real-time market reading and execution timing.
Index ScalpingIndex Scalping Indicator will help to reduced the noise and provide clear call/put options. Use it in 5 min timeframe
Simple Gap IndicatorTitle: Simple Gap Indicator
Description: This is a utility script designed to automate the tracking and management of price gaps (also known as "Windows") on the chart. Unlike static drawings, this indicator dynamically monitors open gaps and automatically "closes" them (stops drawing) once price has filled the area, keeping your chart clean and focused on active levels only.
Why Use This Tool? Traders often mark gaps manually, but charts quickly become cluttered with old, invalid levels. This script solves that problem by using an array-based management system to track every open gap in real-time and remove it the moment it is invalidated by price action.
Technical Methodology:
Gap Detection: The script identifies "Full Gaps" where the Low of the current candle is higher than the High of the previous candle (Bullish), or vice versa (Bearish). This indicates a total disconnect in price delivery.
Dynamic Filtering:
ATR Filter: Users can filter out insignificant "noise" gaps by setting a minimum size threshold based on the Average True Range (ATR).
Time Filter: Option to restrict gap detection to specific session hours (e.g., ignoring overnight gaps on 24h charts).
Auto-Closure: The script loops through all active gaps on every new bar. If the current price wick touches an open gap, the box is visually terminated at that specific bar index and removed from the tracking array.
Visuals:
Green Box: Bullish Gap (Support Zone).
Red Box: Bearish Gap (Resistance Zone).
Labels: Optional text displaying the precise Top/Bottom price coordinates of the gap.
How to Use:
Enable "Auto-Close Gap on Retest" to keep your chart clean.
Use the ATR Filter if you are getting too many signals on lower timeframes (e.g., set to 0.5x ATR).
Set alerts for "New Gap" or "Gap Filled" to automate your workflow.
Credits: Calculations based on standard Gap/Window price action theory. Array management logic custom-coded for Pine Script v6.
NYSE Open Close Session Map by o0psiNYSE Open Close Session Map by o0psi
This indicator highlights the regular US cash session window (default 09:30–16:00 New York time) and makes the key session bars obvious on the chart.
What it shows
A marker on the session OPEN bar
A marker on the session CLOSE bar (last in-session candle)
Optional background highlight for the full session window
Optional labels for the session high and session low bars (based on intraday price during the session)
How it works
The script detects bars inside the selected session window (New York timezone). It anchors OPEN on the first in-session bar, updates the session high/low while the session is active, then anchors CLOSE on the final in-session bar and labels the high/low bars where they occurred.
Notes
Session range precision depends on chart timeframe (lower timeframes capture extremes more precisely).
This is a charting/visualization tool and does not provide trading advice.
Alertes Trading Manuel//@version=6
indicator("Signal simple +0.5% LONG", overlay = true)
// --- Paramètres ---
tpPctInput = input.float(0.5, "TP (%)", step = 0.1) // objectif pour toi : 0.5%
slPctInput = input.float(0.3, "SL (%)", step = 0.1) // SL indicatif : 0.3%
tpPct = tpPctInput / 100.0
slPct = slPctInput / 100.0
emaLenFast = input.int(50, "EMA rapide (intraday)", minval = 1)
emaLenSlow = input.int(200, "EMA lente (intraday)", minval = 1)
volLen = input.int(20, "Période moyenne Volume", minval = 1)
// --- Tendance daily : MA200 jours ---
ma200D = request.security(syminfo.tickerid, "D", ta.sma(close, 200))
above200D = close > ma200D
// --- Tendance intraday ---
emaFast = ta.ema(close, emaLenFast)
emaSlow = ta.ema(close, emaLenSlow)
upTrendIntraday = close > emaFast and emaFast > emaSlow
// --- MACD & RSI ---
= ta.macd(close, 12, 26, 9)
rsi = ta.rsi(close, 14)
macdOK = macdLine > macdSignal
rsiOK = rsi > 49 and rsi < 75
// --- Volume ---
volMa = ta.sma(volume, volLen)
volOK = volume > volume and volume > volMa
// --- Signal LONG simple ---
longSignal = above200D and upTrendIntraday and macdOK and rsiOK and volOK
// --- Affichage du signal ---
plotshape(
longSignal,
title = "Signal LONG",
location = location.belowbar,
style = shape.triangleup,
color = color.lime,
size = size.small,
text = "LONG"
)
// --- Lignes TP / SL indicatives basées sur le dernier signal ---
var float tpLine = na
var float slLine = na
if longSignal
tpLine := close * (1 + tpPct)
slLine := close * (1 - slPct)
// Les lignes restent jusqu'au prochain signal
plot(tpLine, "TP indicatif", color = color.new(color.green, 50), style = plot.style_linebr)
plot(slLine, "SL indicatif", color = color.new(color.red, 50), style = plot.style_linebr)
// --- Affichage des moyennes ---
plot(emaFast, "EMA rapide", color = color.new(color.blue, 40))
plot(emaSlow, "EMA lente", color = color.new(color.orange, 40))
plot(ma200D, "MA200 jours (daily)", color = color.new(color.fuchsia, 0), linewidth = 2)
Risk & Position CalculatorThis indicator is called "Risk & Position Calculator".
This indicator shows 4 information on a table format.
1st: 20 day ADR% (ADR%)
2nd: Low of the day price (LoD)
3rd: The percentage distance between the low of the day price and the current market price in real-time (LoD dist.%)
4th: The calculated amount of shares that are suggested to buy (Shares)
The ADR% and LoD is straightforward, and I will explain more on the 3rd and 4th information.
__________________________________________________________________________________
The Lod dist.% is a useful tool if you are a breakout buyer and use the low of the day price as your stop loss, it helps you determine if a breakout buy is at a risk tight area (~1/2 ADR%) or it is more of a chase (>1 ADR%).
I use four different colors to visualize this calculation results (green, yellow, purple, and red).
Green: Lod dist.% <= 0.5 ADR%
Yellow: 0.5 ADR% < Lod dist.% <= 1 ADR%
Purple: 1 ADR% < Lod dist.% <= 1.5 ADR%
Red: 1.5 ADR% < Lod dist.%
(e.g., if Lod dist.% is colored in Green, it means your stop loss is <= 0.5 ADR%, therefore if you buy here, the risk is probably tight enough)
__________________________________________________________________________________
The Shares is a useful tool if you want to know exactly how many shares you should buy at the breakout moment. To use this tool, you first need to input two information in the indicator setting panel: the account size ($) and portfolio risk (%).
Account Size ($) means the dollar value in your total account.
Portfolio Risk (%) means how much risk you are willing to take per trade.
(e.g. a 1% portfolio risk in a 5000$ account is 50$, which is the risk you will take per trade)
After you provide these two inputs, the indicator will help you calculate how many shares you should buy based on the calculated Dollar Risk ($), real-time market price, and the low of the day price.
(e.g. Dollar Risk (50$), real-time market price (100$), Lod price (95$) -> then you will need to buy 50/(100-95) = 10 shares to meet your demand, so it will display as Shares { 10 } )
In addition, I also introduce a mechanism that helps you avoid buying too big of a position relative to your overall account . I set the limit to 25%, which means you don't put more than 25% of your account money into a single trade, which helps prevent single stock risk.
By introducing this mechanism, it will supervise if the suggested Shares to buy exceed max position limit (25%). If it actually exceeds, instead of using Dollar Risk ($) to calculate Shares, it will use position limit to calculate and display the max Shares you should buy.
__________________________________________________________________________________
That's it. Hope you find this explanation helpful when you use this indicator. Have a great day mate:)
takeshi_2Step_Screener_MOU_KAKU_FIXED3//@version=5
indicator("MNO_2Step_Screener_MOU_KAKU_FIXED3", overlay=true, max_labels_count=500)
// =========================
// Inputs
// =========================
emaSLen = input.int(5, "EMA Short (5)")
emaMLen = input.int(13, "EMA Mid (13)")
emaLLen = input.int(26, "EMA Long (26)")
macdFast = input.int(12, "MACD Fast")
macdSlow = input.int(26, "MACD Slow")
macdSignal = input.int(9, "MACD Signal")
macdZeroTh = input.float(0.2, "MOU: MACD near-zero threshold", step=0.05)
volLookback = input.int(5, "Volume MA days", minval=1)
volMinRatio = input.float(1.3, "MOU: Volume ratio min", step=0.1)
volStrong = input.float(1.5, "Strong volume ratio (Breakout/KAKU)", step=0.1)
volMaxRatio = input.float(3.0, "Volume ratio max (filter)", step=0.1)
wickBodyMult = input.float(2.0, "Pinbar: lowerWick >= body*x", step=0.1)
pivotLen = input.int(20, "Resistance lookback", minval=5)
pullMinPct = input.float(5.0, "Pullback min (%)", step=0.1)
pullMaxPct = input.float(15.0, "Pullback max (%)", step=0.1)
breakLookbackBars = input.int(5, "Pullback route: valid bars after break", minval=1)
// --- Breakout route (押し目なし初動ブレイク) ---
useBreakoutRoute = input.bool(true, "Enable MOU Breakout Route (no pullback)")
breakConfirmPct = input.float(0.3, "Break confirm: close > R*(1+%)", step=0.1)
bigBodyLookback = input.int(20, "Break candle body MA length", minval=5)
bigBodyMult = input.float(1.2, "Break candle: body >= MA*mult", step=0.1)
requireCloseNearHigh = input.bool(true, "Break candle: close near high")
closeNearHighPct = input.float(25.0, "Close near high threshold (% of range)", step=1.0)
allowMACDAboveZeroInstead = input.bool(true, "Breakout route: allow MACD GC above zero instead")
// 表示
showEMA = input.bool(true, "Plot EMAs")
showMou = input.bool(true, "Show MOU label")
showKaku = input.bool(true, "Show KAKU label")
showDebugTbl = input.bool(false, "Show debug table (last bar)")
locChoice = input.string("Below Bar", "Label location", options= )
lblLoc = locChoice == "Below Bar" ? location.belowbar : location.abovebar
// =========================
// EMA
// =========================
emaS = ta.ema(close, emaSLen)
emaM = ta.ema(close, emaMLen)
emaL = ta.ema(close, emaLLen)
// plot は if の中に入れない(naで制御)
plot(showEMA ? emaS : na, color=color.new(color.yellow, 0), title="EMA 5")
plot(showEMA ? emaM : na, color=color.new(color.blue, 0), title="EMA 13")
plot(showEMA ? emaL : na, color=color.new(color.orange, 0), title="EMA 26")
emaUpS = emaS > emaS
emaUpM = emaM > emaM
emaUpL = emaL > emaL
goldenOrder = emaS > emaM and emaM > emaL
above26_2days = close > emaL and close > emaL
// 勝率維持の土台(緩めない)
baseTrendOK = (emaUpS and emaUpM and emaUpL) and goldenOrder and above26_2days
// =========================
// MACD
// =========================
= ta.macd(close, macdFast, macdSlow, macdSignal)
macdGC = ta.crossover(macdLine, macdSig)
macdUp = macdLine > macdLine
macdNearZero = math.abs(macdLine) <= macdZeroTh
macdGCAboveZero = macdGC and macdLine > 0 and macdSig > 0
macdMouOK = macdGC and macdNearZero and macdUp
macdBreakOK = allowMACDAboveZeroInstead ? (macdMouOK or macdGCAboveZero) : macdMouOK
// =========================
// Volume
// =========================
volMA = ta.sma(volume, volLookback)
volRatio = volMA > 0 ? (volume / volMA) : na
volumeMouOK = volRatio >= volMinRatio and volRatio <= volMaxRatio
volumeStrongOK = volRatio >= volStrong and volRatio <= volMaxRatio
// =========================
// Candle patterns
// =========================
body = math.abs(close - open)
upperWick = high - math.max(open, close)
lowerWick = math.min(open, close) - low
pinbar = (lowerWick >= wickBodyMult * body) and (lowerWick > upperWick) and (close >= open)
bullEngulf =
close > open and close < open and
close >= open and open <= close
bigBull =
close > open and
open < emaM and close > emaS and
(body > ta.sma(body, 20))
candleOK = pinbar or bullEngulf or bigBull
// =========================
// Resistance / Pullback route
// =========================
res = ta.highest(high, pivotLen)
pullbackPct = res > 0 ? (res - close) / res * 100.0 : na
pullbackOK = pullbackPct >= pullMinPct and pullbackPct <= pullMaxPct
brokeRes = ta.crossover(close, res )
barsSinceBreak = ta.barssince(brokeRes)
afterBreakZone = (barsSinceBreak >= 0) and (barsSinceBreak <= breakLookbackBars)
pullbackRouteOK = afterBreakZone and pullbackOK
// =========================
// Breakout route (押し目なし初動ブレイク)
// =========================
breakConfirm = close > res * (1.0 + breakConfirmPct / 100.0)
bullBreak = close > open
bodyMA = ta.sma(body, bigBodyLookback)
bigBodyOK = bodyMA > 0 ? (body >= bodyMA * bigBodyMult) : false
rng = math.max(high - low, syminfo.mintick)
closeNearHighOK = not requireCloseNearHigh ? true : ((high - close) / rng * 100.0 <= closeNearHighPct)
mou_breakout =
useBreakoutRoute and
baseTrendOK and
breakConfirm and
bullBreak and
bigBodyOK and
closeNearHighOK and
volumeStrongOK and
macdBreakOK
mou_pullback = baseTrendOK and volumeMouOK and candleOK and macdMouOK and pullbackRouteOK
mou = mou_pullback or mou_breakout
// =========================
// KAKU (Strict): 8条件 + 最終三点
// =========================
cond1 = emaUpS and emaUpM and emaUpL
cond2 = goldenOrder
cond3 = above26_2days
cond4 = macdGCAboveZero
cond5 = volumeMouOK
cond6 = candleOK
cond7 = pullbackOK
cond8 = pullbackRouteOK
all8_strict = cond1 and cond2 and cond3 and cond4 and cond5 and cond6 and cond7 and cond8
final3 = pinbar and macdGCAboveZero and volumeStrongOK
kaku = all8_strict and final3
// =========================
// Display (統一ラベル)
// =========================
showKakuNow = showKaku and kaku
showMouPull = showMou and mou_pullback and not kaku
showMouBrk = showMou and mou_breakout and not kaku
plotshape(showMouPull, title="MOU_PULLBACK", style=shape.labelup, text="猛",
color=color.new(color.lime, 0), textcolor=color.black, location=lblLoc, size=size.tiny)
plotshape(showMouBrk, title="MOU_BREAKOUT", style=shape.labelup, text="猛B",
color=color.new(color.lime, 0), textcolor=color.black, location=lblLoc, size=size.tiny)
plotshape(showKakuNow, title="KAKU", style=shape.labelup, text="確",
color=color.new(color.yellow, 0), textcolor=color.black, location=lblLoc, size=size.small)
// =========================
// Alerts
// =========================
alertcondition(mou, title="MNO_MOU", message="MNO: MOU triggered")
alertcondition(mou_breakout, title="MNO_MOU_BREAKOUT", message="MNO: MOU Breakout triggered")
alertcondition(mou_pullback, title="MNO_MOU_PULLBACK", message="MNO: MOU Pullback triggered")
alertcondition(kaku, title="MNO_KAKU", message="MNO: KAKU triggered")
// =========================
// Debug table (optional)
// =========================
var table t = table.new(position.top_right, 2, 14, border_width=1, border_color=color.new(color.white, 60))
fRow(_name, _cond, _r) =>
bg = _cond ? color.new(color.lime, 70) : color.new(color.red, 80)
tx = _cond ? "OK" : "NO"
table.cell(t, 0, _r, _name, text_color=color.white, bgcolor=color.new(color.black, 0))
table.cell(t, 1, _r, tx, text_color=color.white, bgcolor=bg)
if showDebugTbl and barstate.islast
// ❗ colspanは使えないので2セルでヘッダーを作る
table.cell(t, 0, 0, "MNO Debug", text_color=color.white, bgcolor=color.new(color.black, 0))
table.cell(t, 1, 0, "", text_color=color.white, bgcolor=color.new(color.black, 0))
fRow("BaseTrend", baseTrendOK, 1)
fRow("MOU Pullback", mou_pullback, 2)
fRow("MOU Breakout", mou_breakout, 3)
fRow("Break confirm", breakConfirm, 4)
fRow("Break big body", bigBodyOK, 5)
fRow("Break close high", closeNearHighOK, 6)
fRow("Break vol strong", volumeStrongOK, 7)
fRow("Break MACD", macdBreakOK, 8)
fRow("KAKU all8", all8_strict, 9)
fRow("KAKU final3", final3, 10)
fRow("MOU any", mou, 11)
fRow("KAKU", kaku, 12)






















