Search in ideas for "Pine Script"
Automated Trading with Pine ScriptIn the digital age, trading is gradually shifting from manual analysis to automated solutions. A key player in this process is Pine Script — a programming language developed for the TradingView platform, enabling users to create custom indicators, strategies, and automated signals. Its simplicity and powerful capabilities have made it especially popular among retail traders.
What is Pine Script?
Pine Script is a language developed by the TradingView team specifically for financial market analysis. Unlike general-purpose languages like Python or C++, Pine Script is designed for tasks related to technical analysis and trading automation.
It is used for:
Creating custom indicators;
Writing trading strategies;
Visualizing data on charts;
Setting up trading alerts (notifications).
Why Automate Trading?
Automated trading eliminates the human factor, which is crucial in volatile markets. Key advantages include:
Speed of reaction — the algorithm reacts instantly to signals.
Discipline — automated strategies do not succumb to emotions.
Scalability — one strategy can be applied to dozens of instruments.
Historical analysis — the ability to test ideas on past data (backtesting).
Structure of a Pine Script
Every script starts with a version declaration and the type of tool being created:
pinescript
Copy
Edit
//@version=5
indicator("Sample Indicator", overlay=true)
@version=5 — Pine Script version.
indicator(...) — indicates that the script is an indicator.
overlay=true — places graphics over the price chart.
For strategies, the strategy keyword is used:
pinescript
Copy
Edit
strategy("My Strategy", overlay=true)
Example of a Simple Automated Strategy
Let’s build a script that generates buy and sell signals based on the crossover of two moving averages:
pinescript
Copy
Edit
//@version=5
strategy("MA Strategy", overlay=true)
fastMA = ta.sma(close, 9)
slowMA = ta.sma(close, 21)
longCondition = ta.crossover(fastMA, slowMA)
shortCondition = ta.crossunder(fastMA, slowMA)
if longCondition
strategy.entry("Buy", strategy.long)
if shortCondition
strategy.entry("Sell", strategy.short)
plot(fastMA, color=color.green)
plot(slowMA, color=color.red)
This code:
Opens a long position when the fast MA crosses above the slow MA.
Opens a short position when the fast MA crosses below the slow MA.
Strategy Backtesting
TradingView automatically runs a backtest on historical data. In the Strategy Tester tab, users get:
total number of trades;
average profit;
win rate;
maximum drawdown;
risk/reward ratio.
This is a vital tool to evaluate the effectiveness of a strategy before deploying it in live trading.
Adding Stop Loss and Take Profit
To manage risk, strategies can include loss and profit limits:
pinescript
Copy
Edit
strategy.entry("Buy", strategy.long)
strategy.exit("Exit Buy", from_entry="Buy", stop=100, limit=200)
stop=100 — stop loss at 100 points.
limit=200 — take profit at 200 points.
This enhances both automation and risk control in the trading process.
Setting Up Alerts
While Pine Script cannot place real trades by itself, it can generate alert signals, which can be linked to external systems or brokers.
pinescript
Copy
Edit
alertcondition(longCondition, title="Buy Signal", message="Buy signal")
alertcondition(shortCondition, title="Sell Signal", message="Sell signal")
After adding these conditions to the chart, users can set up alerts that arrive via email, mobile notifications, or webhooks—useful for integration with bots or APIs.
Automated Trading via API
For full automation (from signal to trade execution), Pine Script is often used in conjunction with other technologies:
Webhook — TradingView sends an HTTP request when an alert triggers.
Server or bot — receives and processes the request, then sends an order to the broker.
Broker’s API — executes the order (open, close, modify positions).
Examples of brokers with API access: Binance, Bybit, Interactive Brokers, Alpaca, MetaTrader (via third-party bridges).
Tips for Writing Trading Strategies
Start simple. Use just 1–2 indicators.
Avoid overfitting. Don’t tailor your strategy too closely to past data.
Test on different timeframes. Ensure strategy stability.
Account for fees and slippage. Especially important on lower timeframes.
Add filters. For example, trend direction, volume, or volatility conditions.
Pine Script Limitations
While powerful and beginner-friendly, Pine Script has some limitations:
No tick-by-tick data access. Scripts execute on bar close.
Resource limits. Limits on script length and processing power.
No direct trade execution. Only possible via external integration or supported brokers.
Conclusion
Pine Script is an excellent tool for traders who want to automate their trading ideas. It allows you to create, test, and visualize strategies—even with minimal programming knowledge. While it’s not a full-fledged programming language, its capabilities are more than sufficient for most retail trading needs. With Pine Script, traders can improve efficiency, consistency, and reduce the emotional impact of trading decisions.
SSS50PercentRule backtesting with PINE scriptsHello Partypeople,
after my last video I was pretty excited that the SSS50PercentRule indicators (video below) show propabilities of greater 60% in 8h charts for USOIL and NATGAS. Trading the tickers the last 2 weeks based on these triggers was no fun... . So I got my self into pine scripting and backtested the SSS50PercentRule on the 8h timeframe using the startegy tab in tradingview....
Last video: see RELATED IDEAS
Playing with the Power of Pine Script # High effort Bitcoin Trash posting
acknowledgements / Credits / Links to Scripts used in this publication :
//---
A Useful MA Weighting Function For Controlling Lag & Smoothness
alexgrover
Nov 2, 2020
Get Ticker Name - JD
Duyck
Aug 20
Pine Color Magic and Chart Theme Simulator
midtownsk8rguy
Sep 7, 2019
Bitcoin S2F(X)
Tainoko
Jul 27
Bitcoin Halving Countdown
Daveatt
Jan 11, 2020
Bitcoin Halving Events
kevindcarr
Sep 29
pinecoders.com/faq_and_code/
tradingview.com/pine-script-docs/en/v5/index.html
//---
trade with tide
take advantage of the waves
ignore the ripples / noise
Investing / Trading : like water
you an scroll and zoom the chart :)
this publication is not financial or trading advice :)
I am an internet cat meme not your financial advisor :)
never invest in a way that would keep you up at night ...
"sideways price action is bullish price action "
INDEX:BTCUSD
Got my new script updated to Pine Script V6I'm all algorithmic trading, well, investing. I use the wealth of data we all have access to. My pine script connects to 3Commas with a rare dynamic volume scaling feature. This means the signals that are sent by this script from TV to 3C are updated with algorithmically-calculated volume scaling. This is not normally possible.
Another positive side effect of a dynamic VS TV 3C connection is you'll gain access to nearly unlimited numbers of safety orders. Also normally not possible.
I will launch bots on BTCUSD, ETHUSD, SOLUSD, and likely a basket of highly volatile assets. I can do stocks, forex, anything on TradingView. I'll be launching bots on all timeframes and diversifying as much as possible!
UPDATED: PINE SCRIPT FOR EMA CROSSINGS UPDATE: I suggest to use the 8 13 41 EMAs they seem to work best for me.
I have now updated the pine script I published a while ago with one of the new features introduced today.
The new script now has a much smaller footprint on your chart, as it now changes the background color according to which EMAs are crossed. The option to change the threshold is now accessible through the 'Inputs' tab when accessing the script settings.
If you like it I would be happy about a small donation.
BTC 1GyfGTBsVHMbPovFGFeipe7b7ET1aebGx5
Questions or Comments? Just send me a PM or post in the comments section below!
UPDATED: Pine script for EMA crossingsI have now updated the pine script I published a while ago with one of the new features introduced today.
The new script now has a much smaller footprint on your chart, as it now changes the background color according to which EMAs are crossed. The option to change the threshold is now accessible through the 'Inputs' tab when accessing the script settings.
If you like it I would be happy about a small donation.
BTC 1GyfGTBsVHMbPovFGFeipe7b7ET1aebGx5
Questions or Comments? Just send me a PM or post in the comments section below!
Any one could help me on the EMV Pine script ?Dear guys, I am new for pine script, could you pls hlep to correct it ?
//@version=4
study("EMV")
kk = sma(volume,14)/volume;
mid =100*((high+low-(high+low) ))/(high+low);
emv = sma(mid*kk*(high-low)/sma(high-low,14),14);
memv = sma(emv,9);
B1 = plot(EMV,color=color.blue)
B2 = plot(MAEMV,color=color.red)
hline(0, color=color.green, title="Zero Line")
Pine Script, KDJ Indicator, FreeThis indicator was originally noted in the tradingview help forums. Noted from "Google's Finance Site," but they use a modified (using EMA instead of traditional SMA) slow stochastic with the %J equation (%J =3 * D – 2 * K ). I can't find any references to the origins of the %J equation, but it is noted in several other online sites.
getsatisfaction.com
So, I've taken the indicator and made some options, upgrades and published it for free!. The basic foundation of the code is still the %J equation. I've included an option to use either the EMA (default) and the SMA (more traditional slow stochastic). You can also adjust the lookback period, %D smoothing, and I've included the option to smooth the %J. This last option slows the indicator down a little, but really cuts out the choppiness of the %J crossings.
Get the source here: pastebin.com
Installation video by @ChrisMoody here : vimeopro.com
Pine Script - Relative Momentum IndicatorThis indicator was developed by Roger Altman and was introduced in the February 1993 issue of "Technical Analysis of Stocks & Commodities" magazine. The RSI was developed by J. Welles Wilder and is discussed in his book "New Concepts in Technical Trading".
Get the source here: pastebin.com
Installation video by @ChrisMoody here : vimeopro.com
After I got done coding this, I saw that www.tradingview.com had already coded the same indicator. Small differences, but same indicator, just want to give credit to a line leader.
Growing uptrend and weekly snapshots collectionPine scripts and drawing, this week.
imgur.com
Aside linked BTC analysis projects:
(Gif albums)
imgur.com
imgur.com
Pine Beginner with Gr8 Script Idea - Script part need helpHi everyone
So before you get to excited - this is only the half of an idea which needs some Pine Scripting polish before I would classify this idea as one to take note of. With that said, if there's someone reading this that is willing to amend the code of my poor attempt to combine 3 scripts together in to 1 rather successful (potentially) algo/auto-trading script which was initially intended to place trades on MT5 for those who are either stuck, to far tied-in or simply stubborn enough to continue using a broker/s that are not listed on TradingView's list of verified brokers.
I must add that I honestly think this script has the potential to be one hellofa successful strategy for any trader who is considering or attempting to learn this fascinating and exciting coding language that can either leave you more confused than blind deaf old man at a psychedelic's rave OR open up a whole new approach of trading that was previously unfathomable yet now with each unique scripts encounter becoming unquestionably clearer that traders who embrace this path can only empower their trading potentials. I think if more opportunistic scripts like this one (once correctly coded by someone who is not as much a rookie as I am - at Pine Script coding not trading) along with some helpful guidelines for traders who have not discovered the wonders that TradingView has to offer any/all traders - that these "aha" types of doorways will be easily flooded with new interest evoked traders to the TradingView world.
But that's just one traders opinion who is looking towards putting this somewhat overly thought concept to test/s and I welcome any of you who wish to do the same, particularly in terms of trying to make heads or tails of my script that in theory makes perfect sense in my mind by using well known trading concepts by those who don't necessarily need to know how to code them in order to use them. However, in this specific case, the knowledge of how to code them has been given the centre front spotlight so feel free to take your shot in it's lime light if you wish. I would most definitely appreciate it and I'm sure you would benefit from the final scripts results as well.
Thanks to any and all who give it a go.
// Here's the script that I feel is best to share - there is a more recent updated version, however, I feel that my scripting skills or lack of may have made that version a great deal more confusing and messy than what this version below is. Hopefully you can see where Im trying to go with it. If not, please don't hesitate to ask and I'll do my best to try clarify where needed.
//
//@version=4
//
// Thanks to dynausmaux falconCoin LazyBear RicardoSantos LucemAnb andreholanda73 for all the scripts I'm using here.
// Special thanks to TradingView for unarguably the best trading platform in the world that facilitates development and learning.
// Before I begin, TAKE NOTE: I'm not an expert trader or pine script coder as such and all the code used here is copied and/or modified from scripts freely found that are published through TradingView.
//
//
// For those of you who actually do look in to the code behind scripts they come accross - here's logic behind all the colorful shapes all over your charts.
//
// CIRCLES & TRIANGLES:
// - LITTLE CIRCLE: They appear at all WaveTrend wave crossings.
// - GREEN CIRCLE: The wavetrend waves are at the oversold level and have crossed up (bullish).
// - RED CIRCLE: The wavetrend waves are at the overbought level and have crossed down (bearish).
// - GOLD/ORANGE CIRCLE: When RSI is below 20, WaveTrend waves are below or equal to -80 and have crossed up after good bullish divergence (DONT BUY WHEN GOLD CIRCLE APPEAR).
// - None of these circles are certain signs to trade. It is only information that can help you.
// - PURPLE TRIANGLE: Appear when a bullish or bearish divergence is formed and WaveTrend waves crosses at overbought and oversold points.
//
// +BEARS/BULLS FLAG:
// - MFI+RSI Area are RED (Below 0).
// - Wavetrend wave above 0 and crossing over down.
// - VWAP Area below 0 on higher timeframe.
// - This pattern reversed becomes bullish.
// +SIDE NOTE: Check the last heikinashi candle from 2 higher timeframe
// - Bearish/Bullish DIAMOND:
// -- HT Candle is red
// -- WT > 0 and crossed down
study(title = 'VuManChu B Divergences', shorttitle = 'VuMan CBD')
// PARAMETERS {
// WaveTrend
wtShow = input(true, title = 'Show WaveTrend', type = input.bool)
wtBuyShow = input(true, title = 'Show Buy dots', type = input.bool)
wtGoldShow = input(true, title = 'Show Gold dots', type = input.bool)
wtSellShow = input(true, title = 'Show Sell dots', type = input.bool)
wtDivShow = input(true, title = 'Show Div. dots', type = input.bool)
vwapShow = input(true, title = 'Show Fast WT', type = input.bool)
wtChannelLen = input(9, title = 'WT Channel Length', type = input.integer)
wtAverageLen = input(12, title = 'WT Average Length', type = input.integer)
wtMASource = input(hlc3, title = 'WT MA Source', type = input.source)
wtMALen = input(3, title = 'WT MA Length', type = input.integer)
// WaveTrend Overbought & Oversold lines
obLevel = input(53, title = 'WT Overbought Level 1', type = input.integer)
obLevel2 = input(60, title = 'WT Overbought Level 2', type = input.integer)
obLevel3 = input(100, title = 'WT Overbought Level 3', type = input.integer)
osLevel = input(-53, title = 'WT Oversold Level 1', type = input.integer)
osLevel2 = input(-60, title = 'WT Oversold Level 2', type = input.integer)
osLevel3 = input(-75, title = 'WT Oversold Level 3', type = input.integer)
// Divergence WT
wtShowDiv = input(true, title = 'Show WT Regular Divergences', type = input.bool)
wtShowHiddenDiv = input(false, title = 'Show WT Hidden Divergences', type = input.bool)
showHiddenDiv_nl = input(true, title = 'Not apply OB/OS Limits on Hidden Divergences', type = input.bool)
wtDivOBLevel = input(45, title = 'WT Bearish Divergence min', type = input.integer)
wtDivOSLevel = input(-65, title = 'WT Bullish Divergence min', type = input.integer)
// Divergence extra range
wtDivOBLevel_addshow = input(true, title = 'Show 2nd WT Regular Divergences', type = input.bool)
wtDivOBLevel_add = input(15, title = 'WT 2nd Bearish Divergence', type = input.integer)
wtDivOSLevel_add = input(-40, title = 'WT 2nd Bullish Divergence 15 min', type = input.integer)
// RSI+MFI
rsiMFIShow = input(true, title = 'Show MFI', type = input.bool)
rsiMFIperiod = input(60,title = 'MFI Period', type = input.integer)
rsiMFIMultiplier = input(150, title = 'MFI Area multiplier', type = input.float)
rsiMFIPosY = input(2.5, title = 'MFI Area Y Pos', type = input.float)
// RSI
rsiShow = input(false, title = 'Show RSI', type = input.bool)
rsiSRC = input(close, title = 'RSI Source', type = input.source)
rsiLen = input(14, title = 'RSI Length', type = input.integer)
rsiOversold = input(30, title = 'RSI Oversold', minval = 50, maxval = 100, type = input.integer)
rsiOverbought = input(60, title = 'RSI Overbought', minval = 0, maxval = 50, type = input.integer)
// Divergence RSI
rsiShowDiv = input(false, title = 'Show RSI Regular Divergences', type = input.bool)
rsiShowHiddenDiv = input(false, title = 'Show RSI Hidden Divergences', type = input.bool)
rsiDivOBLevel = input(60, title = 'RSI Bearish Divergence min', type = input.integer)
rsiDivOSLevel = input(30, title = 'RSI Bullish Divergence min', type = input.integer)
// RSI Stochastic
stochShow = input(true, title = 'Show Stochastic RSI', type = input.bool)
stochUseLog = input(true, title=' Use Log?', type = input.bool)
stochAvg = input(false, title='Use Average of both K & D', type = input.bool)
stochSRC = input(close, title = 'Stochastic RSI Source', type = input.source)
stochLen = input(14, title = 'Stochastic RSI Length', type = input.integer)
stochRsiLen = input(14, title = 'RSI Length ', type = input.integer)
stochKSmooth = input(3, title = 'Stochastic RSI K Smooth', type = input.integer)
stochDSmooth = input(3, title = 'Stochastic RSI D Smooth', type = input.integer)
// Divergence stoch
stochShowDiv = input(false, title = 'Show Stoch Regular Divergences', type = input.bool)
stochShowHiddenDiv = input(false, title = 'Show Stoch Hidden Divergences', type = input.bool)
// Schaff Trend Cycle
tcLine = input(false, title="Show Schaff TC line", type=input.bool)
tcSRC = input(close, title = 'Schaff TC Source', type = input.source)
tclength = input(10, title="Schaff TC", type=input.integer)
tcfastLength = input(23, title="Schaff TC Fast Lenght", type=input.integer)
tcslowLength = input(50, title="Schaff TC Slow Length", type=input.integer)
tcfactor = input(0.5, title="Schaff TC Factor", type=input.float)
// Sommi Flag
sommiFlagShow = input(false, title = 'Show Sommi flag', type = input.bool)
sommiShowVwap = input(false, title = 'Show Sommi F. Wave', type = input.bool)
sommiVwapTF = input('720', title = 'Sommi F. Wave timeframe', type = input.string)
sommiVwapBearLevel = input(0, title = 'F. Wave Bear Level (less than)', type = input.integer)
sommiVwapBullLevel = input(0, title = 'F. Wave Bull Level (more than)', type = input.integer)
soomiFlagWTBearLevel = input(0, title = 'WT Bear Level (more than)', type = input.integer)
soomiFlagWTBullLevel = input(0, title = 'WT Bull Level (less than)', type = input.integer)
soomiRSIMFIBearLevel = input(0, title = 'Money flow Bear Level (less than)', type = input.integer)
soomiRSIMFIBullLevel = input(0, title = 'Money flow Bull Level (more than)', type = input.integer)
// Sommi Diamond
sommiDiamondShow = input(false, title = 'Show Sommi diamond', type = input.bool)
sommiHTCRes = input('60', title = 'HTF Candle Res. 1', type = input.string)
sommiHTCRes2 = input('240', title = 'HTF Candle Res. 2', type = input.string)
soomiDiamondWTBearLevel = input(0, title = 'WT Bear Level (More than)', type = input.integer)
soomiDiamondWTBullLevel = input(0, title = 'WT Bull Level (Less than)', type = input.integer)
// macd Colors
macdWTColorsShow = input(false, title = 'Show MACD Colors', type = input.bool)
macdWTColorsTF = input('240', title = 'MACD Colors MACD TF', type = input.string)
darkMode = input(false, title = 'Dark mode', type = input.bool)
// Colors
colorRed = #ff0000
colorPurple = #e600e6
colorGreen = #3fff00
colorOrange = #e2a400
colorYellow = #ffe500
colorWhite = #ffffff
colorPink = #ff00f0
colorBluelight = #31c0ff
colorWT1 = #90caf9
colorWT2 = #0d47a1
colorWT2_ = #131722
colormacdWT1a = #4caf58
colormacdWT1b = #af4c4c
colormacdWT1c = #7ee57e
colormacdWT1d = #ff3535
colormacdWT2a = #305630
colormacdWT2b = #310101
colormacdWT2c = #132213
colormacdWT2d = #770000
// } PARAMETERS
// FUNCTIONS {
// Divergences
f_top_fractal(src) => src < src and src < src and src > src and src > src
f_bot_fractal(src) => src > src and src > src and src < src and src < src
f_fractalize(src) => f_top_fractal(src) ? 1 : f_bot_fractal(src) ? -1 : 0
f_findDivs(src, topLimit, botLimit, useLimits) =>
fractalTop = f_fractalize(src) > 0 and (useLimits ? src >= topLimit : true) ? src : na
fractalBot = f_fractalize(src) < 0 and (useLimits ? src <= botLimit : true) ? src : na
highPrev = valuewhen(fractalTop, src , 0)
highPrice = valuewhen(fractalTop, high , 0)
lowPrev = valuewhen(fractalBot, src , 0)
lowPrice = valuewhen(fractalBot, low , 0)
bearSignal = fractalTop and high > highPrice and src < highPrev
bullSignal = fractalBot and low < lowPrice and src > lowPrev
bearDivHidden = fractalTop and high < highPrice and src > highPrev
bullDivHidden = fractalBot and low > lowPrice and src < lowPrev
// RSI+MFI
f_rsimfi(_period, _multiplier, _tf) => security(syminfo.tickerid, _tf, sma(((close - open) / (high - low)) * _multiplier, _period) - rsiMFIPosY)
// WaveTrend
f_wavetrend(src, chlen, avg, malen, tf) =>
tfsrc = security(syminfo.tickerid, tf, src)
esa = ema(tfsrc, chlen)
de = ema(abs(tfsrc - esa), chlen)
ci = (tfsrc - esa) / (0.015 * de)
wt1 = security(syminfo.tickerid, tf, ema(ci, avg))
wt2 = security(syminfo.tickerid, tf, sma(wt1, malen))
wtVwap = wt1 - wt2
wtOversold = wt2 <= osLevel
wtOverbought = wt2 >= obLevel
wtCross = cross(wt1, wt2)
wtCrossUp = wt2 - wt1 <= 0
wtCrossDown = wt2 - wt1 >= 0
wtCrosslast = cross(wt1 , wt2 )
wtCrossUplast = wt2 - wt1 <= 0
wtCrossDownlast = wt2 - wt1 >= 0
// Schaff Trend Cycle
f_tc(src, length, fastLength, slowLength) =>
ema1 = ema(src, fastLength)
ema2 = ema(src, slowLength)
macdVal = ema1 - ema2
alpha = lowest(macdVal, length)
beta = highest(macdVal, length) - alpha
gamma = (macdVal - alpha) / beta * 100
gamma := beta > 0 ? gamma : nz(gamma )
delta = gamma
delta := na(delta ) ? delta : delta + tcfactor * (gamma - delta )
epsilon = lowest(delta, length)
zeta = highest(delta, length) - epsilon
eta = (delta - epsilon) / zeta * 100
eta := zeta > 0 ? eta : nz(eta )
stcReturn = eta
stcReturn := na(stcReturn ) ? stcReturn : stcReturn + tcfactor * (eta - stcReturn )
stcReturn
// Stochastic RSI
f_stochrsi(_src, _stochlen, _rsilen, _smoothk, _smoothd, _log, _avg) =>
src = _log ? log(_src) : _src
rsi = rsi(src, _rsilen)
kk = sma(stoch(rsi, rsi, rsi, _stochlen), _smoothk)
d1 = sma(kk, _smoothd)
avg_1 = avg(kk, d1)
k = _avg ? avg_1 : kk
// MACD
f_macd(src, fastlen, slowlen, sigsmooth, tf) =>
fast_ma = security(syminfo.tickerid, tf, ema(src, fastlen))
slow_ma = security(syminfo.tickerid, tf, ema(src, slowlen))
macd = fast_ma - slow_ma,
signal = security(syminfo.tickerid, tf, sma(macd, sigsmooth))
hist = macd - signal
// MACD Colors on WT
f_macdWTColors(tf) =>
hrsimfi = f_rsimfi(rsiMFIperiod, rsiMFIMultiplier, tf)
= f_macd(close, 28, 42, 9, macdWTColorsTF)
macdup = macd >= signal
macddown = macd <= signal
macdWT1Color = macdup ? hrsimfi > 0 ? colormacdWT1c : colormacdWT1a : macddown ? hrsimfi < 0 ? colormacdWT1d : colormacdWT1b : na
macdWT2Color = macdup ? hrsimfi < 0 ? colormacdWT2c : colormacdWT2a : macddown ? hrsimfi < 0 ? colormacdWT2d : colormacdWT2b : na
// Get higher timeframe candle
f_getTFCandle(_tf) =>
_open = security(heikinashi(syminfo.tickerid), _tf, open, barmerge.gaps_off, barmerge.lookahead_on)
_close = security(heikinashi(syminfo.tickerid), _tf, close, barmerge.gaps_off, barmerge.lookahead_on)
_high = security(heikinashi(syminfo.tickerid), _tf, high, barmerge.gaps_off, barmerge.lookahead_on)
_low = security(heikinashi(syminfo.tickerid), _tf, low, barmerge.gaps_off, barmerge.lookahead_on)
hl2 = (_high + _low) / 2.0
newBar = change(_open)
candleBodyDir = _close > _open
// Sommi flag
f_findSommiFlag(tf, wt1, wt2, rsimfi, wtCross, wtCrossUp, wtCrossDown) =>
= f_wavetrend(wtMASource, wtChannelLen, wtAverageLen, wtMALen, tf)
bearPattern = rsimfi < soomiRSIMFIBearLevel and
wt2 > soomiFlagWTBearLevel and
wtCross and
wtCrossDown and
hwtVwap < sommiVwapBearLevel
bullPattern = rsimfi > soomiRSIMFIBullLevel and
wt2 < soomiFlagWTBullLevel and
wtCross and
wtCrossUp and
hwtVwap > sommiVwapBullLevel
f_findSommiDiamond(tf, tf2, wt1, wt2, wtCross, wtCrossUp, wtCrossDown) =>
= f_getTFCandle(tf)
= f_getTFCandle(tf2)
bearPattern = wt2 >= soomiDiamondWTBearLevel and
wtCross and
wtCrossDown and
not candleBodyDir and
not candleBodyDir2
bullPattern = wt2 <= soomiDiamondWTBullLevel and
wtCross and
wtCrossUp and
candleBodyDir and
candleBodyDir2
// } FUNCTIONS
// CALCULATE INDICATORS {
// RSI
rsi = rsi(rsiSRC, rsiLen)
rsiColor = rsi <= rsiOversold ? colorGreen : rsi >= rsiOverbought ? colorRed : colorPurple
// RSI + MFI Area
rsiMFI = f_rsimfi(rsiMFIperiod, rsiMFIMultiplier, timeframe.period)
rsiMFIColor = rsiMFI > 0 ? #3ee145 : #ff3d2e
// Calculates WaveTrend
= f_wavetrend(wtMASource, wtChannelLen, wtAverageLen, wtMALen, timeframe.period)
// Stochastic RSI
= f_stochrsi(stochSRC, stochLen, stochRsiLen, stochKSmooth, stochDSmooth, stochUseLog, stochAvg)
// Schaff Trend Cycle
tcVal = f_tc(tcSRC, tclength, tcfastLength, tcslowLength)
// Sommi flag
= f_findSommiFlag(sommiVwapTF, wt1, wt2, rsiMFI, wtCross, wtCrossUp, wtCrossDown)
//Sommi diamond
= f_findSommiDiamond(sommiHTCRes, sommiHTCRes2, wt1, wt2, wtCross, wtCrossUp, wtCrossDown)
// macd colors
= f_macdWTColors(macdWTColorsTF)
// WT Divergences
= f_findDivs(wt2, wtDivOBLevel, wtDivOSLevel, true)
= f_findDivs(wt2, wtDivOBLevel_add, wtDivOSLevel_add, true)
= f_findDivs(wt2, 0, 0, false)
wtBearDivHidden_ = showHiddenDiv_nl ? wtBearDivHidden_nl : wtBearDivHidden
wtBullDivHidden_ = showHiddenDiv_nl ? wtBullDivHidden_nl : wtBullDivHidden
wtBearDivColor = (wtShowDiv and wtBearDiv) or (wtShowHiddenDiv and wtBearDivHidden_) ? colorRed : na
wtBullDivColor = (wtShowDiv and wtBullDiv) or (wtShowHiddenDiv and wtBullDivHidden_) ? colorGreen : na
wtBearDivColor_add = (wtShowDiv and (wtDivOBLevel_addshow and wtBearDiv_add)) or (wtShowHiddenDiv and (wtDivOBLevel_addshow and wtBearDivHidden_add)) ? #9a0202 : na
wtBullDivColor_add = (wtShowDiv and (wtDivOBLevel_addshow and wtBullDiv_add)) or (wtShowHiddenDiv and (wtDivOBLevel_addshow and wtBullDivHidden_add)) ? #1b5e20 : na
// RSI Divergences
= f_findDivs(rsi, rsiDivOBLevel, rsiDivOSLevel, true)
= f_findDivs(rsi, 0, 0, false)
rsiBearDivHidden_ = showHiddenDiv_nl ? rsiBearDivHidden_nl : rsiBearDivHidden
rsiBullDivHidden_ = showHiddenDiv_nl ? rsiBullDivHidden_nl : rsiBullDivHidden
rsiBearDivColor = (rsiShowDiv and rsiBearDiv) or (rsiShowHiddenDiv and rsiBearDivHidden_) ? colorRed : na
rsiBullDivColor = (rsiShowDiv and rsiBullDiv) or (rsiShowHiddenDiv and rsiBullDivHidden_) ? colorGreen : na
// Stoch Divergences
= f_findDivs(stochK, 0, 0, false)
stochBearDivColor = (stochShowDiv and stochBearDiv) or (stochShowHiddenDiv and stochBearDivHidden) ? colorRed : na
stochBullDivColor = (stochShowDiv and stochBullDiv) or (stochShowHiddenDiv and stochBullDivHidden) ? colorGreen : na
// Small Circles WT Cross
signalColor = wt2 - wt1 > 0 ? color.red : color.lime
// Buy signal.
buySignal = wtCross and wtCrossUp and wtOversold
buySignalDiv = (wtShowDiv and wtBullDiv) or
(wtShowDiv and wtBullDiv_add) or
(stochShowDiv and stochBullDiv) or
(rsiShowDiv and rsiBullDiv)
buySignalDiv_color = wtBullDiv ? colorGreen :
wtBullDiv_add ? color.new(colorGreen, 60) :
rsiShowDiv ? colorGreen : na
// Sell signal
sellSignal = wtCross and wtCrossDown and wtOverbought
sellSignalDiv = (wtShowDiv and wtBearDiv) or
(wtShowDiv and wtBearDiv_add) or
(stochShowDiv and stochBearDiv) or
(rsiShowDiv and rsiBearDiv)
sellSignalDiv_color = wtBearDiv ? colorRed :
wtBearDiv_add ? color.new(colorRed, 60) :
rsiBearDiv ? colorRed : na
// Gold Buy
lastRsi = valuewhen(wtFractalBot, rsi , 0)
wtGoldBuy = ((wtShowDiv and wtBullDiv) or (rsiShowDiv and rsiBullDiv)) and
wtLow_prev <= osLevel3 and
wt2 > osLevel3 and
wtLow_prev - wt2 <= -5 and
lastRsi < 30
// } CALCULATE INDICATORS
// DRAW {
bgcolor(darkMode ? color.new(#000000, 80) : na)
zLine = plot(0, color = color.new(colorWhite, 50))
// MFI BAR
rsiMfiBarTopLine = plot(rsiMFIShow ? -95 : na, title = 'MFI Bar TOP Line', transp = 100)
rsiMfiBarBottomLine = plot(rsiMFIShow ? -99 : na, title = 'MFI Bar BOTTOM Line', transp = 100)
fill(rsiMfiBarTopLine, rsiMfiBarBottomLine, title = 'MFI Bar Colors', color = rsiMFIColor, transp = 75)
// WT Areas
plot(wtShow ? wt1 : na, style = plot.style_area, title = 'WT Wave 1', color = macdWTColorsShow ? macdWT1Color : colorWT1, transp = 0)
plot(wtShow ? wt2 : na, style = plot.style_area, title = 'WT Wave 2', color = macdWTColorsShow ? macdWT2Color : darkMode ? colorWT2_ : colorWT2 , transp = 20)
// VWAP
plot(vwapShow ? wtVwap : na, title = 'VWAP', color = colorYellow, style = plot.style_area, linewidth = 2, transp = 45)
// MFI AREA
rsiMFIplot = plot(rsiMFIShow ? rsiMFI: na, title = 'RSI+MFI Area', color = rsiMFIColor, transp = 20)
fill(rsiMFIplot, zLine, rsiMFIColor, transp = 40)
// WT Div
plot(series = wtFractalTop ? wt2 : na, title = 'WT Bearish Divergence', color = wtBearDivColor, linewidth = 2, offset = -2)
plot(series = wtFractalBot ? wt2 : na, title = 'WT Bullish Divergence', color = wtBullDivColor, linewidth = 2, offset = -2)
// WT 2nd Div
plot(series = wtFractalTop_add ? wt2 : na, title = 'WT 2nd Bearish Divergence', color = wtBearDivColor_add, linewidth = 2, offset = -2)
plot(series = wtFractalBot_add ? wt2 : na, title = 'WT 2nd Bullish Divergence', color = wtBullDivColor_add, linewidth = 2, offset = -2)
// RSI
plot(rsiShow ? rsi : na, title = 'RSI', color = rsiColor, linewidth = 2, transp = 25)
// RSI Div
plot(series = rsiFractalTop ? rsi : na, title='RSI Bearish Divergence', color = rsiBearDivColor, linewidth = 1, offset = -2)
plot(series = rsiFractalBot ? rsi : na, title='RSI Bullish Divergence', color = rsiBullDivColor, linewidth = 1, offset = -2)
// Stochastic RSI
stochKplot = plot(stochShow ? stochK : na, title = 'Stoch K', color = color.new(#21baf3, 0), linewidth = 2)
stochDplot = plot(stochShow ? stochD : na, title = 'Stoch D', color = color.new(#673ab7, 60), linewidth = 1)
stochFillColor = stochK >= stochD ? color.new(#21baf3, 75) : color.new(#673ab7, 60)
fill(stochKplot, stochDplot, title='KD Fill', color=stochFillColor)
// Stoch Div
plot(series = stochFractalTop ? stochK : na, title='Stoch Bearish Divergence', color = stochBearDivColor, linewidth = 1, offset = -2)
plot(series = stochFractalBot ? stochK : na, title='Stoch Bullish Divergence', color = stochBullDivColor, linewidth = 1, offset = -2)
// Schaff Trend Cycle
plot(tcLine ? tcVal : na, color = color.new(#673ab7, 25), linewidth = 2, title = "Schaff Trend Cycle 1")
plot(tcLine ? tcVal : na, color = color.new(colorWhite, 50), linewidth = 1, title = "Schaff Trend Cycle 2")
// Draw Overbought & Oversold lines
//plot(obLevel, title = 'Over Bought Level 1', color = colorWhite, linewidth = 1, style = plot.style_circles, transp = 85)
plot(obLevel2, title = 'Over Bought Level 2', color = colorWhite, linewidth = 1, style = plot.style_stepline, transp = 85)
plot(obLevel3, title = 'Over Bought Level 3', color = colorWhite, linewidth = 1, style = plot.style_circles, transp = 95)
//plot(osLevel, title = 'Over Sold Level 1', color = colorWhite, linewidth = 1, style = plot.style_circles, transp = 85)
plot(osLevel2, title = 'Over Sold Level 2', color = colorWhite, linewidth = 1, style = plot.style_stepline, transp = 85)
// Sommi flag
plotchar(sommiFlagShow and sommiBearish ? 108 : na, title = 'Sommi bearish flag', char='⚑', color = colorPink, location = location.absolute, size = size.tiny, transp = 0)
plotchar(sommiFlagShow and sommiBullish ? -108 : na, title = 'Sommi bullish flag', char='⚑', color = colorBluelight, location = location.absolute, size = size.tiny, transp = 0)
plot(sommiShowVwap ? ema(hvwap, 3) : na, title = 'Sommi higher VWAP', color = colorYellow, linewidth = 2, style = plot.style_line, transp = 15)
// Sommi diamond
plotchar(sommiDiamondShow and sommiBearishDiamond ? 108 : na, title = 'Sommi bearish diamond', char='◆', color = colorPink, location = location.absolute, size = size.tiny, transp = 0)
plotchar(sommiDiamondShow and sommiBullishDiamond ? -108 : na, title = 'Sommi bullish diamond', char='◆', color = colorBluelight, location = location.absolute, size = size.tiny, transp = 0)
// Circles
plot(wtCross ? wt2 : na, title = 'Buy and sell circle', color = signalColor, style = plot.style_circles, linewidth = 3, transp = 15)
plotchar(wtBuyShow and buySignal ? -107 : na, title = 'Buy circle', char='·', color = colorGreen, location = location.absolute, size = size.small, transp = 50)
plotchar(wtSellShow and sellSignal ? 105 : na , title = 'Sell circle', char='·', color = colorRed, location = location.absolute, size = size.small, transp = 50)
plotchar(wtDivShow and buySignalDiv ? -106 : na, title = 'Divergence buy circle', char='•', color = buySignalDiv_color, location = location.absolute, size = size.small, offset = -2, transp = 15)
plotchar(wtDivShow and sellSignalDiv ? 106 : na, title = 'Divergence sell circle', char='•', color = sellSignalDiv_color, location = location.absolute, size = size.small, offset = -2, transp = 15)
plotchar(wtGoldBuy and wtGoldShow ? -106 : na, title = 'Gold buy gold circle', char='•', color = colorOrange, location = location.absolute, size = size.small, offset = -2, transp = 15)
// } DRAW
// ALERTS {
// BUY
alertcondition(buySignal, 'Buy (Big green circle)', 'Green circle WaveTrend Oversold')
alertcondition(buySignalDiv, 'Buy (Big green circle + Div)', 'Buy & WT Bullish Divergence & WT Overbought')
alertcondition(wtGoldBuy, 'GOLD Buy (Big GOLDEN circle)', 'Green & GOLD circle WaveTrend Overbought')
alertcondition(sommiBullish or sommiBullishDiamond, 'Sommi bullish flag/diamond', 'Blue flag/diamond')
alertcondition(wtCross and wtCrossUp, 'Buy (Small green dot)', 'Buy small circle')
// SELL
alertcondition(sommiBearish or sommiBearishDiamond, 'Sommi bearish flag/diamond', 'Purple flag/diamond')
alertcondition(sellSignal, 'Sell (Big red circle)', 'Red Circle WaveTrend Overbought')
alertcondition(sellSignalDiv, 'Sell (Big red circle + Div)', 'Buy & WT Bearish Divergence & WT Overbought')
alertcondition(wtCross and wtCrossDown, 'Sell (Small red dot)', 'Sell small circle')
// } ALERTS
How to Identify a Head and Shoulders Pattern on TradingViewTo effectively trade the head and shoulders pattern, there are a few factors to consider. If you don’t have an Alpaca account but have a TradingView account, you can sign up for an Alpaca account.
Multiple Time Frame Analysis
Analyze the chart on different time frames—such as 4-hour, daily, and weekly—to get a complete view of the broader trend. If the weekly chart indicates a downtrend while the 4-hour chart shows an uptrend, it may be premature or risky to interpret price action as a head and shoulders pattern. Aligning trends across time frames generally increases the reliability of your findings.
In the image below, using Broadcom, Inc (AVGO) stock chart, the weekly chart shows a well-established uptrend, indicating bullish market sentiment. On the daily chart, an inverse head and shoulders pattern forms along the upward trend line. The 4-hour chart reveals another inverse head and shoulders setup on a smaller scale. Confirming this bullish structure across multiple time frames may increase a traders’ confidence in a continued uptrend, rather than relying on a single chart interval.
NOTE: "AVGO" is used for demonstration purposes and should not be considered investment advice.
Break of Swing High and Swing Low
Pay attention to recent swing points to confirm the pattern. In a standard head and shoulders formation, a decisive break below the neckline (often aligning with a previous swing low) typically validates the pattern. Conversely, in an inverse head and shoulders, a break above the neckline confirms a bullish reversal. Observing retests of the neckline can further strengthen your confirmation and help refine entry or exit points.
Use of Additional Technical Indicators
Supplement your visual analysis with a few simple indicators to strengthen your signal confirmation and filter out false moves:
Moving Averages (MA) : Use simple or exponential moving averages (such as a 20-day EMA and a 50-day SMA) to gauge overall trend direction. A crossover where the short-term MA moves above the long-term MA supports an uptrend, and vice versa.
Bollinger Bands : Look at Bollinger Bands to assess volatility and identify overbought or oversold conditions. If the price approaches or breaks out of these bands, it can signal a potential reversal or continuation, adding context to your swing points.
Moving Average Convergence Divergence (MACD) : Monitor the MACD to spot momentum shifts. If the MACD lines diverge from the price action, it might indicate that a breakout is less reliable.
Attached is an image showing the head and shoulders pattern on AVGO stock with the MACD (12,26) displayed below. The MACD enhances the analysis by confirming momentum: a bullish crossover and expanding histogram support the pattern's validity, while divergence, such as flat or declining momentum despite rising prices, warns of a possible false breakout.
TradingView Implementation: Coding the Head and Shoulders Pattern with Pine Script
TradingView is a widely used platform that offers advanced charting tools and a scripting language called Pine Script. The head and shoulders pattern, being a powerful reversal indicator, can be detected automatically using a custom indicator with a Pine Script.
Let's explore how to implement this using the example:
Setting Up the Detection System
The example Pine Script indicator below automatically highlights both traditional head and shoulders (bearish) and inverse head and shoulders (bullish) patterns on any chart. As shown in the screenshot, the indicator successfully detected inverse head and shoulders patterns on both 4-hour and daily timeframes, coinciding with an uptrend on the weekly chart.
Understanding the Pine Script Code
The script begins by declaring version 6 compatibility and creating an overlay indicator. The leftbars and rightbars parameters allow traders to adjust the sensitivity of the pattern detection—smaller values detect shorter-term patterns while larger values find longer-term formations.
//@version=6
indicator("Head & Shoulders", overlay=true)
// Input parameters
leftbars = input.int(4, title="Left Bars")
rightbars = input.int(4, title="Right Bars")
The core of the detection relies on identifying pivot points—local highs and lows that form the shoulders and head of the pattern.
// Find pivot points
ph = ta.pivothigh(rightbars, leftbars)
pl = ta.pivotlow(rightbars, leftbars)
For the inverse head and shoulders (bullish pattern), the script checks if:
The right shoulder low is higher than the head low (condi1)
The head low is lower than the left shoulder low (condi2)
When both conditions are met, a purple background highlights the pattern.
// Bullish (Inverse) Head and Shoulders pattern detection
condi1 = ta.valuewhen(na(pl) == false, pl, 0) > ta.valuewhen(na(pl ) == false, pl , 0) ? 1 : 0
condi2 = ta.valuewhen(na(pl ) == false, pl , 0) < ta.valuewhen(na(pl ) == false, pl , 2) ? 1 : 0
colorbull = condi1 == 1 and condi2 == 1
Similarly, for the traditional head and shoulders (bearish pattern), the script verifies if:
The right shoulder high is lower than the head high (condi3)
The head high is higher than the left shoulder high (condi4)
When detected, a gold background highlights this bearish pattern.
// Bearish Head and Shoulders pattern detection
condi3 = ta.valuewhen(na(ph) == false, ph, 0) < ta.valuewhen(na(ph ) == false, ph , 0) ? 1 : 0
condi4 = ta.valuewhen(na(ph ) == false, ph , 0) > ta.valuewhen(na(ph ) == false, ph , 2) ? 1 : 0
colorbear = condi3 == 1 and condi4 == 1
Visual Indicators and Alerts
The indicator uses distinct visual cues:
Purple background (#7331FF) with an upward arrow (↗) for bullish patterns
Gold background (#EBC003) with a downward arrow (↘) for bearish patterns
These visual markers make it easy to spot patterns across multiple timeframes, as demonstrated in the screenshot where inverse head and shoulders patterns appear on both 4-hour and daily charts.
// Background colors for pattern visualization
bgcolor(colorbull ? color.new(#7331FF, 50) : na, title="Bullish H&S", offset=-leftbars)
bgcolor(colorbear ? color.new(#EBC003, 50) : na, title="Bearish H&S", offset=-leftbars)
// Alert signals
plotchar(colorbull, title="Bullish H&S", char="↗", location=location.belowbar, color=color.new(#7331FF, 0))
plotchar(colorbear, title="Bearish H&S", char="↘", location=location.abovebar, color=color.new(#EBC003, 0))
Setting Up Trading Alerts
The script includes three alert conditions that can notify traders when:
A bullish (inverse) head and shoulders forms
A bearish head and shoulders forms
Either pattern appears
This allows traders to receive timely notifications without constant chart monitoring.
As seen in the screenshot above, this indicator successfully highlighted multiple inverse head and shoulders patterns that aligned with a broader uptrend, demonstrating its effectiveness as a trend confirmation tool when used across multiple timeframes.
// Alert conditions
alertcondition(colorbull, title="Bullish H&S Detected", message="Bullish Head and Shoulders Pattern Detected")
alertcondition(colorbear, title="Bearish H&S Detected", message="Bearish Head and Shoulders Pattern Detected")
alertcondition(colorbear or colorbull, title="H&S Signal", message="Head and Shoulders Pattern Detected")
The head and shoulders pattern is a fundamental tool in technical analysis, offering insights into potential trend reversals. By understanding its structure, variations, and the context in which it appears, traders can make more informed decisions.
While the pattern often provides valuable signals, it's essential to consider its limitations and corroborate findings with additional technical indicators and thorough analysis. Combining theoretical knowledge with practical application on platforms like TradingView and Alpaca can enhance one's trading strategy and execution.
=====================================================================
Disclosure
Alpaca and TradingView are not affiliated and neither are responsible for the liabilities of the other.
All investments involve risk, and the past performance of a security, or financial product does not guarantee future results or returns. There is no guarantee that any investment strategy will achieve its objectives. Please note that diversification does not ensure a profit, or protect against loss. There is always the potential of losing money when you invest in securities, or other financial products. Investors should consider their investment objectives and risks carefully before investing.
Securities brokerage services are provided by Alpaca Securities LLC ("Alpaca Securities"), member FINRA / SIPC , a wholly-owned subsidiary of AlpacaDB, Inc. Technology and services are offered by AlpacaDB, Inc.
Cryptocurrency services are made available by Alpaca Crypto LLC ("Alpaca Crypto"), a FinCEN registered money services business (NMLS # 2160858), and a wholly-owned subsidiary of AlpacaDB, Inc. Alpaca Crypto is not a member of SIPC or FINRA. Cryptocurrencies are not stocks and your cryptocurrency investments are not protected by either FDIC or SIPC. Please see the Disclosure Library for more information.
Cryptocurrency is highly speculative in nature, involves a high degree of risks, such as volatile market price swings, market manipulation, flash crashes, and cybersecurity risks. Cryptocurrency regulations are continuously evolving, and it is your responsibility to understand and abide by them. Cryptocurrency trading can lead to large, immediate and permanent loss of financial value. You should have appropriate knowledge and experience before engaging in cryptocurrency trading. For additional information, please click here .
This is not an offer, solicitation of an offer, or advice to buy or sell securities or cryptocurrencies or open a brokerage account or cryptocurrency account in any jurisdiction where Alpaca Securities or Alpaca Crypto, respectively, are not registered or licensed, as applicable.
Please note that this article is for general informational purposes only and is believed to be accurate as of the posting date, but may be subject to change. The examples above are for illustrative purposes only. All examples are for illustrative purposes only.
Past hypothetical backtest results do not guarantee future returns, and actual results may vary from the analysis.
The Paper Trading API is offered by AlpacaDB, Inc. and does not require real money or permit a user to transact in real securities in the market. Providing use of the Paper Trading API is not an offer or solicitation to buy or sell securities, securities derivative or futures products of any kind, or any type of trading or investment advice, recommendation or strategy, given or in any manner endorsed by AlpacaDB, Inc. or any AlpacaDB, Inc. affiliate and the information made available through the Paper Trading API is not an offer or solicitation of any kind in any jurisdiction where AlpacaDB, Inc. or any AlpacaDB, Inc. affiliate (collectively, “Alpaca”) is not authorized to do business.
Alpaca is not affiliated with this third-party website, which is not actively monitored by us. We do not review or update content here regularly and are not responsible for user comments or third-party content. For full disclosures, visit: alpaca.markets/disclosures
How to use pandas_ta library to build R-Breaker indicatorToday is the first day of 2022. I hereby wish all my friends a smooth transaction in the new year, and your account will be N times profitable.
The reason why I write this article is not to simply introduce the R-Breaker strategy itself. I think many of my friends may have used this strategy for intraday short-term trading operations. And I hope to use this case to introduce how to use the pandas_ta library I just released for indicator and strategy design.
Many friends who are familiar with Python may find: Is the pandas_ta library not an open source library for Python? How can it be directly used in Tradingview? In fact, I spent some time and energy to convert the Python version of the pandas_ta library file into Tradingview's Pine v5 script, and used the latest library functions released in v5 to encapsulate most of the functions.
The pandas_ta library is a public library file containing functions that can be reused in Pine indicators, strategies or other libraries. They are useful for defining commonly used functions, so their source code does not have to be included in every script that requires them. The pandas_ta library is a public and open source Pine script library, so it is referenced in another script. In fact, according to Tradingview's release policy, all libraries must be released as open source before they can be publicly cited. In other words, public scripts can only use public libraries, and they must be open source. Private or personal scripts saved in the Pine editor can use public or private libraries. A library can use other libraries, or even its own previous version (Tradingview requires that the version number of the library must be noted when importing).
If you want to use the pandas_ta library, it is done through the import statement in the following format:
import //
Among them, the path // will uniquely identify the library. must be specified explicitly. In order to ensure the reliability of scripts that use the library, there is no way to automatically use the latest version of the library. Each time the author of the library updates, its version number will increase. If you plan to use the latest version of the library, you need to update the value in the import statement. The as part is optional. When used, it defines the namespace that will reference library functions. For example, if you import a library using the allTime alias as we did in the example below, you would call the library's function allTime.(). When no alias is defined, the name of the library becomes its namespace. To use the panadas_ta library, our script will need an import statement:
import blackcat1402/pandas_ta/2 as pta
The above is an introduction to the usage of the Tradingview library. Next, let me talk about the realization of the intraday short-term strategy R-Breaker.
The R-Breaker strategy is a short-term intraday trading strategy that combines trend and reversal trading methods. High, Close and Low PreClose are respectively the highest price of the current K-line, the closing price of the current K-line, the lowest price of the current K-line and the closing price of yesterday. Through these prices, a pivot point (Pivot Point) can be set, and many people in China also refer to it as the "pocket pivot." With the "pocket pivot", we can calculate the support and resistance levels for buying and selling. They are:
-Breakthrough buying price = Observing selling price + 0.25 * (Observing selling price-Observing buying price)
-Observe the selling price = High + 0.35 * (Close – Low)
-Reversal selling price = 1.07 / 2 * (High + Low) – 0.07 * Low
-Reversal buying price = 1.07 / 2 * (High + Low) – 0.07 * High
-Observe the buying price = Low – 0.35 * (High – Close)
-Breakthrough selling price = Observing the buying price-0.25 * (Observing the selling price-Observing the buying price)
R-Breaker trading strategy details:
-1) When the intraday highest price exceeds the observed selling price, and the intraday price falls back and further breaks below the support line constituted by the reversal selling price, a reversal strategy is adopted, that is, at this point (backhand, open position) ) Short;
-2) When the intraday lowest price is lower than the observed purchase price, and the intraday price rebounds and further exceeds the resistance line constituted by the reverse purchase price, a reversal strategy is adopted, that is, at this point (backhand, open position) ) Long;
-3) In the case of a short position, if the intraday price exceeds the breakthrough buying price, a trend strategy is adopted, that is, open a long position at that point;
-4) In the case of a short position, if the intraday price breaks below the selling price, a trend strategy is adopted, that is, open a short position at that point.
R-Breaker indicator usage
-Generally used in short periods such as minute periods (I generally use 30 minutes and 1 hour periods, taking into account the response speed and stability), or the T+0 varieties with strong shares.
-It is best to perform double verification based on other indicators such as volume, price, market, and sector.
-The green label B is for early warning and buying.
-The red S label is short warning and sell.
Use pandas_ta library file to build R-Breaker
At the beginning of script writing, you need to use import to import the pandas_ta library, as follows:
//@version=5
indicator(" L2 Intraday R-Breaker Indicator", overlay = true)
import blackcat1402/pandas_ta/2 as pta
After naming the pandas_ta library as pta, you need to use "pta." as the prefix when referencing functions in it, for example:
preclose = callsec(syminfo.tickerid, "D", close, false)
nn = ta.barssince(dayofmonth!=pta.xrf(dayofmonth,1))+1
hh = pta.xrf(pta.xhh(high,nn),nn)
ll = pta.xrf(pta.xll(low,nn),nn)
Do not use pta.xrf, pta.xll, pta.xhh to reference the functions in the pandas_ta library.
In summary, this is the whole content of the tutorial. The tradingview library is very convenient to use, which can greatly improve coding efficiency and focus on the development of core strategies.
Best Editors' Picks of 2023We present our awards for the best Editors' Picks of 2023! This marks our second year of recognizing outstanding open-source Community scripts. From the 84 picks in 2023, our PineCoders have cast their votes, highlighting three exceptional indicator scripts and one outstanding library. Each author of these noteworthy entries will receive 100,000 TradingView coins.
The awardees:
• Intrabar Analyzer by KioseffTrading
• Machine Learning: Lorentzian Classification by jdehorty
• Harmonic Patterns Based Trend Follower by Trendoscope
• SimilarityMeasures by RicardoSantos
Congratulations to the winners, and a heartfelt thank you to all Pine Script™ coders who contribute their open-source publications to our Community scripts . We eagerly anticipate another year of remarkable scripts in 2024!
What are Editors' Picks ?
The Editors' Picks showcase the best open-source script publications selected by our PineCoders team. Many of these scripts are original and only available on TradingView. These picks are not recommendations to buy or sell anything, nor to use a specific indicator. Our aim is to highlight the most interesting recent publications to encourage learning and sharing in our community.
Any open-source Community scripts can be picked if they're original, provide good potential value to traders, include helpful descriptions, and comply with the House Rules.
S&P 500 index. bearish trend/The provided S&P Chart appears to be a tradingview chart or analysis screen for S&P 500 E-mini Futures, with some annotations and tools listed. Here are the patterns and tools mentioned or implied:
### *Patterns:*
1. *Resistance Level (D, resistance)*
- This indicates a price level where selling pressure may overcome buying pressure, potentially causing the price to stall or reverse. The "D" could denote a specific resistance level identified by the trader or tool.
2. *RSL*
- This likely stands for *"Relative Strength Line"* or a similar indicator, though the exact meaning depends on the trader's context. It could also refer to a custom tool or script.
---
### *Tools:*
1. *Pine Editor*
- A scripting tool in TradingView used to create custom indicators or strategies (written in Pine Script).
2. *Strategy Tester*
- A backtesting tool to evaluate trading strategies on historical data.
3. *Replay Trading*
- A feature to simulate trading in past market conditions for practice or analysis.
4. *Trading Panel*
- Likely refers to the interface for executing trades or managing positions.
5. *Crypto Pairs Screener*
- A tool for scanning and comparing cryptocurrency pairs, though oddly placed here (possibly a multi-asset analysis setup).
6. *Price Data Summary*
- The header shows key price points (High, Low, Close) and a slight decline (-0.04%).
---
### *Potential Analysis Approach:*
- The trader may be using *horizontal resistance levels* (marked as "D") alongside a custom RSL indicator to assess price action.
- The tools suggest a focus on *scripting (Pine Editor), backtesting (Strategy Tester), and trade simulation (Replay Trading)*.
- The mention of "Crypto Pairs Screener" is unusual for S&P 500 futures, possibly indicating a multi-platform setup or a misplaced label.
### *Missing Context:*
- No visible chart patterns (e.g., head-and-shoulders, triangles) or common indicators (e.g., MACD, RSI) are explicitly mentioned.
- The "RSL" acronym’s meaning is unclear without further detail.
If you have access to the actual chart image, additional patterns (like trendlines, candlestick formations) or tools (like volume indicators) might be visible. Let me know if you'd like clarification on any of these terms!
Who are PineCoders?People often ask us who PineCoders are. Simply put, we are a group of Pine programmers who aim to contribute to the TradingView ecosystem. Many of the Pine Wizards are PineCoders, yet many PineCoders are not Wizards. We are a relatively small group of just about 40. Our group of programmers contributes to the ever-growing community in many ways. Some may create script publications for users to benefit from, while other members are Pine experts contributing in different, often anonymous, ways. We don't publish a list of PineCoders members because many are happy avoiding the limelight; they do what they do for the love of Pine and our community.
PineCoders strive to represent, in a balanced way, the interests of Pine programmers, script publishers and vendors, and the traders who use scripts on TradingView. Oh, and we have lots of fun together.
█ WHAT DO PINECODERS DO?
Many of you recognize us as the script moderators who operate this account. However, script moderation is only one manifestation of our activities. In the Pine realm, we also:
• Help maintain and evolve the Script Publishing Rules and Vendor Requirements .
• Answer questions in the Q&A forums we support: the Q&A chat on TradingView, the Telegram Q&A group , and Stack Overflow .
• Moderate the Telegram Q&A group and the Q&A chat on TradingView.
• Manage the private spaces where our top programmers share and help improve Pine.
• Design solutions to improve the Pine-related aspects of TradingView.
• Help define Pine-related development priorities.
• Tally suggestions for improvement from Pine users.
• Answer Pine-related support tickets.
• Test new features and changes to Pine.
• Report bugs.
• Publish content from the PineCoders and TradingView accounts.
• Publish a monthly script in TASC and from the PineCodersTASC account.
• Publish Pine-related news in our broadcast channels.
• Select and support our Trusted Pine Programmers for Hire .
• Select the Editors' Picks for Community Scripts .
• Select the yearly Pine Wizards nominees.
• Organize Pinefests , the Pine programming contests .
• Collaborate on the technical documentation of Pine.
█ HOW ARE PINECODERS CHOSEN?
Any member of PineCoders can propose a candidacy. When our management team approves it, they submit the nomination to our members to cast their votes. If the majority of our group agrees, we send an invitation to the user. We select people who are agile in Pine and interested in contributing to our ever-growing community. We keep our group relatively small but diverse, as we believe it fosters a dynamic conducive to productive exchanges and efficient decision making.
█ WHAT'S YOUR RELATIONSHIP WITH TRADINGVIEW?
A handful of users launched PineCoders in 2019 with the support of a TradingView co-founder who recognized the potential of uniting power users with good ideas to improve Pine. The official support from this visionary and our daily collaboration with key TradingView teams are some of the main reasons we can successfully realize our projects.
We founded PineCoders as a volunteer group, and to this day, the vast majority of PineCoders activities are made possible because of volunteer contributions. As our projects evolved and some work required a few of us to commit to internal TradingView activities, those few also added contract work for TradingView to their volunteer activities within PineCoders.
█ WE ARE NOT ALONE
Our group does not hold a monopoly on good deeds. Many other Pine programmers also contribute to the strength and liveliness of our unique community.
With TradingView being so popular, a constant influx of newcomers to Pine want to learn how to enhance their trading practice by programming indicators and strategies. It would be impossible for PineCoders to support them alone, and it's comforting to see that even today, some people still find purpose in volunteering their time and knowledge to help others.
Thank you to all those who help our fantastic community in one way or another.
HOW-TO: Compare Different Strategies With Strategy TesterMy good friend Moses emerged from the cloud and declared “I have beaten the Nasdaq 100 by 1,100% over the last 24 years.”
I double and triple-checked his numbers, and goodness me he was right.
“How did you achieve that Moses!” I exclaimed.
“It was achieved using the application of mathematics and technical analysis” Moses retorted.
“But what did you do specifically,” I asked.
“I managed to avoid all the major stock market crashes and entered the Index ETF lower than when I sold it. This compounded my long-term gains tremendously” he cried.
MOSES ( M arket O utperforming S tock E TF S trategy) is of course my affectionately named TradingView Strategy Pine Scripts/Algos.
TradingView the New King Of Backtesting
I have been working on backtesting systems for the last 14 years. I have used many competing services, but TradingView is my new favorite tool.
Why?
TradingView has enabled me to backtest many scenarios using their excellent Pine Script. I am not a developer, but Pine Script is super easy.
Backtesting & Strategy Testing Takes Time… But TradingView Makes it Quicker.
Creating a strategy that tests for solid results takes a lot of time and effort. But don’t get disheartened. Start with indicators you believe in and test them. Do they really work? How often, what is your success rate. How long is each trade? How often do you trade? What is your drawdown? What is your Sharpe & Sortino ratio?
Luckily TradingView makes this process really fast, the speed of calculating the results of a test is mind-blowing. Seriously, it’s a platform that can perform 5, 6, 7, 8 strategies side by side over 24 years in the blink of an eye.
How did Moses Perform?
I have 3 MOSES strategies which you can see on the chart. All three beat the Nasdaq 100, but one really beat it hard. The “Buy on Bull Sell on Bear” strategy made $2.88 million on $100K invested in 1997, vs. $1.76 million for a “Buy and Hold” strategy, a 1,100% difference on $100K invested.
This long-term performance was with only 12 trades in 24 years with a 67% success rate. How do I know this? TradingView tells me in its strategy tester reporting.
Moses tells me many things:
When we are in a solid Bull Market (Green Dots)
When we are in a Bear Market (Red Dots)
When we have a Shock to the Market (Shock Label)
When we have a Catastrophic Event (Red Catastrophe Label)
When to buy back in early, before the full bull market resumes (yellow dots)
Thanks to TradingView
Thanks to TradingView, I have a platform where I can rapidly test ideas and see if they work in the past.
I can check to see if a new fancy indicator really works or if it is just hype. (95% are hype)
If you are not backtesting strategies, then how do you know if they have a chance to work in the future?
Walking the Path
We all start as beginners. We think it is easy to make money. Then we experience a large crash and we lose a lot of money. Then we leave the market. If you persevere, you will try to build your knowledge and experience. If you go 23 years down that path, you realize that system and strategy development using backtesting is essential to making repeatable money.
Strategy Development Advice
“You can try to out-compete the hedge fund algorithms by day trading, but that is near impossible. You cannot out-arbitrage a supercomputer.”
You can, however, develop your own strategy that works over weeks, months, or years, and you can really make good profits.
Notes on the Chart
I run 5 scripts, 3 Moses Strategies + 1 Buy & Hold strategy for comparison (lower panes), and the MOSES Signals 2.0 in the price chart.
The chart is Weekly and from 1997 to today.
Note on Strategies.
Systems may not work in the future as they have worked in the past. There is no guarantee of future returns. Moses is a long-term strategy that works over years, not a day trading strategy. Moses worked in the past on major US and European stock market indices, it does not work with India or Chinese markets, no Strategy is perfect, not even Moses. Moses scripts are private.
Follow me if you like the post, and if you want to see my next post, the “10 Commandments of Moses” 😊
Any questions you have, let me know in the comments.
Barry
Pinefest #1This Pinefest was closed October 28 2023. Congratulations to its winner, alexgrover with this script .
█ CHALLENGE
Create three functions that will return the exact value where two data series intersect: crossValue(source1, source2)
crossoverValue(source1, source2)
crossunderValue(source1, source2)
When a cross occurs, the functions must return the intersection's value. When no cross occurs, they must return na .
█ SUBMISSIONS
Prepare your entry as a private open-source script publication, including a detailed description explaining to its audience how it works and can be useful, just like public scripts published in Community Scripts . Your private publication must comply with our Script Publishing Rules .
Submit your entry as a comment in the Comments section below, with a link to your private publication. This way, all TradingViewers can view submissions. Note that publishing links to private publications is against House Rules; we make an exception for our Pinefest submissions.
No public script publications will be accepted as entries. Participants who publish their entries publicly will be disqualified, and their publication will be hidden. Entries must be your own work. Calls to functions of previously published libraries (by you or others) are allowed, as is the use of a private library accompanying your entry.
You have one week to submit your entry. Submission deadline: 28 Oct 2023, 12:00 UTC
If you have questions about this Pinefest, please post a comment below.
█ EVALUATION CRITERIA
A PineCoders committee will evaluate all submissions based on the following criteria:
• Submission date
• Solution to the challenge
• Code efficiency
• Code readability
• Description
• Visuals
• Script usability
• Compliance with our Script Publishing Rules
In case two or more publications reach an identical final evaluation, the earliest submission will win. Committee decisions are final.
█ REWARDS
The winner of this Pinefest will receive 500 USD and publish their script publicly in our Community Scripts . Their publication will also be awarded an Editors' Pick , for which the winner will receive an additional 100 USD . Authors of the five highest-scoring submissions will be awarded TradingView merchandise.






















