Pinescript v3 Compatibility Framework (v4 Migration Tool)Pinescript v3 Compatibility Framework (v4 Migration Tool)
This code makes most v3 scripts work in v4 with only a few minor changes below. Place the framework code before the first input statement.
You can totally delete all comments.
Pros:
- to port to v4 you only need to make a few simple changes, not affecting the core v3 code functionality
Cons:
- without #include - large redundant code block, but can be reduced as needed
- no proper syntax highlighting, intellisence for substitute constant names
Make the following changes in v3 script:
1. standard types can't be var names, color_transp can't be in a function, rename in v3 script:
color() => color.new()
bool => bool_
integer => integer_
float => float_
string => string_
2. init na requires explicit type declaration
float a = na
color col = na
3. persistent var init (optional):
s = na
s := nz(s , s) // or s := na(s ) ? 0 : s
// can be replaced with var s
var s = 0
s := s + 1
___________________________________________________________
Key features of Pinescript v4 (FYI):
1. optional explicit type declaration/conversion (you still can't cast series to int)
float s
2. persistent var modifier
var s
var float s
3. string series - persistent strings now can be used in cond and output to screen dynamically
4. label and line objects
- can be dynamically created, deleted, modified using get/set functions, moved before/after the current bar
- can be in if or a function unlike plot
- max limit: 50-55 label, and 50-55 line drawing objects in addition to already existing plots - both not affected by max plot outputs 64
- can only be used in the main chart
- can serve as the only output function - at least one is required: plot, barcolor, line, label etc.
- dynamic var values (including strings) can be output to screen as text using label.new and to_string
str = close >= open ? "up" : "down"
label.new(bar_index, high, text=str)
col = close >= open ? color.green : color.red
label.new(bar_index, na, "close = " + tostring(close), color=col, textcolor=color.white, style=label.style_labeldown, yloc=yloc.abovebar)
// create new objects, delete old ones
l = line.new(bar_index, high, bar_index , low , width=4)
line.delete(l )
// free object buffer by deleting old objects first, then create new ones
var l = na
line.delete(l)
l = line.new(bar_index, high, bar_index , low , width=4)
Поиск скриптов по запросу "a股板块+沪深两市+股价不超过10元的股票+技术形态好"
Turtle Trade Channels by KıvanÇ fr3762his trend following system was designed by Dennis Gartman and Bill Eckhart, and relies on breakouts of historical highs and lows to take and close trades: it is the complete opposite to the "buy low and sell high" approach. This trend following system was taught to a group of average and normal individuals, and almost everyone turned into a profitable trader.
The main rule is "Trade an N-day breakout and take profits when an M-day high or low is breached (N must me above M)". Examples:
Buy a 10-day breakout and close the trade when price action reaches a 5-day low.
Go short a 20-day breakout and close the trade when price action reaches a 10-day high.
In this indicator, the red line is the trading line, and the dotted blue line is the exit line. Original system is:
Go long when the trading line crosses below close price
Go short when the trading line rosses above close price
Exit long positions when the price touches the exit line
Exit short positions when the price touches the exit line
Recommended initial stop-loss is ATR * 2 from the opening price. Default system parameters were 20,10 and 55,20.
Original Turtle Rules:
To trade exactly like the turtles did, you need to set up two indicators representing the main and the failsafe system.
Set up the main indicator with TradePeriod = 20 and StopPeriod = 10 (A.k.a S1)
Set up the failsafe indicator with TradePeriod = 55 and StopPeriod = 20 using a different color. (A.k.a S2)
The entry strategy using S1 is as follows
Buy 20-day breakouts using S1 only if last signaled trade was a loss.
Sell 20-day breakouts using S1 only if last signaled trade was a loss.
If last signaled trade by S1 was a win, you shouldn't trade -Irregardless of the direction or if you traded last signal it or not-
The entry strategy using S2 is as follows:
Buy 55-day breakouts only if you ignored last S1 signal and the market is rallying without you
Sell 55-day breakouts only if you ignored last S1 signal and the market is pluging without you
The turtles had a progressive position sizing approach that boosted their winnings. Once a trading decision has been made you should...
Developers: Dennis Gartman and Bill Eckhart
İndikatörü geliştiren: Dennis Gartman and Bill Eckhart
Amazing Crossover System - 100+ pips per day!I got the main concept for this system on another site. While I have made one important change, I must stress that the heart of this system was created by someone else! We must give credit where credit is due!
Y'all know baby pips. @ForexPhantom published about this system and did both back and forward test around 10 years ago.
I found it on the sit and now I put it to code to see how it performs. I assume 10 points spread for every trade. I use Renesource or AxiTrader to get the low spreads.
There are 2 mods, the single trades and constant trading on the direction.
Main concept
Indicators
5 EMA -- YELLOW
10 EMA -- RED
RSI (10 - Apply to Median Price: HL/2) -- One level at 50.
TIME FRAME
1 Hour Only (very important!)
PAIRS
Virtually any pair seems to work as this is strictly technical analysis.
I recommend sticking to the main currencies and avoiding cross currencies (just his preference).
WHEN TO ENTER A TRADE
Enter LONG when the Yellow EMA crosses the Red EMA from underneath.
RSI must be approaching 50 from the BOTTOM and cross 50 to warrant entry.
Enter SHORT when the Yellow EMA crosses the Red EMA from the top.
RSI must be approaching 50 from the TOP and cross 50 to warrant entry.
I've attached a picture which demonstrates all these conditions.
That's it!
f.bpcdn.co
Trend Score by KIVANÇ fr3762Trend Score compares close prices between last close with previous closes by a certain period of time.
It's like momentum but gives a score +1 when close price is equal to or above (defaultly) 10 bars ago and gives a score of -1 when below.
calculation continues from default length to the 2 times of length.
Defaultly (for 10 bars length)
If Trend Score converges to 10; that means there's a strong uptrend
conversely if Trend Score converges to -10; that means a strong downtrend market is on.
JSE Wyckoff Wave Volume Code// The Stock Market Institute (SMI) describes an propriety indicator the "SMI Wyckoff Wave" for US Stocks. This code is an attempt to make a Wyckoff Wave for the Johannesburg Stock Exchange (JSE).
// The JSE Wyckoff Wave is in a separate code. This is the code for the volume of the wave. Please see code for the JSE Wyckoff Wave which goes with this indicator.
//
// The Wave presents a normalized price for the 10 selected stocks (An Index for the 10 stocks).
// The theory is to select stocks that are widely held, market leaders, actively traded and participate in important market moves.
// This is only my attempt to select 10 stocks and a different selection can be made.
// I am not certain how SMI determine their weightings but what I have done it to equalize the Rand value of the stock volumne so that moves are of equal magnitude.
// The then provides a view of the overall condition of the market and volume flow in the market.
//
// I have used the September 2018 price to normalize the stock price for the 10 selected stocks based. The stocks and weightings can be changed periodically depending on the performance and leadership.
//
// Please, let me know if there is a better work around this.
The stocks and their weightings are:
"JSE:BTI"/0.79
"JSE:SHP"/2.87
"JSE:NPN"/0.18
"JSE:AGL"/1.96
"JSE:SOL"/1.0
"JSE:CFR"/4.42
"JSE:MND"/1.40
"JSE:MTN"/7.63
"JSE:SLM"/7.29
"JSE:FSR"/8.25
JSE Wyckoff WaveThe Stock Market Institute (SMI) describes an propriety indicator the "SMI Wyckoff Wave" for US Stocks. This code is an attempt to make a Wyckoff Wave for the Johannesburg Stock Exchange (JSE). Once the wave has been established the volume can also be calculated. Please see code for the JSE Wyckoff Wave Volume which goes with this indicator.
The Wave presents a normalized price for the 10 selected stocks (An Index for the 10 stocks). The theory is to select stocks that are widely held, market leaders, actively traded and participate in important market moves. This is only my attempt to select 10 stocks and a different selection can be made. I am not certain how SMI determine their weightings but what I have done it to equalize the Rand value of the stock so that moves are of equal magnitude. The then provides a view of the overall condition of the market and volume flow in the market.
I have used the September 2018 price to normalize the stock price for the 10 selected stocks based. The stocks and weightings can be changed periodically depending on the performance and leadership.
Most Indecies when constructed assume that all high prices and all low prices happen at the same time and therefor inflate the wicks of the bars. To make the wave more representatives for the SMI Wyckoff Wave the price is determined on the 5 minute timeframe which removes this bias. However, TradingView does not calculate properly when selecting a lower timeframe than in current period. A work around is to call the sma of the highs and add these which provides more realistic tails. Please, let me know if there is a better work around this.
The stocks and their weightings are:
"JSE:BTI"*0.79
"JSE:SHP"*2.87
"JSE:NPN"*0.18
"JSE:AGL"*1.96
"JSE:SOL"*1.0
"JSE:CFR"*4.42
"JSE:MND"*1.40
"JSE:MTN"*7.63
"JSE:SLM"*7.29
"JSE:FSR"*8.25
OHLC Daily Resolution BandsShout out to nPE- for the idea.
Bands made with stdev from 10 day OHLC.
Keeps resolution to daily, so you can use bands as daily pivots for day trading.
Upper band 1=yesterday close + 0.5 std(ohlc,10)
Upper band 1=yesterday close + 1 std(ohlc,10)
Mid=yesterday close
Lower band 1=yesterday close - 0.5 std(ohlc,10)
Lower band 2=yesterday close - 1 std(ohlc,1
XPloRR MA-Buy ATR-Trailing-Stop Long Term Strategy Beating B&HXPloRR MA-Buy ATR-MA-Trailing-Stop Strategy
Long term MA Trailing Stop strategy to beat Buy&Hold strategy
None of the strategies that I tested can beat the long term Buy&Hold strategy. That's the reason why I wrote this strategy.
Purpose: beat Buy&Hold strategy with around 10 trades. 100% capitalize sold trade into new trade.
My buy strategy is triggered by the EMA(blue) crossing over the SMA curve(orange).
My sell strategy is triggered by another EMA(lime) of the close value crossing the trailing stop(green) value.
The trailing stop value(green) is set to a multiple of the ATR(15) value.
ATR(15) is the SMA(15) value of the difference between high and low values.
Every stock has it's own "DNA", so first thing to do is find the right parameters to get the best strategy values voor EMA, SMA and Trailing Stop.
Then keep using these parameter for future buy/sell signals only for that particular stock.
Do the same for other stocks.
Here are the parameters:
Exponential MA: buy trigger when crossing over the SMA value (use values between 11-50)
Simple MA: buy trigger when EMA crosses over the SMA value (use values between 20 and 200)
Stop EMA: sell trigger when Stop EMA of close value crosses under the trailing stop value (use values between 8 and 16)
Trailing Stop #ATR: defines the trailing stop value as a multiple of the ATR(15) value
Example parameters for different stocks (Start capital: 1000, Order=100% of equity, Period 1/1/2005 to now):
BAR(Barco): EMA=11, SMA=82, StopEMA=12, Stop#ATR=9
Buy&HoldProfit: 45.82%, NetProfit: 294.7%, #Trades:8, %Profit:62.5%, ProfitFactor: 12.539
AAPL(Apple): EMA=12, SMA=45, StopEMA=12, Stop#ATR=6
Buy&HoldProfit: 2925.86%, NetProfit: 4035.92%, #Trades:10, %Profit:60%, ProfitFactor: 6.36
BEKB(Bekaert): EMA=12, SMA=42, StopEMA=12, Stop#ATR=7
Buy&HoldProfit: 81.11%, NetProfit: 521.37%, #Trades:10, %Profit:60%, ProfitFactor: 2.617
SOLB(Solvay): EMA=12, SMA=63, StopEMA=11, Stop#ATR=8
Buy&HoldProfit: 43.61%, NetProfit: 151.4%, #Trades:8, %Profit:75%, ProfitFactor: 3.794
PHIA(Philips): EMA=11, SMA=80, StopEMA=8, Stop#ATR=10
Buy&HoldProfit: 56.79%, NetProfit: 198.46%, #Trades:6, %Profit:83.33%, ProfitFactor: 23.07
I am very curious to see the parameters for your stocks and please make suggestions to improve this strategy.
Mattzab ArrowsMattzab Arrows
THE BASICS
Buy and Sell Signal Arrows
Tack Marks to show how close the next opposite arrow might be- showing possible trend reversals
Standard Bollinger Bands
10-Day SMA Line
Configurable
Open Source
THE NITTY GRITTY
For starters, all values listed below can be changed in the settings. Length of time, as well as source, can be changed. For the Hidden EMA, this can be made visible by increasing its transparency.
ARROWS
The buy and sell signal arrows are based on price and MACD histogram.
The MACD settings are as follows: 10 day fast EMA , 20 day slow EMA , 5 day SMA signal smoothing. Instead of close price, we are using the average point of the day's high, low, and close.
For the arrows, current price and yesterday's price are using hl2 for high/low average.
A BUY arrow is created when:
Current Price IS GREATER THAN Previous Price _AND_ Current MACD Histogram IS GREATER THAN Previous MACD Histogram.
Important Note! Because the MACD Histogram repaints, the buy arrows may appear, then disappear later in the day, if the MACD changes. Check on the changelog to see if I've fixed it by the time you're reading this. (TradingView doesn't let you edit the description after it's been posted)
A SELL arrow is created when:
Current Price IS LESS THAN Previous Price _AND_ Current MACD Histogram IS LESS THAN Yesterday's MACD Histogram _AND_ Close Price is below _EITHER_ the Hidden EMA (default set to 4) _OR_ the Visible SMA (Default set to 10, which is the black line).
The hidden EMA can be made visible by increasing it's transparency in the Style tab.
Including the requirement to only sell if the standard conditions are met, PLUS being below one of those moving average lines, helps to prevent false sell arrows and repainting.
TACK MARKS
The Red Tack is the threshold, or barrier, for the next arrow. It will not move. It is based on previous High/Low/Close Price + MACD.
The Blue Tack is the current point in space for our average Price and MACD Delta Values. It will move throughout the day (or hour or minute depending on your resolution). The Blue Tack will give you an indication of how close or how far from the reversal threshold (Red Tack) the ticker is at that point.
While the Blue Tack is ABOVE Red, the most recent signal arrow will be a buy, and we are in a buy/hold period.
While the Blue Tack is BELOW Red, the most recent signal arrow will be a sell, and we are in a sell/wait period.
If the Blue Tack crosses above or below Red, you'll get the next arrow.
MOVING AVERAGE LINES
There are three moving average lines in this indicator.
The first is black, and is by default a 10-Day Simple Moving Average Line.
This black line is a good safeguard against selling too early. This is a good support line and that's how I use it.
The second is invisible, but can be made visible in the Styling, and is by default a 4-Day Exponential Moving Average Line
The third is the blue 20-Day Bollinger Band line.
BOLLINGER BANDS
The Bollinger Bands are unmodified and are just a background indicator for your use. If you prefer not to see the Bollinger Bands , change their transparency to 0% to hide them. I've cleaned up the Bollinger Bands to make the indicator as a whole- easier on the eyes.
Please leave feedback on how the script works for you, if you run into problems, if you have any changes you'd like to see, etc.
MACDouble + RSI (rec. 15min-2hr intrv) Uses two sets of MACD plus an RSI to either long or short. All three indicators trigger buy/sell as one (ie it's not 'IF MACD1 OR MACD2 OR RSI > 1 = buy", its more like "IF 1 AND 2 AND RSI=buy", all 3 match required for trigger)
The MACD inputs should be tweaked depending on timeframe and what you are trading. If you are doing 1, 3, 5 min or real frequent trading then 21/44/20 and 32/66/29 or other high value MACDs should be considered. If you are doing longer intervals like 2, 3, 4hr then consider 9/19/9 and 21/44/20 for MACDs (experiment! I picked these example #s randomly).
Ideal usage for the MACD sets is to have MACD2 inputs at around 1.5x, 2x, or 3x MACD1's inputs.
Other settings to consider: try having fastlength1=macdlength1 and then (fastlength2 = macdlength2 - 2). Like 10/26/10 and 23/48/20. This seems to increase net profit since it is more likely to trigger before major price moves, but may decrease profitable trade %. Conversely, consider FL1=MCDL1 and FL2 = MCDL2 + (FL2 * 0.5). Example: 10/26/10 and 22/48/30 this can increase profitable trade %, though may cost some net profit.
Feel free to message me with suggestions or questions.
Kay_BBandsV3This is the 3rd version of Kay_BBands.
When +DI (Directional Index ) is above -DI , then Upper band will be visible and vice-versa.
This is when the ADX is above the threshold. 28 is the default in this version. I found its more appealing in 5M time frame.
BLUE - ADX under 10
GREEN - Uptrend, ADX over 10
RED - Downtrend, ADX over 10
Use it with another band with setting 20, 0.6 deviation. Prices keeping above or below the 2nd bands upper or lower bounds shows trending conditions.
I didn't know how to update the old script so published it again.
Changes - :
1) Updated default settings for the indicator
2) ADX setting are now DI (28), ADX (10), adx level to check is 10.
3) IMPORTANT one - When DI is up/down, lower/upper band will also have color (more visible that way.)
Play around the settings.. It really eliminates extra indicator checking visually... Please like if you think idea is good.
CM Renko Overlay BarsCM_Renko Overlay Bars V1
Overlays Renko Bars on Regular Price Bars.
Default Renko plot is based on Average True Range. Look Back period adjustable in Inputs Tab.
If you Choose to use "Traditional" Renko bars and pick the Size of the Renko Bars the please read below.
Value in Input Tab is multiplied by .001 (To work on Forex)
1 = 10 pips on EURUSD - 1 X .001 = .001 or 10 Pips
10 = .01 or 100 Pips
1000 = 1 point to the left of decimal. 1 Point in Stocks etc.
10000 = 10 Points on Stocks etc.
***V2 will fix this issue.
Custom Indicator - No Trade Zone Warning Back Ground Highlights!Years ago I did an analysis of my trades. Every period of the day was profitable except for two. From 10:00-1030, and 1:00 to 1:30. (I was actively Day Trading Futures) Imagine a vertical graph broken down in to 30 minute time segments. I had nice Green bars in every time slot (Showing Net Profits), and HUGE Red Bars from 10 to 10:30 and 1 to 1:30. After analysis I found I made consistent profits at session open, but then I would enter in to bad setups around 10 to make more money. I also found after I took lunch when I came back at 1:00 I would force trades instead of patiently waiting for a great trade setup. I created an indicator that plotted a red background around those times telling me I was not allowed to enter a trade. Profits went up!!! Details on How to adjust times are in 1st Post. You can adjust times and colors to meet your own trading needs.
BB SPY Mean Reversion Investment StrategySummary
Mean reversion first, continuation second. This strategy targets equities and ETFs on daily timeframes. It waits for price to revert from a Bollinger location with candle and EMA agreement, then manages risk with ATR based exits. Uniqueness comes from two elements working together. One, an adaptive band multiplier driven by volatility of volatility that expands or contracts the envelope as conditions change. Two, a bias memory that re arms the same direction after any stop, target, or time exit until a true opposite signal appears. Add it to a clean chart, use the markers and levels, and select on bar close for conservative alerts. Shapes can move while the bar is open and settle on close.
Scope and intent
• Markets. Currently adapted for SPY, needs to be optimized for other assets
• Timeframes. Daily primary. Other frames are possible but not the default
• Default demo. SPY on daily
• Purpose. Trade mean reversion entries that can chain into a longer swing by splitting holds into ATR or time segments
Originality and usefulness
• Novelty. Adaptive band width from volatility of volatility plus a persistent bias array that keeps the original direction alive across sequential entries until an opposite setup is confirmed
• Failure modes mitigated. False starts in chop are reduced by candle color and EMA location. Missed continuation after a take profit or stop is addressed by the re arm engine. Oversized envelopes during quiet regimes are avoided by the adaptive multiplier
• Testability. Every module has Inputs and visible levels so users can see why a suggestion appears
• Portable yardstick. All risk and targets are expressed in ATR units
Method overview in plain language
The engine measures where price sits relative to Bollinger bands, confirms with candle color and EMA location, requires ADX for shorts(in our case long close since we use it currently as long only), and optionally requires a trend or mean reversion regime using band width percent rank and basis slope. Risk uses ATR for stop, target, and optional breakeven. A small array stores the last confirmed direction. While flat, the engine keeps a pending order in that direction. The array flips only when a true opposite setup appears.
Base measures
• Range basis. True Range smoothed over a user defined ATR Length
• Return basis. Not required
Components
• Bollinger envelope. SMA length and standard deviation multiplier. Entry is based on cross of close through the band with location bias
• Candle and EMA filter. Close relative to open and close relative to EMA align direction
• ADX gate for shorts. Requires minimum trend strength for short trades
• Adaptive multiplier. Band width scales using volatility of volatility so envelopes breathe with conditions
• Regime gate optional. Band width percent rank and basis slope identify trend or mean reversion regimes
• Risk manager. ATR stop, ATR target, optional breakeven, optional time exit
• Bias memory. Array stores last confirmed direction and re arms entries while flat
Fusion rule
Minimum satisfied gates count style. All required gates must be true. Optional gates are controlled in Inputs. Bias memory never overrides an opposite confirmed setup.
Signal rule
• Long setup when close crosses up through the lower band, the bar closes green, and close is above the long EMA
• Short setup when close crosses down through the upper band, the bar closes red, close is below the short EMA, and ADX is above the minimum
• While flat the model keeps a pending order in the stored direction until a true opposite setup appears
• IN LONG or IN SHORT describes states between entry and exit
What you will see on the chart
• Markers for Long and Short setups
• Exit markers from ATR or time rules
• Reference levels for entry, stop, and target
• Bollinger bands and optional adaptive bands
Inputs with guidance
Setup
• Signal timeframe. Uses the chart timeframe
• Invert direction optional. Flips long and short
Logic
• BB Length. Typical 10 to 50. Higher smooths more
• BB Mult. Typical 1.0 to 2.5. Higher widens entries
• EMA Length long. Typical 10 to 50
• EMA Length short. Typical 5 to 30
• ADX Minimum for short. Typical 15 to 35
Filters
• Regime Type. none or trend or mean reversion
• Rank Lookback. Typical 100 to 300
• Basis Slope Length and Threshold. Larger values reduce false trends
Risk
• ATR Length. Typical 10 to 21
• ATR Stop Mult. Typical 1.0 to 3.0
• ATR Take Profit Mult. Typical 2.0 to 5.0
• Breakeven Trigger R. Move stop to entry after the chosen multiple
• Time Exit. Minimum bars and extension when profit exceeds a fraction of ATR
Bias and rearm
• Bias flips kept. Array depth
• Keep rearm when flat. Maintain a pending order while flat
UI
• Show markers and levels. Clean defaults
Usage recipes
Alerts update in real time and can change while the bar forms. Select on bar close for conservative workflows.
Properties visible in this publication
• Initial capital 25000
• Base currency USD
• If any higher timeframe calls are enabled, request.security uses lookahead off
• Commission 0.03 percent
• Slippage 3 ticks
• Default order size method Percent of equity with value 5
• Pyramiding 0
• Process orders on close On
• Bar magnifier Off
• Recalculate after order is filled Off
• Calc on every tick Off
Realism and responsible publication
No performance claims. Costs and fills vary by venue. Shapes can move intrabar and settle on close. Strategies use standard candles only.
Honest limitations and failure modes
High impact releases and thin liquidity can break assumptions. Gap heavy symbols may require larger ATR. Very quiet regimes can reduce contrast in the mean reversion signal. If stop and target can both be touched inside one bar, outcome follows the TradingView order model for that bar path.
Regimes with extreme one sided trend and very low volatility can reduce mean reversion edges. Results vary by symbol and venue. Past results never guarantee future outcomes.
Open source reuse and credits
None.
Backtest realism
Costs are realistic for liquid equities. Sizing does not exceed five percent per trade by default. Any departure should be justified by the user.
If you got any questions please le me know
VWAP + WaveTrend + CHoCH & BOS//@version=5
indicator("GC — VWAP + WaveTrend + CHoCH & BOS (v3.3, clean + pro visuals)", overlay=true, max_lines_count=500, max_labels_count=500)
// ================== TOGGLES D'AFFICHAGE ==================
showVWAPLine = input.bool(true, "Afficher VWAP")
showVWAPBands = input.bool(true, "Afficher Bandes VWAP (ATR)")
showWave = input.bool(true, "Afficher WaveTrend (vague)")
showCHoCH = input.bool(true, "Afficher CHoCH")
showBOS = input.bool(true, "Afficher BOS")
showOB = input.bool(true, "Afficher Order Blocks")
highlightBreakCandle = input.bool(true, "Surbrillance bougie de cassure (CHoCH)")
// ================== TOGGLES LOGIQUES ==================
useBiasFilter = input.bool(true, "Activer filtre Biais HTF (Ichimoku)")
useSessionsFilter = input.bool(true, "Activer filtre Sessions (Europe/Paris)")
enableAlerts = input.bool(true, "Activer alertes LONG/SHORT")
// ================== PARAMS ==================
tfHTF1 = input.timeframe("60", "HTF #1 (H1) pour biais")
tfHTF2 = input.timeframe("240", "HTF #2 (H4) pour biais")
// Sessions (format HHMM-HHMM)
asiaSess = input.session("0100-0900", "Asie (Heure Paris)")
lonSess = input.session("0900-1730", "Londres (Heure Paris)")
nySess = input.session("1430-2200", "New York (Heure Paris)")
useAsia = input.bool(true, "Filtrer Asie")
useLon = input.bool(false, "Filtrer Londres")
useNY = input.bool(false, "Filtrer New York")
// VWAP bands (ATR)
atrLenBands = input.int(14, "ATR Len (bandes VWAP)")
atrMult = input.float(1.0, "ATR Mult (bandes)", step=0.1)
// Structure
pivotLen = input.int(5, "Pivot len (structure)")
// ================== BIAIS ICHIMOKU (HTF) ==================
tenkanLen = input.int(9, "Tenkan", inline="ichi")
kijunLen = input.int(26, "Kijun", inline="ichi")
spanBLen = input.int(52, "SenkouB",inline="ichi")
f_ichi(srcH, srcL, cLen, bLen) =>
ts = (ta.highest(srcH, cLen) + ta.lowest(srcL, cLen)) / 2.0
ks = (ta.highest(srcH, bLen) + ta.lowest(srcL, bLen)) / 2.0
= request.security(syminfo.tickerid, tfHTF1, f_ichi(high, low, tenkanLen, kijunLen), barmerge.gaps_on, barmerge.lookahead_off)
= request.security(syminfo.tickerid, tfHTF2, f_ichi(high, low, tenkanLen, kijunLen), barmerge.gaps_on, barmerge.lookahead_off)
biaisBullRaw = close > ksH1 and tsH1 > ksH1 and close > ksH4 and tsH4 > ksH4
biaisBearRaw = close < ksH1 and tsH1 < ksH1 and close < ksH4 and tsH4 < ksH4
biaisBull = useBiasFilter ? biaisBullRaw : true
biaisBear = useBiasFilter ? biaisBearRaw : true
// ================== SESSIONS ==================
inAsia = not na(time(timeframe.period, asiaSess, "Europe/Paris"))
inLon = not na(time(timeframe.period, lonSess, "Europe/Paris"))
inNY = not na(time(timeframe.period, nySess, "Europe/Paris"))
sessionPassRaw = (useAsia and inAsia) or (useLon and inLon) or (useNY and inNY) or (not useAsia and not useLon and not useNY)
sessionPass = useSessionsFilter ? sessionPassRaw : true
// ================== VWAP + BANDES (ATR) ==================
vwap = ta.vwap
atrB = ta.atr(atrLenBands)
upper = vwap + atrMult * atrB
lower = vwap - atrMult * atrB
plot(showVWAPLine ? vwap : na, "VWAP", linewidth=2, color=color.new(color.gray, 0))
plot(showVWAPBands ? upper : na, "VWAP + ATR", color=color.new(color.gray, 0))
plot(showVWAPBands ? lower : na, "VWAP - ATR", color=color.new(color.gray, 0))
// ================== WAVE TREND (vague lisible) ==================
waveLen1 = input.int(20, "Wave base EMA")
waveLen2 = input.int(40, "Wave smoothing Hull")
srcWT = (high + low + close)/3.0
emaBase = ta.ema(srcWT, waveLen1)
w2half = math.max(1, math.round(waveLen2 / 2.0))
hull = ta.wma(2*ta.wma(emaBase, w2half) - ta.wma(emaBase, waveLen2), math.max(1, math.round(math.sqrt(waveLen2))))
wave = ta.ema(hull, math.max(2, math.round(waveLen1/2.0)))
slopeUp = wave > wave
slopeDn = wave < wave
waveColor =
(useBiasFilter and biaisBullRaw and slopeUp) ? color.new(color.lime, 0) :
(useBiasFilter and biaisBearRaw and slopeDn) ? color.new(color.red, 0) :
color.new(color.gray, 0)
plot(showWave ? wave : na, "WaveTrend", linewidth=3, color=waveColor)
// ================== STRUCTURE: PIVOTS ==================
ph = ta.pivothigh(high, pivotLen, pivotLen)
pl = ta.pivotlow(low, pivotLen, pivotLen)
var float lastSwingHigh = na
var float lastSwingLow = na
var int lastSwingHighBar = na
var int lastSwingLowBar = na
if not na(ph)
lastSwingHigh := ph
lastSwingHighBar := bar_index - pivotLen // index du pivot confirmé
if not na(pl)
lastSwingLow := pl
lastSwingLowBar := bar_index - pivotLen
// Cassures confirmées (bar close)
brokeHigh = not na(lastSwingHigh) and ta.crossover(close, lastSwingHigh)
brokeLow = not na(lastSwingLow) and ta.crossunder(close, lastSwingLow)
// Tendance locale par pente de la Wave
trendUp = slopeUp
trendDown = slopeDn
// Définition des états
bosUp = barstate.isconfirmed and trendUp and brokeHigh
bosDown = barstate.isconfirmed and trendDown and brokeLow
chochUp = barstate.isconfirmed and trendDown and brokeHigh
chochDown = barstate.isconfirmed and trendUp and brokeLow
// ================== VISUELS PRO (lignes BOS/CHoCH + OB + Highlight) ==================
// Conteneurs pour limiter l'encombrement
var line bosLines = array.new_line()
var label bosLabels = array.new_label()
var line chochLines = array.new_line()
var label chochLbls = array.new_label()
var box obBoxes = array.new_box()
var box brkBoxes = array.new_box()
f_trim(arrLine, arrLbl, maxKeep) =>
// supprime les plus anciens si on dépasse maxKeep
if array.size(arrLine) > maxKeep
l = array.shift(arrLine)
line.delete(l)
if array.size(arrLbl) > maxKeep
lb = array.shift(arrLbl)
label.delete(lb)
f_trim_boxes(arr, maxKeep) =>
if array.size(arr) > maxKeep
b = array.shift(arr)
box.delete(b)
// --- Création BOS Up / Down (ligne horizontale + petit label "bos")
if showBOS and bosUp and not na(lastSwingHigh) and not na(lastSwingHighBar)
l = line.new(lastSwingHighBar, lastSwingHigh, bar_index, lastSwingHigh, xloc=xloc.bar_index, extend=extend.none, color=color.new(color.lime, 0), width=2)
lb = label.new(bar_index, lastSwingHigh, "bos", style=label.style_label_left, color=color.new(color.lime, 0), textcolor=color.new(color.black, 0))
array.push(bosLines, l), array.push(bosLabels, lb), f_trim(bosLines, bosLabels, 12)
if showBOS and bosDown and not na(lastSwingLow) and not na(lastSwingLowBar)
l = line.new(lastSwingLowBar, lastSwingLow, bar_index, lastSwingLow, xloc=xloc.bar_index, extend=extend.none, color=color.new(color.red, 0), width=2)
lb = label.new(bar_index, lastSwingLow, "bos", style=label.style_label_left, color=color.new(color.red, 0), textcolor=color.new(color.white, 0))
array.push(bosLines, l), array.push(bosLabels, lb), f_trim(bosLines, bosLabels, 12)
// --- CHoCH Up / Down (ligne + label "ChoCh" + highlight bougie de cassure)
if showCHoCH and chochUp and not na(lastSwingHigh) and not na(lastSwingHighBar)
l = line.new(lastSwingHighBar, lastSwingHigh, bar_index, lastSwingHigh, xloc=xloc.bar_index, extend=extend.none, color=color.new(color.teal, 0), width=2)
lb = label.new(bar_index, lastSwingHigh, "ChoCh", style=label.style_label_left, color=color.new(color.teal, 0), textcolor=color.new(color.black, 0))
array.push(chochLines, l), array.push(chochLbls, lb), f_trim(chochLines, chochLbls, 12)
if highlightBreakCandle
b = box.new(bar_index, high, bar_index, low, bgcolor=color.new(color.orange, 70))
array.push(brkBoxes, b), f_trim_boxes(brkBoxes, 8)
if showCHoCH and chochDown and not na(lastSwingLow) and not na(lastSwingLowBar)
l = line.new(lastSwingLowBar, lastSwingLow, bar_index, lastSwingLow, xloc=xloc.bar_index, extend=extend.none, color=color.new(color.maroon, 0), width=2)
lb = label.new(bar_index, lastSwingLow, "ChoCh", style=label.style_label_left, color=color.new(color.maroon, 0), textcolor=color.new(color.white, 0))
array.push(chochLines, l), array.push(chochLbls, lb), f_trim(chochLines, chochLbls, 12)
if highlightBreakCandle
b = box.new(bar_index, high, bar_index, low, bgcolor=color.new(color.orange, 70))
array.push(brkBoxes, b), f_trim_boxes(brkBoxes, 8)
// --- Order Blocks : dernière bougie opposée avant cassure (body-only)
f_last_opposite_body_idx(maxLookback, wantBull) =>
// cherche la dernière bougie opposée dans les 'maxLookback' barres précédant la cassure
var int idx = na
for i = 1 to maxLookback
isBear = close < open
isBull = close > open
if (wantBull and isBear) or (not wantBull and isBull)
idx := i
break
idx
maxLook = 10
if showOB and (bosUp or chochUp) and not na(lastSwingHigh)
obIdx = f_last_opposite_body_idx(maxLook, true) // pour un mouvement haussier, bougie "opposée" est rouge
if not na(obIdx)
topB = math.max(open , close )
botB = math.min(open , close )
b = box.new(bar_index - obIdx, topB, bar_index - obIdx, botB, xloc=xloc.bar_index, extend=extend.right, bgcolor=color.new(color.blue, 80), border_color=color.new(color.blue, 40))
array.push(obBoxes, b), f_trim_boxes(obBoxes, 10)
if showOB and (bosDown or chochDown) and not na(lastSwingLow)
obIdx = f_last_opposite_body_idx(maxLook, false) // pour un mouvement baissier, bougie "opposée" est verte
if not na(obIdx)
topB = math.max(open , close )
botB = math.min(open , close )
b = box.new(bar_index - obIdx, topB, bar_index - obIdx, botB, xloc=xloc.bar_index, extend=extend.right, bgcolor=color.new(color.blue, 80), border_color=color.new(color.blue, 40))
array.push(obBoxes, b), f_trim_boxes(obBoxes, 10)
// ================== ALERTES ==================
barOK = barstate.isconfirmed and sessionPass
longSignal = barOK and biaisBull and ( (showBOS and bosUp) or (showCHoCH and chochUp) ) and (showVWAPLine ? close >= vwap : true)
shortSignal = barOK and biaisBear and ( (showBOS and bosDown) or (showCHoCH and chochDown) ) and (showVWAPLine ? close <= vwap : true)
alertcondition(enableAlerts and longSignal, "LONG signal (clean)", "LONG — {{ticker}} {{interval}}")
alertcondition(enableAlerts and shortSignal, "SHORT signal (clean)", "SHORT — {{ticker}} {{interval}}")
[FS] Pivot Measurements# Pivot Measurements
An advanced TradingView indicator that combines LuxAlgo's pivot point detection algorithm with automatic measurement calculations between consecutive pivots.
## Features
### Pivot Detection
- **Regular Pivots**: Detects standard pivot highs and lows using configurable pivot length
- **Missed Pivots**: Identifies missed reversal levels that occurred between regular pivots
- **Visual Indicators**:
- Regular pivot highs: Red downward triangle (▼)
- Regular pivot lows: Teal upward triangle (▲)
- Missed pivots: Ghost emoji (👻)
- **Zigzag Lines**: Connects pivots with colored lines (solid for regular, dashed for missed)
- **Ghost Levels**: Horizontal lines indicating missed pivot levels
### Measurement System
- **Automatic Measurements**: Calculates price movements between consecutive pivots
- **Visual Display**:
- Transparent colored boxes (blue for upward, red for downward movements)
- Measurement labels showing:
- Price change (absolute and percentage)
- Duration (bars, days, hours, minutes)
- Volume approximation
- **Smart Positioning**: Labels positioned outside boxes (above for upward, below for downward)
- **Color Coding**: Blue for positive movements, red for negative movements
## Parameters
### Pivot Detection
- **Pivot Length** (default: 50): Number of bars on each side to identify a pivot point
- **Regular Pivots**: Toggle and colors for regular pivot highs and lows
- **Missed Pivots**: Toggle and colors for missed pivot detection
### Measurements
- **Number of Measurements** (1-10, default: 10): Maximum number of measurements to display
- **Show Measurement Boxes**: Toggle to show/hide measurement boxes and labels
- **Box Transparency** (0-100, default: 90): Transparency level for measurement boxes
- **Border Transparency** (0-100, default: 50): Transparency level for box borders
- **Label Background Transparency** (0-100, default: 30): Transparency level for label backgrounds
- **Label Size**: Size of measurement labels (tiny, small, normal, large)
## Usage
1. Add the indicator to your chart
2. Configure the **Pivot Length** based on your timeframe:
- Lower values for shorter timeframes (e.g., 10-20 for 1-5 min)
- Higher values for longer timeframes (e.g., 50-100 for daily)
3. Adjust pivot colors and visibility as needed
4. Customize measurement display settings:
- Set the number of measurements to display
- Adjust transparency levels for boxes, borders, and labels
- Choose label size
## Technical Details
- **Pine Script Version**: v6
- **Pivot Detection**: Based on () algorithm for detecting regular and missed pivots
- **Measurement Calculation**:
- Measures between consecutive pivots (from most recent to older)
- Calculates price change, percentage change, duration, and approximate volume
- Automatically sorts pivots chronologically
- **Performance**: Optimized with helper functions to reduce code duplication
## Notes
- The indicator automatically limits the number of stored pivots to optimize performance
- Measurements are only created when there are at least 2 pivots detected
- All measurements are recalculated on each bar update
- The indicator uses `max_bars_back=5000` to ensure sufficient historical data
## License
This indicator uses LuxAlgo's pivot detection algorithm from (). Please refer to the original LuxAlgo license for pivot detection components.
Directional Strength and Momentum Index█ OVERVIEW
“Directional Strength and Momentum Index” (DSMI) is a technical analysis indicator inspired by DMI, but due to different source data, it produces distinct results. DSMI combines direction measurement, trend strength, and overheat levels into a single index, enhanced with gradient fills, extreme zones, entry signals, candle coloring, and a summary table.
█ CONCEPT
The classic DMI, despite its relatively simple logic, can seem somewhat chaotic due to separate +DI and -DI lines and the need for manual interpretation of their relationships. The DSMI indicator was created to increase clarity and speed up results, consolidating key information into a single index from 0 to 100 that simultaneously:
- Indicates trend direction (bullish/bearish)
- Measures movement strength
- Identifies overheat levels
- Generates ready entry signals
DMI (ADX + +DI / -DI) measures trend direction and strength, but does so based solely on comparing price movements between candles. ADX shows whether the trend is orderly and growing (e.g., above 20–30), but does not assess how dynamic the movement is.
DSMI, on the other hand, takes into account candle size and actual market aggression, thus showing directional momentum — whether the trend has real “fuel” to sustain or accelerate, not just whether it is orderly.
The main calculation difference involves replacing True Range with candle size (high-low) and using directional EMA instead of Wilder smoothing. This allows DSMI to react faster to momentum changes, eliminating delays typical of classic DMI based on TR.
This gives the trader an immediate picture of the market situation without analyzing multiple lines.
█ FEATURES
DSMI Main Line:
- EMA(Directional Index) based on +DS and -DS
- Scale 0–100, smooth color gradient depending on strength
+DS / -DS:
- Positive and Negative Directional Strength
- Gradient fill between lines — more intense with stronger trend
Extreme Zones:
- Default 20 and 80
- Gradient fill outside zones
Trend Strength Levels:
- Weak (<10) → neutral
- Moderate (up to 35)
- Strong (up to 45)
- Overheated (up to 55)
- Extreme (>55)
All levels editable
Entry Signals:
- Activated on crossing entry level (default 20)
Or on direction change when DSMI already ≥ entry level
- Highlighted background (green/red)
Candle Coloring:
- According to current trend
Trend Strength Table:
- Top-right corner
- Shows current strength (WEAK/STRONG etc.) + DSMI value
Alerts:
- DSMI Bullish Entry
- DSMI Bearish Entry
█ HOW TO USE
Add to Chart: Paste code in Pine Editor or find in indicator library.
Settings:
DSMI Parameters:
- DSMI Period → default 20
- Show DSMI Line → on/off
Extreme Zones:
- Lower Level → default 20
- Upper Level → default 80
Trend Strength Levels:
- Weak, Moderate, Strong, Overheated → adjust to strategy
Trend Colors:
- BULLISH → default green
- BEARISH → default red
- NEUTRAL → gray
Entry Signals:
- Show Highlight → on/off
- DSMI Entry Level → default 20
Signal Interpretation:
- DSMI Line: Main strength indicator.
- Gradient between +DS and -DS: Visualizes side dominance.
- Crossing 18 with direction confirmation → entry signal.
- Extreme Zones: Potential reversal or continuation points after correction.
- Table: Quick overview of current trend condition.
█ APPLICATIONS
The indicator works well in:
- Trend-following: Enter on signal, exit on direction change or overheat. When a new trend appears, consider entering a position, preferably with a rising trend strength indicator.
- Scalping/daytrading: Shorter period (7–10), lower entry level.
- Swing/position: Longer period (20–30), higher entry level, extreme zones as filters.
- Noise filtering: Ignores consolidation below “Weak” – increasing value e.g. to 15 highlights consolidation zones, but no signals appear there.
Style Adjustment:
- Aggressive strategies → shorten period and entry level
- Conservative → extend period, raise entry level (25–30), watch “Overheated”
“Weak” level (<10 default) → neutral; increasing it e.g. to 15 gives fewer but higher-quality signals. The Weak zone value controls the level below which no signals appear, and the gradient turns gray (often aligned with consolidation zones).
Combine with:
- Support/resistance levels
- Fair Value Gaps (FVG)
- Volume (Volume Profile, VWAP)
- Other oscillators (RSI, Stochastic)
█ NOTES
- Works on all markets and timeframes.
- Adjust period and levels to instrument volatility.
- Higher entry level → fewer signals, higher quality.
- Neutral color below “Weak” – avoids trading in consolidation.
- Gradient and table enable quick assessment without line analysis.
ScalpGawd Risk Reward//@version=5
indicator("ScalpGawd Risk Reward", overlay=true)
i_fromDate = input.time(timestamp("2024-02-01T00:00:00"), title="Entry Time")
i_entryPrice = input.float(4000, "Entry Price")
i_slPrice = input.float(3900, "Stop Loss Price")
i_distance = input.int(100, "Horizontal Distance (in Time Units)", group="Styling")
i_entryColor = input.color(color.white, "Entry Line", inline="Entry", group="Styling")
i_entryStyle = input.string("solid", title="", options= , inline="Entry", group="Styling")
i_entryWidth = input.int(1, "", inline="Entry", group="Styling")
i_slColor = input.color(color.red, "SL Line", inline="SL", group="Styling")
i_slStyle = input.string("solid", title="", options= , inline="SL", group="Styling")
i_slWidth = input.int(2, "", inline="SL", group="Styling")
i_tpColor = input.color(color.green, "TP Line", inline="TP", group="Styling")
i_tpStyle = input.string("solid", title="", options= , inline="TP", group="Styling")
i_tpWidth = input.int(2, "", inline="TP", group="Styling")
i_labelSize = input.string("tiny", "Label Size", options= , group="Label")
i_labelOffset = input.int(2, "Label Offset", group="Label")
i_useTP1 = input.bool(true, "1", inline="1", group="Show Take Profit")
i_useTP2 = input.bool(true, "2", inline="1", group="Show Take Profit")
i_useTP3 = input.bool(true, "3", inline="1", group="Show Take Profit")
i_useTP4 = input.bool(true, "4", inline="1", group="Show Take Profit")
i_useTP5 = input.bool(true, "5", inline="1", group="Show Take Profit")
i_useTP6 = input.bool(true, "6", inline="1", group="Show Take Profit")
i_useTP7 = input.bool(true, "7", inline="1", group="Show Take Profit")
i_useTP8 = input.bool(true, "8", inline="1", group="Show Take Profit")
i_useTP9 = input.bool(true, "9", inline="1", group="Show Take Profit")
i_useTP10 = input.bool(true, "10", inline="1", group="Show Take Profit")
var int barDistance = na
if bar_index < 2
barDistance := time - time
else
barDistance := math.min(barDistance, time - time )
int distanceInTime = barDistance * i_distance
var line entryLine = na, line.delete(entryLine)
var line stopLossLine = na, line.delete(stopLossLine)
var line tpLine1 = na, line.delete(tpLine1)
var line tpLine2 = na, line.delete(tpLine2)
var line tpLine3 = na, line.delete(tpLine3)
var line tpLine4 = na, line.delete(tpLine4)
var line tpLine5 = na, line.delete(tpLine5)
var line tpLine6 = na, line.delete(tpLine6)
var line tpLine7 = na, line.delete(tpLine7)
var line tpLine8 = na, line.delete(tpLine8)
var line tpLine9 = na, line.delete(tpLine9)
var line tpLine10 = na, line.delete(tpLine10)
var label entryLabel = na, label.delete(entryLabel)
var label slLabel = na, label.delete(slLabel)
var label tpLabel1 = na, label.delete(tpLabel1)
var label tpLabel2 = na, label.delete(tpLabel2)
var label tpLabel3 = na, label.delete(tpLabel3)
var label tpLabel4 = na, label.delete(tpLabel4)
var label tpLabel5 = na, label.delete(tpLabel5)
var label tpLabel6 = na, label.delete(tpLabel6)
var label tpLabel7 = na, label.delete(tpLabel7)
var label tpLabel8 = na, label.delete(tpLabel8)
var label tpLabel9 = na, label.delete(tpLabel9)
var label tpLabel10 = na, label.delete(tpLabel10)
float i_tp1Price = i_entryPrice + (i_entryPrice - i_slPrice)
float i_tp2Price = i_entryPrice + (i_entryPrice - i_slPrice) * 2
float i_tp3Price = i_entryPrice + (i_entryPrice - i_slPrice) * 3
float i_tp4Price = i_entryPrice + (i_entryPrice - i_slPrice) * 4
float i_tp5Price = i_entryPrice + (i_entryPrice - i_slPrice) * 5
float i_tp6Price = i_entryPrice + (i_entryPrice - i_slPrice) * 6
float i_tp7Price = i_entryPrice + (i_entryPrice - i_slPrice) * 7
float i_tp8Price = i_entryPrice + (i_entryPrice - i_slPrice) * 8
float i_tp9Price = i_entryPrice + (i_entryPrice - i_slPrice) * 9
float i_tp10Price = i_entryPrice + (i_entryPrice - i_slPrice) * 10
f_getStyle(_style) =>
ret = line.style_solid
if _style == "dotted"
ret := line.style_dotted
else if _style == "dashed"
ret := line.style_dashed
ret
f_getLabelSize() =>
ret = size.normal
if i_labelSize == "small"
ret := size.small
else if i_labelSize == "tiny"
ret := size.tiny
ret
entryLine := line.new(i_fromDate, i_entryPrice, i_fromDate + distanceInTime, i_entryPrice, xloc=xloc.bar_time, color=i_entryColor, width=i_entryWidth, style=f_getStyle(i_entryStyle))
stopLossLine := line.new(i_fromDate, i_slPrice, i_fromDate + distanceInTime, i_slPrice, xloc=xloc.bar_time, color=i_slColor, width=i_slWidth, style=f_getStyle(i_slStyle))
tpLine1 := i_useTP1 ? line.new(i_fromDate, i_tp1Price, i_fromDate + distanceInTime, i_tp1Price, xloc=xloc.bar_time, color=i_tpColor, width=i_tpWidth, style=f_getStyle(i_tpStyle)) : na
tpLine2 := i_useTP2 ? line.new(i_fromDate, i_tp2Price, i_fromDate + distanceInTime, i_tp2Price, xloc=xloc.bar_time, color=i_tpColor, width=i_tpWidth, style=f_getStyle(i_tpStyle)) : na
tpLine3 := i_useTP3 ? line.new(i_fromDate, i_tp3Price, i_fromDate + distanceInTime, i_tp3Price, xloc=xloc.bar_time, color=i_tpColor, width=i_tpWidth, style=f_getStyle(i_tpStyle)) : na
tpLine4 := i_useTP4 ? line.new(i_fromDate, i_tp4Price, i_fromDate + distanceInTime, i_tp4Price, xloc=xloc.bar_time, color=i_tpColor, width=i_tpWidth, style=f_getStyle(i_tpStyle)) : na
tpLine5 := i_useTP5 ? line.new(i_fromDate, i_tp5Price, i_fromDate + distanceInTime, i_tp5Price, xloc=xloc.bar_time, color=i_tpColor, width=i_tpWidth, style=f_getStyle(i_tpStyle)) : na
tpLine6 := i_useTP6 ? line.new(i_fromDate, i_tp6Price, i_fromDate + distanceInTime, i_tp6Price, xloc=xloc.bar_time, color=i_tpColor, width=i_tpWidth, style=f_getStyle(i_tpStyle)) : na
tpLine7 := i_useTP7 ? line.new(i_fromDate, i_tp7Price, i_fromDate + distanceInTime, i_tp7Price, xloc=xloc.bar_time, color=i_tpColor, width=i_tpWidth, style=f_getStyle(i_tpStyle)) : na
tpLine8 := i_useTP8 ? line.new(i_fromDate, i_tp8Price, i_fromDate + distanceInTime, i_tp8Price, xloc=xloc.bar_time, color=i_tpColor, width=i_tpWidth, style=f_getStyle(i_tpStyle)) : na
tpLine9 := i_useTP9 ? line.new(i_fromDate, i_tp9Price, i_fromDate + distanceInTime, i_tp9Price, xloc=xloc.bar_time, color=i_tpColor, width=i_tpWidth, style=f_getStyle(i_tpStyle)) : na
tpLine10 := i_useTP10 ? line.new(i_fromDate, i_tp10Price, i_fromDate + distanceInTime, i_tp10Price, xloc=xloc.bar_time, color=i_tpColor, width=i_tpWidth, style=f_getStyle(i_tpStyle)) : na
entryLabel := label.new(i_fromDate + barDistance * i_labelOffset, i_entryPrice, text="Entry @ " + str.tostring(i_entryPrice, '#.##'), xloc=xloc.bar_time, yloc=yloc.price, textcolor=i_entryColor, style=label.style_none,textalign = text.align_center, size=f_getLabelSize())
slLabel := label.new(i_fromDate + barDistance * i_labelOffset, i_slPrice, text="Stop Loss " + str.tostring((i_slPrice - i_entryPrice) / syminfo.mintick, "#")+ " Ticks @ " + str.tostring(i_slPrice, '#.##'), xloc=xloc.bar_time, yloc=yloc.price, textcolor=i_slColor, style=label.style_none,textalign = text.align_center, size=f_getLabelSize())
tpLabel1 := i_useTP1 ? label.new(i_fromDate + barDistance * i_labelOffset, i_tp1Price, text="Target 1 " + str.tostring((i_tp1Price - i_entryPrice) / syminfo.mintick, "#")+ " Ticks @ " + str.tostring(i_tp1Price, '#.##'), xloc=xloc.bar_time, yloc=yloc.price, textcolor=i_tpColor, style=label.style_none,textalign = text.align_center, size=f_getLabelSize()) : na
tpLabel2 := i_useTP2 ? label.new(i_fromDate + barDistance * i_labelOffset, i_tp2Price, text="Target 2 " + str.tostring((i_tp2Price - i_entryPrice) / syminfo.mintick, "#")+ " Ticks @ " + str.tostring(i_tp2Price, '#.##'), xloc=xloc.bar_time, yloc=yloc.price, textcolor=i_tpColor, style=label.style_none,textalign = text.align_center, size=f_getLabelSize()) : na
tpLabel3 := i_useTP3 ? label.new(i_fromDate + barDistance * i_labelOffset, i_tp3Price, text="Target 3 " + str.tostring((i_tp3Price - i_entryPrice) / syminfo.mintick, "#")+ " Ticks @ " + str.tostring(i_tp3Price, '#.##'), xloc=xloc.bar_time, yloc=yloc.price, textcolor=i_tpColor, style=label.style_none,textalign = text.align_center, size=f_getLabelSize()) : na
tpLabel4 := i_useTP4 ? label.new(i_fromDate + barDistance * i_labelOffset, i_tp4Price, text="Target 4 " + str.tostring((i_tp4Price - i_entryPrice) / syminfo.mintick, "#")+ " Ticks @ " + str.tostring(i_tp4Price, '#.##'), xloc=xloc.bar_time, yloc=yloc.price, textcolor=i_tpColor, style=label.style_none,textalign = text.align_center, size=f_getLabelSize()) : na
tpLabel5 := i_useTP5 ? label.new(i_fromDate + barDistance * i_labelOffset, i_tp5Price, text="Target 5 " + str.tostring((i_tp5Price - i_entryPrice) / syminfo.mintick, "#")+ " Ticks @ " + str.tostring(i_tp5Price, '#.##'), xloc=xloc.bar_time, yloc=yloc.price, textcolor=i_tpColor, style=label.style_none,textalign = text.align_center, size=f_getLabelSize()) : na
tpLabel6 := i_useTP6 ? label.new(i_fromDate + barDistance * i_labelOffset, i_tp6Price, text="Target 6 " + str.tostring((i_tp6Price - i_entryPrice) / syminfo.mintick, "#")+ " Ticks @ " + str.tostring(i_tp6Price, '#.##'), xloc=xloc.bar_time, yloc=yloc.price, textcolor=i_tpColor, style=label.style_none,textalign = text.align_center, size=f_getLabelSize()) : na
tpLabel7 := i_useTP7 ? label.new(i_fromDate + barDistance * i_labelOffset, i_tp7Price, text="Target 7 " + str.tostring((i_tp7Price - i_entryPrice) / syminfo.mintick, "#")+ " Ticks @ " + str.tostring(i_tp7Price, '#.##'), xloc=xloc.bar_time, yloc=yloc.price, textcolor=i_tpColor, style=label.style_none,textalign = text.align_center, size=f_getLabelSize()) : na
tpLabel8 := i_useTP8 ? label.new(i_fromDate + barDistance * i_labelOffset, i_tp8Price, text="Target 8 " + str.tostring((i_tp8Price - i_entryPrice) / syminfo.mintick, "#")+ " Ticks @ " + str.tostring(i_tp8Price, '#.##'), xloc=xloc.bar_time, yloc=yloc.price, textcolor=i_tpColor, style=label.style_none,textalign = text.align_center, size=f_getLabelSize()) : na
tpLabel9 := i_useTP9 ? label.new(i_fromDate + barDistance * i_labelOffset, i_tp9Price, text="Target 9 " + str.tostring((i_tp9Price - i_entryPrice) / syminfo.mintick, "#")+ " Ticks @ " + str.tostring(i_tp9Price, '#.##'), xloc=xloc.bar_time, yloc=yloc.price, textcolor=i_tpColor, style=label.style_none,textalign = text.align_center, size=f_getLabelSize()) : na
tpLabel10 := i_useTP10 ? label.new(i_fromDate + barDistance * i_labelOffset, i_tp10Price, text="Target 10 " + str.tostring((i_tp10Price - i_entryPrice) / syminfo.mintick, "#")+ " Ticks @ " + str.tostring(i_tp10Price, '#.##'), xloc=xloc.bar_time, yloc=yloc.price, textcolor=i_tpColor, style=label.style_none,textalign = text.align_center, size=f_getLabelSize()) : na
i_showBox = input.bool(true, "Show Background", group="Show Background")
var box greenBox = na, box.delete(greenBox)
var box redBox = na, box.delete(redBox)
f_findHighestTP() =>
ret = i_tp1Price
if i_useTP10
ret := i_tp10Price
else if i_useTP9
ret := i_tp9Price
else if i_useTP8
ret := i_tp8Price
else if i_useTP7
ret := i_tp7Price
else if i_useTP6
ret := i_tp6Price
else if i_useTP5
ret := i_tp5Price
else if i_useTP4
ret := i_tp4Price
else if i_useTP3
ret := i_tp3Price
else if i_useTP2
ret := i_tp2Price
ret
greenBox := i_showBox ? box.new(i_fromDate, i_entryPrice, i_fromDate + distanceInTime, f_findHighestTP(), xloc=xloc.bar_time, bgcolor=color.new(i_tpColor, 70), border_width = 0) : na
redBox := i_showBox ? box.new(i_fromDate, i_entryPrice, i_fromDate + distanceInTime, i_slPrice, xloc=xloc.bar_time, bgcolor=color.new(i_slColor, 70), border_width = 0) : na
VIX/VVIX Spike RiskVIX/VVIX Spike Risk Analyzer
The VIX/VVIX Spike Risk Analyzer analyzes historical VIX behavior under similar market conditions to forecast future VIX spike risk.
By combining current VIX and VVIX levels as dual filters, it identifies historical precedents and calculates the probability and magnitude of VIX spikes over the next 1, 5, and 10 trading days.
IMPORTANT: This indicator must be applied to the VIX chart (CBOE:VIX) to function correctly.
Methodology
1. Dual-Filter Pattern Matching
The indicator uses both VIX and VVIX as simultaneous filters to identify historically analogous market conditions:
By requiring BOTH metrics to match historical levels, the indicator creates more precise market condition filters than using VIX alone. This dual-filter approach significantly improves predictive accuracy because:
VIX alone might be at 15, but VVIX can tell us if that 15 is stable (low VVIX) or explosive (high VVIX)
High VVIX + Low VIX often precedes major spikes
Low VVIX + Low VIX suggests sustained calm
2. Tolerance Settings
VIX Matching (Default: ±10% Relative)
Uses relative percentage matching for consistency across different VIX regimes
Example: VIX at 15 matches 13.5-16.5 (±10%)
Can switch to absolute tolerance (±5 points) if preferred
VVIX Matching (Default: ±10 Points Absolute)
Uses absolute point matching as VVIX scales differently
Example: VVIX at 100 matches 90-110
Can switch to relative percentage if preferred
3. Historical Analysis Window
The indicator scans up to 500 bars backward (limited by VVIX data availability) to find all historical periods where both VIX and VVIX were at similar levels. Each match becomes a "sample" for statistical analysis.
4. Forward-Looking Spike Analysis
For each historical match, the indicator measures VIX behavior over the next 1, 5, and 10 days
Display Metrics Explained
Average Highest Spike
Shows the average of the maximum VIX spikes observed.
Highest Single Spike
Shows the single largest spike ever recorded
Probability No 10% Spike
Shows what percentage of historical cases stayed BELOW a 10% spike:
Probability No 20% Spike
Shows what percentage of historical cases stayed BELOW a 20% spike:
Note : You'll see many more shaded bars than the sample count because each match creates up to 5 consecutive shaded bars (bars 1-5 after the match all "look back" and see it).
Short Volatility Strategies:
Enter when there's a LOW probability of big vol spikes based on today's metrics
Long Volatility Strategies
Enter when there's a HIGH probability of big vol spikes based on today's metrics
LibTmFrLibrary "LibTmFr"
This is a utility library for handling timeframes and
multi-timeframe (MTF) analysis in Pine Script. It provides a
collection of functions designed to handle common tasks related
to period detection, session alignment, timeframe construction,
and time calculations, forming a foundation for
MTF indicators.
Key Capabilities:
1. **MTF Period Engine:** The library includes functions for
managing higher-timeframe (HTF) periods.
- **Period Detection (`isNewPeriod`):** Detects the first bar
of a given timeframe. It includes custom logic to handle
multi-month and multi-year intervals where
`timeframe.change()` may not be sufficient.
- **Bar Counting (`sinceNewPeriod`):** Counts the number of
bars that have passed in the current HTF period or
returns the final count for a completed historical period.
2. **Automatic Timeframe Selection:** Offers functions for building
a top-down analysis framework:
- **Automatic HTF (`autoHTF`):** Suggests a higher timeframe
(HTF) for broader context based on the current timeframe.
- **Automatic LTF (`autoLTF`):** Suggests an appropriate lower
timeframe (LTF) for granular intra-bar analysis.
3. **Timeframe Manipulation and Comparison:** Includes tools for
working with timeframe strings:
- **Build & Split (`buildTF`, `splitTF`):** Functions to
programmatically construct valid Pine Script timeframe
strings (e.g., "4H") and parse them back into their
numeric and unit components.
- **Comparison (`isHigherTF`, `isActiveTF`, `isLowerTF`):**
A set of functions to check if a given timeframe is
higher, lower, or the same as the script's active timeframe.
- **Multiple Validation (`isMultipleTF`):** Checks if a
higher timeframe is a practical multiple of the current
timeframe. This is based on the assumption that checking
if recent, completed HTF periods contained more than one
bar is a valid proxy for preventing data gaps.
4. **Timestamp Interpolation:** Contains an `interpTimestamp()`
function that calculates an absolute timestamp by
interpolating at a given percentage across a specified
range of bars (e.g., 50% of the way through the last
20 bars), enabling time calculations at a resolution
finer than the chart's native bars.
---
**DISCLAIMER**
This library is provided "AS IS" and for informational and
educational purposes only. It does not constitute financial,
investment, or trading advice.
The author assumes no liability for any errors, inaccuracies,
or omissions in the code. Using this library to build
trading indicators or strategies is entirely at your own risk.
As a developer using this library, you are solely responsible
for the rigorous testing, validation, and performance of any
scripts you create based on these functions. The author shall
not be held liable for any financial losses incurred directly
or indirectly from the use of this library or any scripts
derived from it.
buildTF(quantity, unit)
Builds a Pine Script timeframe string from a numeric quantity and a unit enum.
The resulting string can be used with `request.security()` or `input.timeframe`.
Parameters:
quantity (int) : series int Number to specifie how many `unit` the timeframe spans.
unit (series TFUnit) : series TFUnit The size category for the bars.
Returns: series string A Pine-style timeframe identifier, e.g.
"5S" → 5-seconds bars
"30" → 30-minute bars
"120" → 2-hour bars
"1D" → daily bars
"3M" → 3-month bars
"24M" → 2-year bars
splitTF(tf)
Splits a Pine‑timeframe identifier into numeric quantity and unit (TFUnit).
Parameters:
tf (string) : series string Timeframe string, e.g.
"5S", "30", "120", "1D", "3M", "24M".
Returns:
quantity series int The numeric value of the timeframe (e.g., 15 for "15", 3 for "3M").
unit series TFUnit The unit of the timeframe (e.g., TFUnit.minutes, TFUnit.months).
Notes on strings without a suffix:
• Pure digits are minutes; if divisible by 60, they are treated as hours.
• An "M" suffix is months; if divisible by 12, it is converted to years.
autoHTF(tf)
Picks an appropriate **higher timeframe (HTF)** relative to the selected timeframe.
It steps up along a coarse ladder to produce sensible jumps for top‑down analysis.
Mapping → chosen HTF:
≤ 1 min → 60 (1h) ≈ ×60
≤ 3 min → 180 (3h) ≈ ×60
≤ 5 min → 240 (4h) ≈ ×48
≤ 15 min → D (1 day) ≈ ×26–×32 (regular session 6.5–8 h)
> 15 min → W (1 week) ≈ ×64–×80 for 30m; varies with input
≤ 1 h → W (1 week) ≈ ×32–×40
≤ 4 h → M (1 month) ≈ ×36–×44 (~22 trading days / month)
> 4 h → 3M (3 months) ≈ ×36–×66 (e.g., 12h→×36–×44; 8h→×53–×66)
≤ 1 day → 3M (3 months) ≈ ×60–×66 (~20–22 trading days / month)
> 1 day → 12M (1 year) ≈ ×(252–264)/quantity
≤ 1 week → 12M (1 year) ≈ ×52
> 1 week → 48M (4 years) ≈ ×(208)/quantity
= 1 M → 48M (4 years) ≈ ×48
> 1 M → error ("HTF too big")
any → error ("HTF too big")
Notes:
• Inputs in months or years are restricted: only 1M is allowed; larger months/any years throw.
• Returns a Pine timeframe string usable in `request.security()` and `input.timeframe`.
Parameters:
tf (string) : series string Selected timeframe (e.g., "D", "240", or `timeframe.period`).
Returns: series string Suggested higher timeframe.
autoLTF(tf)
Selects an appropriate **lower timeframe LTF)** for intra‑bar evaluation
based on the selected timeframe. The goal is to keep intra‑bar
loops performant while providing enough granularity.
Mapping → chosen LTF:
≤ 1 min → 1S ≈ ×60
≤ 5 min → 5S ≈ ×60
≤ 15 min → 15S ≈ ×60
≤ 30 min → 30S ≈ ×60
> 30 min → 60S (1m) ≈ ×31–×59 (for 31–59 minute charts)
≤ 1 h → 1 (1m) ≈ ×60
≤ 2 h → 2 (2m) ≈ ×60
≤ 4 h → 5 (5m) ≈ ×48
> 4 h → 15 (15m) ≈ ×24–×48 (e.g., 6h→×24, 8h→×32, 12h→×48)
≤ 1 day → 15 (15m) ≈ ×26–×32 (regular sessions ~6.5–8h)
> 1 day → 60 (60m) ≈ ×(26–32) per day × quantity
≤ 1 week → 60 (60m) ≈ ×32–×40 (≈5 sessions of ~6.5–8h)
> 1 week → 240 (4h) ≈ ×(8–10) per week × quantity
≤ 1 M → 240 (4h) ≈ ×33–×44 (~20–22 sessions × 6.5–8h / 4h)
≤ 3 M → D (1d) ≈ ×(20–22) per month × quantity
> 3 M → W (1w) ≈ ×(4–5) per month × quantity
≤ 1 Y → W (1w) ≈ ×52
> 1 Y → M (1M) ≈ ×12 per year × quantity
Notes:
• Ratios for D/W/M are given as ranges because they depend on
**regular session length** (typically ~6.5–8h, not 24h).
• Returned strings can be used with `request.security()` and `input.timeframe`.
Parameters:
tf (string) : series string Selected timeframe (e.g., "D", "240", or timeframe.period).
Returns: series string Suggested lower TF to use for intra‑bar work.
isNewPeriod(tf, offset)
Returns `true` when a new session-aligned period begins, or on the Nth bar of that period.
Parameters:
tf (string) : series string Target higher timeframe (e.g., "D", "W", "M").
offset (simple int) : simple int 0 → checks for the first bar of the new period.
1+ → checks for the N-th bar of the period.
Returns: series bool `true` if the condition is met.
sinceNewPeriod(tf, offset)
Counts how many bars have passed within a higher timeframe (HTF) period.
For daily, weekly, and monthly resolutions, the period is aligned with the trading session.
Parameters:
tf (string) : series string Target parent timeframe (e.g., "60", "D").
offset (simple int) : simple int 0 → Running count for the current period.
1+ → Finalized count for the Nth most recent *completed* period.
Returns: series int Number of bars.
isHigherTF(tf, main)
Returns `true` when the selected timeframe represents a
higher resolution than the active timeframe.
Parameters:
tf (string) : series string Selected timeframe.
main (bool) : series bool When `true`, the comparison is made against the chart's main timeframe
instead of the script's active timeframe. Optional. Defaults to `false`.
Returns: series bool `true` if `tf` > active TF; otherwise `false`.
isActiveTF(tf, main)
Returns `true` when the selected timeframe represents the
exact resolution of the active timeframe.
Parameters:
tf (string) : series string Selected timeframe.
main (bool) : series bool When `true`, the comparison is made against the chart's main timeframe
instead of the script's active timeframe. Optional. Defaults to `false`.
Returns: series bool `true` if `tf` == active TF; otherwise `false`.
isLowerTF(tf, main)
Returns `true` when the selected timeframe represents a
lower resolution than the active timeframe.
Parameters:
tf (string) : series string Selected timeframe.
main (bool) : series bool When `true`, the comparison is made against the chart's main timeframe
instead of the script's active timeframe. Optional. Defaults to `false`.
Returns: series bool `true` if `tf` < active TF; otherwise `false`.
isMultipleTF(tf)
Returns `true` if the selected timeframe (`tf`) is a practical multiple
of the active skript's timeframe. It verifies this by checking if `tf` is a higher timeframe
that has consistently contained more than one bar of the skript's timeframe in recent periods.
The period detection is session-aware.
Parameters:
tf (string) : series string The higher timeframe to check.
Returns: series bool `true` if `tf` is a practical multiple; otherwise `false`.
interpTimestamp(offStart, offEnd, pct)
Calculates a precise absolute timestamp by interpolating within a bar range based on a percentage.
This version works with RELATIVE bar offsets from the current bar.
Parameters:
offStart (int) : series int The relative offset of the starting bar (e.g., 10 for 10 bars ago).
offEnd (int) : series int The relative offset of the ending bar (e.g., 1 for 1 bar ago). Must be <= offStart.
pct (float) : series float The percentage of the bar range to measure (e.g., 50.5 for 50.5%).
Values are clamped to the range.
Returns: series int The calculated, interpolated absolute Unix timestamp in milliseconds.
💻 RSI Dual-Band Reversal Strategy (Hacker Mode)This 💻 RSI Dual-Band Reversal Strategy (Hacker Mode) is a mean-reversion trading strategy built on the Relative Strength Index (RSI) indicator.
It identifies potential trend reversals when price momentum reaches extreme overbought or oversold levels — then enters trades expecting the price to revert.
⚙️ Strategy Concept
The RSI measures market momentum on a scale of 0–100.
When RSI is too low, it signals an oversold market → potential buy.
When RSI is too high, it signals an overbought market → potential sell.
This strategy sets two reversal zones using dual RSI bands:
Zone RSI Range Meaning Action
Upper Band 80–90 Overbought Prepare to Sell
Lower Band 10–20 Oversold Prepare to Buy
🧩 Code Breakdown
1. Input Parameters
rsiLength = input.int(14)
upperBandHigh = input.float(90.0)
upperBandLow = input.float(80.0)
lowerBandLow = input.float(10.0)
lowerBandHigh = input.float(20.0)
You can adjust:
RSI Length (default 14) → sensitivity of the RSI.
Upper/Lower Bands → control when buy/sell triggers occur.
2. RSI Calculation
rsi = ta.rsi(close, rsiLength)
Calculates the RSI of the closing price over 14 periods.
3. Signal Logic
buySignal = ta.crossover(rsi, lowerBandHigh)
sellSignal = ta.crossunder(rsi, upperBandLow)
Buy Signal: RSI crosses up through 20 → market rebounding from oversold.
Sell Signal: RSI crosses down through 80 → market turning from overbought.
4. Plotting
RSI line (lime green)
Bands:
🔴 80–90 (Sell Zone)
🟢 10–20 (Buy Zone)
Gray midline at 50 for reference.
Triangle markers for signals:
🟢 “BUY” below chart
🔴 “SELL” above chart
5. Trading Logic
if (buySignal)
strategy.entry("Buy", strategy.long)
if (sellSignal)
strategy.entry("Sell", CRYPTO:BTCUSD strategy.short OANDA:XAUUSD )
Opens a long position on a buy signal.
Opens a short position on a sell signal.
No explicit stop loss or take profit — positions reverse when an opposite signal appears.
🧠 How It Works (Step-by-Step Example)
RSI drops below 20 → oversold → buy signal triggers.
RSI rises toward 80 → overbought → sell signal triggers.
Strategy flips position, always staying in the market (either long or short).
📈 Visual Summary
Imagine the RSI line oscillating between 0 and 100:
100 ────────────────────────────────
90 ───── Upper Band High (Sell Limit)
80 ───── Upper Band Low (Sell Trigger)
50 ───── Midline
20 ───── Lower Band High (Buy Trigger)
10 ───── Lower Band Low (Buy Limit)
0 ────────────────────────────────
When RSI moves above 80 → SELL
When RSI moves below 20 → BUY
⚡ Strategy Profile
Category Description
Type Mean Reversion
Entry Rule RSI crosses up 20 → Buy
Exit/Reverse Rule RSI crosses down 80 → Sell
Strengths Simple, effective in sideways/range markets, minimal lag
Weaknesses Weak in strong trends, no stop-loss or take-profit logic
💡 Suggested Improvements
You can enhance this script by adding:
Stop loss & take profit levels (e.g., % or ATR-based).
Trend filter (e.g., trade only in direction of 200 EMA).
RSI smoothing to reduce noise.
Lot Size Calculator - Gold🥇 Lot Size Calculator for Gold (XAU/USD)
Description:
A professional and accurate lot size calculator specifically designed for Gold (XAU/USD) trading. This indicator helps traders calculate the optimal position size based on account balance, risk percentage, and stop loss distance, ensuring proper risk management for every trade.
Key Features:
Accurate Gold Calculations - Properly accounts for Gold pip values ($10 per pip for standard 100oz lots)
Multi-Currency Support - Works with USD, EUR, and GBP account currencies
Flexible Contract Sizes - Supports Standard (100 oz), Mini (10 oz), and Micro (1 oz) lots
Customizable Decimal Places - Display lot sizes with 2-8 decimal precision (no rounding)
Clean Visual Design - Modern, professional info panel with gold-themed styling
Adjustable Display - Position panel anywhere on chart with customizable colors and sizes
Real-Time Calculations - Instantly updates as you adjust your risk parameters
How It Works:
The calculator uses the standard forex position sizing formula optimized for Gold:
Lot Size = Risk Amount / (Stop Loss in Pips × Pip Value Per Lot)
For Gold (XAU/USD):
Standard Lot (100 oz): 1 pip = $10
Mini Lot (10 oz): 1 pip = $1
Micro Lot (1 oz): 1 pip = $0.10
Settings:
Account Settings:
Account Balance: Your trading capital
Account Currency: USD, EUR, or GBP
Risk Percentage: How much to risk per trade (default: 2%)
Contract Size: 100 oz (Standard), 10 oz (Mini), or 1 oz (Micro)
Display Currency: Choose how to display risk amounts
Trade Settings:
Stop Loss: Your SL distance in pips
Display Settings:
Label Position: Top/Bottom, Left/Right, Middle Right
Label Size: Tiny to Huge
Decimal Places: 2-8 decimals
Custom Colors: Background, text, and accent colors
Perfect For:
Gold (XAU/USD) day traders and swing traders
Position sizing and risk management
Traders using fixed percentage risk models
Anyone trading Gold CFDs or spot markets
Scalpers to long-term Gold investors
What Makes This Different:
Unlike generic lot size calculators, this tool correctly calculates Gold's pip values based on contract size. Many calculators get this wrong, leading to incorrect position sizing. This indicator ensures you're always trading the right lot size for your risk tolerance.
Example Usage:
Account Balance: $10,000
Risk: 1% = $100
Stop Loss: 60 pips
Contract Size: 100 oz (Standard)
Result: 0.1667 lots (exact, no rounding)
Perfect for maintaining consistent risk management in your Gold trading strategy!
ProScalper📊 ProScalper - Professional 1-Minute Scalping System
🎯 Overview
ProScalper is a sophisticated, multi-confluence scalping indicator designed specifically for 1-minute chart trading. Combining advanced technical analysis with intelligent signal filtering, it provides high-probability trade setups with clear entry, stop loss, and take profit levels.
✨ Key Features
🔺 Smart Signal Detection
Range Filter Technology: Fast-responding trend detection (25-period) optimized for 1-minute timeframe
Medium-sized triangles appear above/below candles for clear buy/sell signals
Only most recent signal shown - no chart clutter
Automatically deletes old signals when new ones appear
📋 Real-Time Signal Table
Top-center display shows complete trade breakdown
Grade system: A+, A, B+, B, C+ ratings for every setup
All confluence reasons listed with checkmarks
Score and R:R displayed for instant trade quality assessment
Color-coded: Green for LONG, Red for SHORT
📐 Multi-Confluence Analysis
ProScalper combines 10+ technical factors:
✅ EMA Trend: 4 EMAs (200, 48, 13, 8) for multi-timeframe alignment
✅ VWAP: Dynamic support/resistance
✅ Fibonacci Retracement: Golden ratio (61.8%), 50%, 38.2%, 78.6%
✅ Range Filter: Adaptive trend confirmation
✅ Pivot Points: Smart reversal detection
✅ Volume Analysis: Spike detection and volume profile
✅ Higher Timeframe: 5-minute trend confirmation
✅ HTF Support/Resistance: Key levels from higher timeframes
✅ Liquidity Sweeps: Smart money detection
✅ Opening Range Breakout: First 15-minute range
💰 Complete Trade Management
Entry Lines: Dashed green (LONG) or red (SHORT) showing exact entry
Stop Loss: Red dashed line with price label
Take Profit: Blue dashed line with price label and R:R
Partial Exits: 1R level marked with orange dashed line
All lines extend 10 bars for clean alignment with Fibonacci levels
📊 Dynamic Risk/Reward
Adaptive R:R calculation based on market volatility
Targets adjusted for pivot distances
Minimum 1.2:1 to maximum 3.5:1 for scalping
Position sizing based on account risk percentage
🎨 Professional Visualization
Clean chart layout - no clutter, only essential information
Custom EMA colors: Red (200), Aqua (48), Green (13), White (8)
Gold VWAP line for key support/resistance
Color-coded Fibonacci: Bright yellow (61.8%), white (50%), orange (38.2%), fuchsia (78.6%)
No shaded zones - pure price action focus
📈 Performance Tracking
Real-time statistics table (optional)
Win rate, total trades, P&L tracking
Average R:R and win/loss ratios
Setup-specific performance metrics
⚙️ Settings & Customization
Risk Management
Adjustable account risk per trade (default: 0.5%)
ATR-based stop loss multiplier (default: 0.8 for tight scalping)
Dynamic position sizing
Signal Sensitivity
Confluence Score Threshold: 40-100 (default: 55 for balanced signals)
Range Filter Period: 25 bars (fast signals for 1-min)
Range Filter Multiplier: 2.2 (tighter bands for more signals)
Visual Controls
Toggle signal table on/off
Show/hide Fibonacci levels
Control EMA visibility
Adjust table text size
Partial Exits
1R: 50% (default)
2R: 30% (default)
3R: 20% (default)
Fully customizable percentages
Trailing Stops
ATR-Based (best for scalping)
Pivot-Based
EMA-Based
Breakeven trigger at 0.8R
🎯 Best Use Cases
Ideal For:
✅ 1-minute scalping on liquid instruments
✅ Day traders looking for quick 2-8 minute trades
✅ High-frequency trading with 8-15 signals per session
✅ Trending markets where Range Filter excels
✅ Crypto, Forex, Futures - works on all liquid assets
Trading Style:
Timeframe: 1-minute (can work on 3-5 min with adjusted settings)
Hold Time: 3-8 minutes average
Target: 1.2-3R per trade
Frequency: 8-15 signals per day
Win Rate: 45-55% (with proper risk management)
📋 How to Use
Step 1: Wait for Signal
Watch for green triangle (BUY) or red triangle (SELL)
Signal table appears at top center automatically
Step 2: Review Confluence
Check grade (prefer A+, A, B+ for best quality)
Review all reasons listed in table
Confirm score is above your threshold (55+ recommended)
Note the R:R ratio
Step 3: Enter Trade
Enter at current market price
Set stop loss at red dashed line
Set take profit at blue dashed line
Mark 1R level (orange line) for partial exit
Step 4: Manage Trade
Exit 50% at 1R (orange line)
Move to breakeven after 0.8R
Trail remaining position using your chosen method
Exit fully at TP or opposite signal
🎨 Chart Setup Recommendations
Optimal Display:
Timeframe: 1-minute
Chart Type: Candles or Heikin Ashi
Background: Dark theme for best color visibility
Volume: Enable volume bars below chart
Complementary Indicators (optional):
Order flow/Delta for institutional confirmation
Market profile for key levels
Economic calendar for news avoidance
⚠️ Important Notes
Risk Disclaimer:
Not financial advice - for educational purposes only
Always use proper risk management (0.5-1% per trade max)
Past performance doesn't guarantee future results
Test on demo account before live trading
Best Practices:
✅ Trade during high liquidity hours (9:30-11 AM, 2-4 PM EST)
✅ Avoid news events and market open/close (first/last 2 minutes)
✅ Use tight stops (0.8-1.0 ATR) for 1-minute scalping
✅ Take partial profits quickly (1R = 50% off)
✅ Respect max daily loss limits (3% recommended)
✅ Focus on A and B grade setups for consistency
What Makes This Different:
🎯 Complete system - not just signals, but full trade management
📊 Multi-confluence - 10+ factors analyzed per trade
🎨 Professional visualization - clean, focused chart design
⚡ Optimized for 1-min - settings specifically tuned for fast scalping
📋 Transparent reasoning - see exactly why each trade was taken
🏆 Grade system - instantly know trade quality
🔧 Technical Details
Pine Script Version: 5
Overlay: Yes (plots on price chart)
Max Lines: 500
Max Labels: 100
Non-repainting: All signals confirmed on bar close
Alerts: Compatible with TradingView alerts
📞 Support & Updates
This indicator is actively maintained and optimized for 1-minute scalping. Settings can be adjusted for different timeframes and trading styles, but default configuration is specifically tuned for high-frequency 1-minute scalping.
🚀 Get Started
Add ProScalper to your 1-minute chart
Adjust settings to your risk tolerance
Wait for signals (green/red triangles)
Follow the signal table guidance
Manage trades using provided levels
Track performance with stats table
Happy Scalping! 📊⚡💰






















