HOW TO USE CHATGPT TO CODE PINESCRIPT (ACTUALLY) ChatGPT is an advanced language model that can help you write code more efficiently and accurately. By using ChatGPT, you can generate high-quality Pinescript code without the need for extensive coding knowledge or experience.
In this article, we will focus on using the free version of ChatGPT to code Pinescript indicators and strategies. We'll provide step-by-step instructions, highlighting potential issues you may encounter and how to resolve them. By the end of this article, you'll have the tools you need to leverage ChatGPT to create profitable trading strategies.
So, whether you're an experienced trader or just starting out, read on to discover how you can use ChatGPT to revolutionize your Pinescript coding, and even explore the other exciting possibilities it offers.
Things to know before we continue
💡ChatGPT can generate Pinescript code for both versions 4 and 5, but it's important to note that there are some differences between the two versions. It's recommended to specify which version you want your code written in before using ChatGPT. Additionally, it's worth noting that ChatGPT has more knowledge of Pinescript version 4, so you may want to consider having it write code in version 4 and then use the Tradingview editor to convert it to version 5.
💡It's true that ChatGPT can help you generate Pinescript code without extensive coding knowledge. However, for more complex scripts, it's recommended to have a basic understanding of Pinescript to make the most of ChatGPT. That way, you can better understand the generated code and make adjustments as needed.
💡ChatGPT is a tool that can help you improve your Pinescript coding, not a replacement for it. It's best to use ChatGPT to solve specific issues or come up with solutions for certain parts of your code rather than relying on it to write the entire code for you.
WHAT WE WILL BE CODING FOR OUR FIRST EXAMPLE.
🔸In our example, we will be coding an indicator that uses two moving averages with exposed periods to determine the direction of the market. Additionally, we will be using the stochastic RSI indicator as a momentum indicator to determine when to buy in an uptrend and when to sell in a downtrend. After we have created this script as an indicator, we will use ChatGPT to convert it to a strategy. This will enable us to backtest it using the Tradingview backtesting framework.
Lets begin.
1: The first thing we want to do is let CHatGPT know exactly what we want it to do. And have it come up with a solution to the issue. For our example we are going to type the following below.
Note how I specified the version of pinescript we will be coding in.
2: I am going to let ChatGPT know the description of the indicator we are going to code
🔸As you can see, ChatGPT provided me with Pinescript based on the information I provided. It is worth noting that, while this code worked for me, others may receive slightly different code due to the nature of ChatGPT's predictions. Additionally, ChatGPT explained the code in further detail in its response. Our next step is to test the code to determine whether it meets our requirements, and to note any issues we encounter. If there are any issues, we will provide them to ChatGPT for further assistance. To begin, I will copy and paste the generated code into the Pinescript editor without making any modifications, and attempt to add the script to the chart.
For reference here is the code provided by GPT below :
//@version=4
study(title="Moving Average and Stochastic RSI Indicator", shorttitle="MA+Stoch RSI", overlay=false)
// Input variables
ma1_length = input(title="MA1 Length", type=input.integer, defval=20, minval=1)
ma2_length = input(title="MA2 Length", type=input.integer, defval=50, minval=1)
stoch_length = input(title="Stochastic RSI Length", type=input.integer, defval=14, minval=1)
overbought = input(title="Overbought Level", type=input.integer, defval=80)
oversold = input(title="Oversold Level", type=input.integer, defval=20)
// Calculate moving averages
ma1 = sma(close, ma1_length)
ma2 = sma(close, ma2_length)
// Calculate Stochastic RSI
rsi1 = rsi(close, stoch_length)
rsiH = highest(rsi1, stoch_length)
rsiL = lowest(rsi1, stoch_length)
stoch = (rsi1 - rsiL) / (rsiH - rsiL) * 100
// Determine trend direction based on MA crossover
trendUp = ma1 > ma2 ? true : false
trendDown = ma1 < ma2 ? true : false
// Determine buy and sell signals based on Stochastic RSI
buySignal = trendUp and crossover(stoch, oversold)
sellSignal = trendDown and crossunder(stoch, overbought)
// Plot signals on chart
plotshape(buySignal, style=shape.arrowup, location=location.belowbar, color=color.green, size=size.small, text="Buy")
plotshape(sellSignal, style=shape.arrowdown, location=location.abovebar, color=color.red, size=size.small, text="Sell")
🔸The code had no syntax errors and met all the requirements specified in my prompt. The periods for the moving averages and the stochastic RSI were exposed, allowing them to be adjusted as needed. However, there is one issue that is not a result of ChatGPT, but rather caused by my failure to specify it in the prompt. The indicator is not being overlaid on the chart and is instead being displayed as an oscillator in a separate window below, similar to the RSI indicator. However, for our purposes, we want the indicator to be displayed over the candles themselves.
3: After testing the code and verifying that it meets my requirements, I will provide feedback to GPT that the code is functioning properly. However, I will also request that the indicator be displayed over the candles instead of in a separate window. It's important to communicate clearly with GPT to avoid any unnecessary changes to the code.
🔸Now we will test the code again.
Updated code listed below
//@version=4
study(title="Moving Average and Stochastic RSI Indicator", shorttitle="MA+Stoch RSI", overlay=true)
// Input variables
ma1_length = input(title="MA1 Length", type=input.integer, defval=20, minval=1)
ma2_length = input(title="MA2 Length", type=input.integer, defval=50, minval=1)
stoch_length = input(title="Stochastic RSI Length", type=input.integer, defval=14, minval=1)
overbought = input(title="Overbought Level", type=input.integer, defval=80)
oversold = input(title="Oversold Level", type=input.integer, defval=20)
// Calculate moving averages
ma1 = sma(close, ma1_length)
ma2 = sma(close, ma2_length)
// Calculate Stochastic RSI
rsi1 = rsi(close, stoch_length)
rsiH = highest(rsi1, stoch_length)
rsiL = lowest(rsi1, stoch_length)
stoch = (rsi1 - rsiL) / (rsiH - rsiL) * 100
// Determine trend direction based on MA crossover
trendUp = ma1 > ma2 ? true : false
trendDown = ma1 < ma2 ? true : false
// Determine buy and sell signals based on Stochastic RSI
buySignal = trendUp and crossover(stoch, oversold)
sellSignal = trendDown and crossunder(stoch, overbought)
// Plot signals on chart
plotshape(buySignal, style=shape.arrowup, location=location.belowbar, color=color.green, size=size.small, text="Buy")
plotshape(sellSignal, style=shape.arrowdown, location=location.abovebar, color=color.red, size=size.small, text="Sell")
🔸Great. Now the code is displaying as we would want it to as well!.
4: Now, let's make some improvements to the code. In addition to generating buy and sell signals, I would also like to see the moving averages displayed on the chart. This will allow me to visually understand why the signals are being generated.
Code reference below:
//@version=4
study(title="Moving Average and Stochastic RSI Indicator", shorttitle="MA+Stoch RSI", overlay=true)
// Input variables
ma1_length = input(title="MA1 Length", type=input.integer, defval=20, minval=1)
ma2_length = input(title="MA2 Length", type=input.integer, defval=50, minval=1)
stoch_length = input(title="Stochastic RSI Length", type=input.integer, defval=14, minval=1)
overbought = input(title="Overbought Level", type=input.integer, defval=80)
oversold = input(title="Oversold Level", type=input.integer, defval=20)
// Calculate moving averages
ma1 = sma(close, ma1_length)
ma2 = sma(close, ma2_length)
// Calculate Stochastic RSI
rsi1 = rsi(close, stoch_length)
rsiH = highest(rsi1, stoch_length)
rsiL = lowest(rsi1, stoch_length)
stoch = (rsi1 - rsiL) / (rsiH - rsiL) * 100
// Determine trend direction based on MA crossover
trendUp = ma1 > ma2 ? true : false
trendDown = ma1 < ma2 ? true : false
// Determine buy and sell signals based on Stochastic RSI
buySignal = trendUp and crossover(stoch, oversold)
sellSignal = trendDown and crossunder(stoch, overbought)
// Plot signals on chart
plotshape(buySignal, style=shape.arrowup, location=location.belowbar, color=color.green, size=size.small, text="Buy")
plotshape(sellSignal, style=shape.arrowdown, location=location.abovebar, color=color.red, size=size.small, text="Sell")
// Plot moving averages on chart
plot(ma1, color=color.blue)
plot(ma2, color=color.orange)
🔸Great! Now that we can see the moving averages, we have a better understanding of why the buy and sell signals are being generated. However, before we convert the indicator into a strategy, we need to make one final adjustment: reducing the number of signals being generated. There are various ways to achieve this such as using an ADX filter or a volatility filter. However, for this example, we will simply limit the number of signals generated for each cross of the moving averages to 1.
5: Final adjustments, During the tutorial, ChatGPT crashed, which can happen from time to time. If this happens, simply create a new chat session, copy the code from PineScript, and ask ChatGPT what the script does. Once ChatGPT advises you, you can ask it to act as an expert and help you make any necessary adjustments to the code in PineScript version 4.
🔸Here is when we started to have issues.
Here is my prompt and here is the code provided by ChatGPT
//@version=4
study(title="Moving Average and Stochastic RSI Indicator", shorttitle="MA+Stoch RSI", overlay=true)
// Input variables
ma1_length = input(title="MA1 Length", type=input.integer, defval=20, minval=1)
ma2_length = input(title="MA2 Length", type=input.integer, defval=50, minval=1)
stoch_length = input(title="Stochastic RSI Length", type=input.integer, defval=14, minval=1)
overbought = input(title="Overbought Level", type=input.integer, defval=80)
oversold = input(title="Oversold Level", type=input.integer, defval=20)
// Calculate moving averages
ma1 = sma(close, ma1_length)
ma2 = sma(close, ma2_length)
// Calculate Stochastic RSI
rsi1 = rsi(close, stoch_length)
rsiH = highest(rsi1, stoch_length)
rsiL = lowest(rsi1, stoch_length)
stoch = (rsi1 - rsiL) / (rsiH - rsiL) * 100
// Initialize buy and sell signals to false
var buySignal = false
var sellSignal = false
// Determine trend direction based on MA crossover
trendUp = ma1 > ma2 ? true : false
trendDown = ma1 < ma2 ? true : false
// Generate buy signal if a signal has not already been generated and the conditions are met
if trendUp and crossover(stoch, oversold) and not buySignal
buySignal := true
// Generate sell signal if a signal has not already been generated and the conditions are met
if trendDown and crossunder(stoch, overbought) and not sellSignal
sellSignal := true
// Plot signals on chart
plotshape(buySignal, style=shape.arrowup, location=location.belowbar, color=color.green, size=size.small, text="Buy")
plotshape(sellSignal, style=shape.arrowdown, location=location.abovebar, color=color.red, size=size.small, text="Sell")
// Reset buy and sell signals if a new trend develops
if trendUp and sellSignal
sellSignal := false
if trendDown and buySignal
buySignal := false
// Plot moving averages on chart
plot(ma1, color=color.blue)
plot(ma2, color=color.orange)
🔸Once I inputted the code provided I started to get a signal for every candle which is not what we wanted.
So I advised GPT of the issue.
It then attempted to solve the issue but instead it modified the code to only generate a buy signal or sell signal if the moving averages and the stochastic conditions where met all AT THE SAME TIME, Resulting in little to no signals.
//@version=4
study(title="Moving Average and Stochastic RSI Indicator", shorttitle="MA+Stoch RSI", overlay=true)
// Input variables
ma1_length = input(title="MA1 Length", type=input.integer, defval=20, minval=1)
ma2_length = input(title="MA2 Length", type=input.integer, defval=50, minval=1)
stoch_length = input(title="Stochastic RSI Length", type=input.integer, defval=14, minval=1)
overbought = input(title="Overbought Level", type=input.integer, defval=80)
oversold = input(title="Oversold Level", type=input.integer, defval=20)
// Calculate moving averages
ma1 = sma(close, ma1_length)
ma2 = sma(close, ma2_length)
// Calculate Stochastic RSI
rsi1 = rsi(close, stoch_length)
rsiH = highest(rsi1, stoch_length)
rsiL = lowest(rsi1, stoch_length)
stoch = (rsi1 - rsiL) / (rsiH - rsiL) * 100
// Determine trend direction based on MA crossover
trendUp = ma1 > ma2 ? true : false
trendDown = ma1 < ma2 ? true : false
// Keep track of current trend direction
var currentTrendUp = trendUp
var currentTrendDown = trendDown
// Determine buy and sell signals based on Stochastic RSI
buySignal = false
sellSignal = false
if trendUp and not currentTrendUp and crossover(stoch, oversold)
buySignal := true
currentTrendUp := true
else if trendDown and not currentTrendDown and crossunder(stoch, overbought)
sellSignal := true
currentTrendDown := true
// Reset trend direction if moving averages cross
if not trendUp and currentTrendUp or not trendDown and currentTrendDown
currentTrendUp := trendUp
currentTrendDown := trendDown
// Plot signals on chart
plotshape(buySignal, style=shape.arrowup, location=location.belowbar, color=color.green, size=size.small, text="Buy")
plotshape(sellSignal, style=shape.arrowdown, location=location.abovebar, color=color.red, size=size.small, text="Sell")
// Plot moving averages on chart
plot(ma1, color=color.blue)
plot(ma2, color=color.orange)
I advised ChatGPT of the issue once again. And was more clear in what I wanted.
This time, GPT was successful in solving the issue and the code was working exactly how I wanted it to. As you can see, one of the major challenges with using GPT to generate code is clearly articulating what you want it to do and limiting the number of iterations and changes it makes to the code. Additionally, providing feedback on what it is doing right and wrong is crucial in achieving the desired outcome.
//@version=4
study(title="Moving Average and Stochastic RSI Indicator", shorttitle="MA+Stoch RSI", overlay=true)
// Input variables
ma1_length = input(title="MA1 Length", type=input.integer, defval=20, minval=1)
ma2_length = input(title="MA2 Length", type=input.integer, defval=50, minval=1)
stoch_length = input(title="Stochastic RSI Length", type=input.integer, defval=14, minval=1)
overbought = input(title="Overbought Level", type=input.integer, defval=80)
oversold = input(title="Oversold Level", type=input.integer, defval=20)
// Calculate moving averages
ma1 = sma(close, ma1_length)
ma2 = sma(close, ma2_length)
// Calculate Stochastic RSI
rsi1 = rsi(close, stoch_length)
rsiH = highest(rsi1, stoch_length)
rsiL = lowest(rsi1, stoch_length)
stoch = (rsi1 - rsiL) / (rsiH - rsiL) * 100
// Initialize trend direction and signal variables
var trendUp = ma1 > ma2 ? true : false
var trendDown = ma1 < ma2 ? true : false
var signalUp = false
var signalDown = false
// Determine trend direction based on MA crossover
if ma1 > ma2
trendUp := true
trendDown := false
else
trendUp := false
trendDown := true
// Determine buy and sell signals based on Stochastic RSI
buySignal = false
sellSignal = false
if trendUp and crossover(stoch, oversold) and not signalUp
buySignal := true
signalUp := true
signalDown := false
else if trendDown and crossunder(stoch, overbought) and not signalDown
sellSignal := true
signalUp := false
signalDown := true
// Plot signals on chart
plotshape(buySignal, style=shape.arrowup, location=location.belowbar, color=color.green, size=size.small, text="Buy")
plotshape(sellSignal, style=shape.arrowdown, location=location.abovebar, color=color.red, size=size.small, text="Sell")
// Plot moving averages on chart
plot(ma1, color=color.blue)
plot(ma2, color=color.orange)
6: With our indicator now functioning properly, we can move on to the next step of converting it into a strategy for testing on Tradingview. To accomplish this, we'll need to establish specific take profit and stop loss criteria I've decided to use the price of the slow moving average as the exit of the trades. Which will also act as a trailing stop loss
//@version=4
strategy("MA+Stoch RSI Strategy", overlay=true)
// Input variables
ma1_length = input(title="MA1 Length", type=input.integer, defval=20, minval=1)
ma2_length = input(title="MA2 Length", type=input.integer, defval=50, minval=1)
stoch_length = input(title="Stochastic RSI Length", type=input.integer, defval=14, minval=1)
overbought = input(title="Overbought Level", type=input.integer, defval=80)
oversold = input(title="Oversold Level", type=input.integer, defval=20)
// Calculate moving averages
ma1 = sma(close, ma1_length)
ma2 = sma(close, ma2_length)
// Calculate Stochastic RSI
rsi1 = rsi(close, stoch_length)
rsiH = highest(rsi1, stoch_length)
rsiL = lowest(rsi1, stoch_length)
stoch = (rsi1 - rsiL) / (rsiH - rsiL) * 100
// Determine trend direction based on MA crossover
trendUp = ma1 > ma2 ? true : false
trendDown = ma1 < ma2 ? true : false
// Initialize flag variables
var hasBoughtSignal = false
var hasSoldSignal = false
// Generate signals
if trendUp and crossover(stoch, oversold) and not hasBoughtSignal
strategy.entry("Buy", strategy.long)
hasBoughtSignal := true
hasSoldSignal := false
if trendDown and crossunder(stoch, overbought) and not hasSoldSignal
strategy.entry("Sell", strategy.short)
hasBoughtSignal := false
hasSoldSignal := true
// Set stop loss and take profit levels
if strategy.position_size != 0
if strategy.position_size > 0
strategy.exit("StopLoss", "Buy", stop=ma2, qty_percent=100)
strategy.exit("TakeProfit", "Sell", limit=close - (ma2 - close), qty_percent=100)
else
strategy.exit("StopLoss", "Sell", stop=ma2, qty_percent=100)
strategy.exit("TakeProfit", "Buy", limit=close + (close - ma2), qty_percent=100)
// Plot moving averages on chart
plot(ma1, color=color.blue)
plot(ma2, color=color.orange)
And that's it! Our code is complete. The final step is to convert it to version 5
And here is the final code
//@version=5
strategy('MA+Stoch RSI Strategy', overlay=true)
// Input variables
ma1_length = input.int(title='MA1 Length', defval=20, minval=1)
ma2_length = input.int(title='MA2 Length', defval=50, minval=1)
stoch_length = input.int(title='Stochastic RSI Length', defval=14, minval=1)
overbought = input(title='Overbought Level', defval=80)
oversold = input(title='Oversold Level', defval=20)
// Calculate moving averages
ma1 = ta.sma(close, ma1_length)
ma2 = ta.sma(close, ma2_length)
// Calculate Stochastic RSI
rsi1 = ta.rsi(close, stoch_length)
rsiH = ta.highest(rsi1, stoch_length)
rsiL = ta.lowest(rsi1, stoch_length)
stoch = (rsi1 - rsiL) / (rsiH - rsiL) * 100
// Determine trend direction based on MA crossover
trendUp = ma1 > ma2 ? true : false
trendDown = ma1 < ma2 ? true : false
// Initialize flag variables
var hasBoughtSignal = false
var hasSoldSignal = false
// Generate signals
if trendUp and ta.crossover(stoch, oversold) and not hasBoughtSignal
strategy.entry('Buy', strategy.long)
hasBoughtSignal := true
hasSoldSignal := false
hasSoldSignal
if trendDown and ta.crossunder(stoch, overbought) and not hasSoldSignal
strategy.entry('Sell', strategy.short)
hasBoughtSignal := false
hasSoldSignal := true
hasSoldSignal
// Set stop loss and take profit levels
if strategy.position_size != 0
if strategy.position_size > 0
strategy.exit('StopLoss', 'Buy', stop=ma2, qty_percent=100)
strategy.exit('TakeProfit', 'Sell', limit=close - (ma2 - close), qty_percent=100)
else
strategy.exit('StopLoss', 'Sell', stop=ma2, qty_percent=100)
strategy.exit('TakeProfit', 'Buy', limit=close + close - ma2, qty_percent=100)
// Plot moving averages on chart
plot(ma1, color=color.new(color.blue, 0))
plot(ma2, color=color.new(color.orange, 0))
🔸I will also publish this script along with this article for others to use. However, I want to stress that this is not a guaranteed profitable system and users should use it at their own risk. This tutorial is simply an example of how to use ChatGPT to create your own script and test it.
🔸While using ChatGPT, you may encounter some issues, such as incomplete responses due to word limits. In such cases, you can refer to the end of the code and ask ChatGPT to provide only the additional part of the response. Additionally, the longer the chat history, the more likely you may encounter issues as GPT makes more modifications to the code. Therefore, it's important to limit the number of changes and provide clear feedback to help GPT understand your desired outcome. You may sometimes need to start a new chat if having many issues.
🔸Another way to utilize GPT for more complex tasks, especially when you already have programming knowledge, is to use it to brainstorm solutions for specific issues instead of writing the code. For example, if you're working with multiple timeframes, GPT may be unable to generate the code for you, but it can help you come up with ideas and potential solutions to the problem. Here is an example below :
Pinescript
Indicator usage knowledge ☆♡
TradingView PineScript indicator code involves understanding the code, installing it on TradingView, testing it on historical data, optimizing it for your trading strategy, and implementing it in your live trading. By following these steps, you can make the most of your indicator and increase your chances of success in the market.
To install a script on TradingView, follow these steps:
• Open TradingView and click on the "Pine Editor" tab at the bottom of the screen.
• Once you are in the Pine Editor, create a new script by clicking on the "New indicator" button in the top left corner.
• Argument how and what your indicator should calculate , plot and generate alerts in.
• After definening your indicator script, click on the "Save" button in the top left corner to save the code.
• Next, click on the "Add to Chart" button in the top right corner to add the code to your chart.
• Finally, customize the settings of the indicator as needed while testing it using the backtesting feature on TradingView.
Once you have installed the code, you can modify it to suit your trading needs. Be sure to test the modified code on historical data using the backtesting feature on TradingView before using it in live trading.
You are on your way to optimizing your trading strategy and increasing your profits.
• Understand the Code: Start by going through the code and understanding what it does. You can do this by studying the way to argument your indicatot script. It's important to know what the code is doing before using it in your trading strategy.
• Install the Code: Once you understand the code, install it on TradingView. Be sure to check for any errors.
• Test the Code: After installing the code, it's important to test it on historical data. This will help you verify that the indicator works as expected and can be useful in your trading strategy. You can do this by using the backtesting feature on TradingView.
• Optimize the Code: Depending on your trading style, you may need to optimize the code. This means tweaking the parameters to fit your specific trading strategy. For example, you may need to adjust the timeframe, the number of periods, or the signal thresholds.
• Implement the Code: Once you are satisfied with the code, you can start using it in your live trading strategy. Be sure to monitor your trades and adjust your strategy as needed.
It is important to remember that no trading strategy is foolproof, and there is always a risk of losing money. Always practice proper risk management and trade with caution.
"By analyzing market sessions using indicators , traders can gain a better understanding of the market dynamics during different times of the day. This information can be used to identify high-probability trading opportunities, as well as to manage risk in periods of low liquidity or high volatility. When used in conjunction with other technical indicators, such as RSI4, volumes, awesome oscillators and market session indicators, analysis if the market will provide a more complete picture, helping you make more informed trading decisions."
-Happy Foreign Exchange Trading - J
2nd Pine Script Lesson: Coding the Entry Logic - Bollinger BandWelcome back to our Trading View tutorial series! In this second lesson, be learning how to code the entry logic for a Bollinger Band indicator using Pine Script.
If you're new here and missed the first lesson, we highly recommend starting there as it provides a solid foundation for understanding the concepts we'll be covering today:
In this hands-on lesson, we'll guide you through every step of coding the entry logic for your own Bollinger Band indicator using Pine Script. By the end of this lesson, you'll have a functional indicator that you can use to inform your trading decisions. So, sit back, grab a cup of coffee, and let's get started!
Code the entry logic
a) This is where we are calling the Mikilap function with two arguments:
- the coinpair and
- the timeframe we want to use.
// Calling the Mikilap function to start the calculation
int indi_value = Function_Mikilap(symbol_full, time_frame)
b) In the function initiation we convert the strings into simple strings.
// Definition of a Pine Script individual function to handle the Request and avoid Repainting Errors
Function_Mikilap(simple string coinpair, simple string tf_to_use) =>
c) As we are calling the function to get an integer value, we have to define an output variable as an integer and place this variable as the last line in the local scope of the function code to return the integer value.
int function_result = 0
// placeholder for indicator calculations
function_result
Step 1:
Using the lower bandwidth of the Bollinger Band based on SMA (close, 21) and a standard deviation of 2.0 and try to highlight bars, where close is next to the lower band
a) Requesting the values for the coinpair with request.security()
= request.security(coinpair, tf_to_use, )
We recommend using repainting functions like request or barstate only in a local scope (inside a function) and not to request complex calculated values. For saving calculation capacity it is useful to only request the classic four OHLCs and do any calculation with these four after the r equest.security() .
b) Calculation of the lower Bollinger Bands values as we need the global info, which type of source, length, and deviation value to use for the calculation, let‘s cut & paste the input for the Bollinger Band in the general starting section of the code and as we want to look for close values „next“ to the lower bandwidth, we need to define what „next“ means; let‘s do it in another input variable, perhaps we want to play with the definition later.
string symbol_full = input.symbol(defval = "BINANCE:BTCUSDT", title = "Select Pair:", group = "General")
string time_frame = input.string(defval = "60", title = "Timeframe:", tooltip = "Value in minutes, so 1 hour = 60", group = "General")
int length = input.int(defval = 21, title = "BB Length:", group = "Bollinger Band Setting")
src = input(defval = close, title="BB Source", group = "Bollinger Band Setting")
float mult = input.float(defval = 2.0, title="BB Standard-Deviation", group = "Bollinger Band Setting")
float lower_dev = input.float(defval = 0.1, title="BB Lower Deviation in %", group = "Bollinger Band Setting")/100
First, let‘s make it visible on the chart by re-writing the Bollinger Bandplot, which is not needed anymore.
// Calling the Mikilap function to start the calculation
int indi_value = Function_Mikilap(symbol_full, time_frame)
// Output on the chart
// Part 2 - plotting a Band around the lower bandwidth of a Bollinger Band for the active CoinPair on the chart
lower_bb = ta.sma(src, length) - (mult*ta.stdev(src, length))
lower_bb_devup = lower_bb + lower_bb * lower_dev
lower_bb_devdown = lower_bb - lower_bb * lower_dev
upper = plot(lower_bb_devup, "BB Dev UP", color=#faffaf)
lower = plot(lower_bb_devdown, "BB Dev DOWN", color=#faffaf)
fill(upper, lower, title = "BB Dev Background", color=color.rgb(245, 245, 80, 80))
c) Now we use the same calculation for the coinpair inside the function and start with the selection of the source (OHLC) to use, which is activein the respective input variable.
// Defintion of a Pine Script individual function to handle the Request and avoid Repainting Errors
Function_Mikilap(simple string coinpair, simple string tf_to_use) =>
int function_result = 0
bool barstate_info = barstate.isconfirmed
= request.security(coinpair, tf_to_use, )
src_cp = switch src
open => open_R
high => high_R
low => low_R
=> close_R
lower_band_cp = ta.sma(src_cp,length) - (mult*ta.stdev(src_cp, length))
lower_band_cp_devup = lower_band_cp + lower_band_cp * lower_dev
lower_band_cp_devdown = lower_band_cp - lower_band_cp * lower_dev
// placeholder for indicator calculations
d) As the bandwidth for the interesting close values is defined by our band, the only thing missing for the part of the Bollinger Band in our Mikilap indicator is to check if the close value of a bar is inside our band. As we are talking about closed bars, let‘s be sure that it is really closed by using barstate.isconfirmed (repainting built-in function!) and save it in a variable in the head of the function to avoid requesting this info too often.
bool barstate_info = barstate.isconfirmed
Now let‘s check if the close value of a bar is inside our band.
bool bb_entry = close_R < lower_band_cp_devup and close_R > lower_band_cp_devdown and barstate_info
And increase the output variable by 1 in case the close value is inside.
if bb_entry
function_result += 1
By using bb_entry , we are referring to the last bar next to the actual bar, because we want to enter on the opening of the bar after the criteria has been met.
e) And to make these possible entries visible, we want to place a label below the bar and show the entry price (=open value of the bar) as mouseover (tooltip). This should only happen if the active coinpair on the chart is the same coinpair, which is in the calculation of the function.
if function_result == 1 and ticker.standard(syminfo.tickerid) == coinpair
label LE_arrow = label.new(x = bar_index, y = low_R, text = " ↑ LE", yloc = yloc.belowbar, color = color.rgb(255,255,255,25),style = label.style_none, textcolor = color.white, tooltip = str.tostring(open_R))
Note:
You will love labels (!) and in case you are looking for text symbols that can be used as labels, look here: www.messletters.com
If you need help use the Pine Script Reference Manual, which explains 99% of everything in Pine Script, here: www.tradingview.com
f) As our function now returns different integer values (0 or 1), we can use this info to color the background on the actual chart in case it is 1.
// Calling the Mikilap function to start the calculation
int indi_value = Function_Mikilap(symbol_full, time_frame)
color bg_color = indi_value ? color.rgb(180,180,180,75) : color.rgb(25,25,25,100)
bgcolor(bg_color)
g) To finish this little Pine Script lesson and to achieve our initial targets, we just need to integrate the second indicator (RSI) into the function. We want to use the RSI for 0,5 days (12 hours) and use it to ensure to not go into a long entry in an oversold (< 25) or overbought (> 70) market. We will use RSI (low, 12) within 25 to 45 as the range to go for.
Your tasks:
define new input variables for RSI: src_rsi and length_rsi
define new input variables for the RSI range we want to use: rsi_minand rsi_max(please use the „inline“ format of an input type)
calculate the RSI (src_rsi, length_rsi) inside our Mikilap-function
define a boolean variable (rsi_entry) to check if the calculated RSI value is inside the range (please add as last check the barstate_info)
add the RSI entry check to the Bollinger Band entry check to combine them
Congratulations on finishing the second lesson on Trading View - we hope you found it informative and engaging!
We're committed to providing you with valuable insights and practical knowledge throughout this tutorial series. So, we'd love to hear from you! Please leave a comment below with your suggestions on what you'd like us to focus on in the next lesson.
Thanks for joining us on this learning journey, and we're excited to continue exploring Trading View with you!
1st Pine Script Lesson: Coding an Indicator - Bollinger Band
Welcome to this lesson on Trading View, where we will be learning how to create a Bollinger Band indicator using Pine Script.
Bollinger Bands are a popular tool that helps measure an asset's volatility and identify potential trends in price movement. Essentially, the indicator consists of three lines: a middle line that's a simple moving average (SMA), and an upper and lower band that are two standard deviations away from the SMA. The upper band represents the overbought level, meaning the price of the asset is considered high and may be due for a correction. The lower band represents the oversold level, meaning the price is considered low and may be due for a rebound.
Pine Script is a programming language specifically used for creating custom indicators and strategies on Trading View. It's a powerful tool that allows traders to customize their technical analysis to fit their special trading needs and gain deeper insights into the markets..
In this lesson, we'll be taking a hands-on approach to learning. We'll walk through each step of creating our own Bollinger Band indicator using Pine Script, with the goal of helping you gain confidence in your ability to customize and create indicators that meet your unique trading needs. So, grab a cup of coffee and let's get started!
Step 1: Set up a new chart
Let‘s set up a new clean chart to work with for this example. You will find the menu to manage your layouts on the top right of the TradingView screen.
a) add a new layout
b) rename it to „Mizar Example“
c) select BTCUSDT from Binance
d) set the time frame to 1 hour
e) clean the screen (closing the Volume indicator)
f) save it
Step 2: Coding an indicator
Let‘s code our new indicator („Mizar-Killer-Long-Approach“)and make the possible entry moments visible on the chart. You will find the Pine Editor on the bottom left of the TradingView screen.
a) open the Pine Editor
b) use „Open“ in the Pine Editor menu bar
c) use the item: create a new indicator
d) let‘s use full screen for a better overview use the three dots on the right end of the Pine Editor menu bar and open the script in a separate new browser tab
e) rename it to “Mikilap“ by clicking on the current name
f) save it
Step 3: Coding an indicator
Let‘s start coding Our target:
1. create an own new indicator: Mikilap, which bases in general on RSI and Bollinger Band
2. define the parameter for Mikilap, to select the long entries
3. show the long entries on the chart by - putting a label below the bar - change the background color of the timeframe for the bar on the chart
Initiation/Generals
• Indicator initiation
//Indicator script initiation
indicator(title = "Mizar-Killer-Long-Approach", shorttitle = "Mikilap", overlay = true, max_labels_count = 300)
indicator = Pine keyword for an indicator script
title = Long form of the name
short title = Short form of the name as shown on the chart
overlay = true: output like labels, boxes, … are shown on the chart
false: output like plots, … are shown in a separate pane
• General variables and input
// Coin Pair with PREFIX
// Bitcoin / USDT on Binance as an example / standard value on an 60 minutes = 1-hour timeframe
string symbol_full = input.symbol(defval = "BINANCE:BTCUSDT", title = "Select Pair:", group = "General")
string time_frame = input.string(defval = "60", title = "Timeframe:", tooltip = "Value in minutes, so 1 hour = 60", group = "General")
Using the input type of a variable allows you to change this setting in the setup on the chart without changing the Pine Script code.
Framework Code on Main Level
• Framework code on the main level around the indicator calculation function
// Defintion of a Pine Script individual function to handle the Request and avoid Repainting Errors
Function_Mikilap(simple string coinpair, simple string tf_to_use) =>
int function_result = 0
// placeholder for indicator calculations
function_result
// Calling the Milky Way function to start the calculation
int indi_value = Function_Mikilap(symbol_full, time_frame)
Output on the chart - Part 1
// Output on the chart
// Part 1 - plotting a Bollinger Band for the active CoinPair on the chart
int length = input.int(defval = 21, title = "BB Length:", group = "Bollinger Band Setting")
src = input(defval = close, title="BB Source", group = "Bollinger Band Setting")
float mult = input.float(defval = 2.0, title="BB Standard-Deviation", group = "Bollinger Band Setting")
upper_band = ta.sma(src, length) + (mult * ta.stdev(src, length))
lower_band = ta.sma(src, length) - (mult * ta.stdev(src, length))
upper = plot(upper_band, "BB Upper", color=#faffaf)
lower = plot(lower_band, "BB Lower", color=#faffaf)
fill(upper, lower, title = "BB Background", color=color.rgb(245, 245, 80, 80))
Done for today!
• Let‘s save our current script and take a look if we see our Bollinger Band plotted on the chart.
• Step 1: Save (top right)
• Step 2: check in the compiling section, that there are no errors (separate pane below the code)
• Step 3: go to the Mizar Example chart and add an Indicator
How does it look now?
You will see the Bollinger Band as a yellow area around the candles. By pressing the „Settings“ button behind the name of our indicator, the menu for Mikilap will open and you can adjust all the settings we have done with input type variables.
Congrats if you‘ve made it until here! Get prepared for the next lesson, where we will continue with the indicator/entry logic.
The Philosophy of Selling Technical IndicatorsWith a rather odd & convoluted history, the industry of selling access to technical indicators goes back further in time than most traders & investors are aware of.
A rather large majority of investors perceive the act of selling access to technical indicators as being in most relation to selling 'snake-oil'.
While this is true for many vendors who unfortunately market indicators as a 'get rich quick' scheme for trading, it's not true for every vendor.
In this article we are going to do a deep dive exposing what makes a bad vendor, going through the history of indicator vendors, and outlining how vendors can actually have an overall positive impact for the community.
Disclaimer: LuxAlgo is a provider of technical indicators (mostly free, but some paid), however, we will try to be as un-biased as possible in this piece. This article is purely for informational & educational purposes for the greater community.
🔶 WHAT MAKES A GOOD VENDOR?
We could summarize this as a vendor who first & foremost follows TradingView vendor requirements , develops quality products, cares about the community, truly acknowledges that past performance is not necessarily indicative of future results, and has good business practices.
A step by step ruleset to follow of how to be a good vendor could be as follows:
🔹 1. Publish open-source scripts
Aside from the paid scripts, vendors should be easily able to contribute other publications with open-source code for the greater community.
Come on, let the world see that code! There shouldn't be any hesitation to contribute open-source scripts if a vendor is deeming themselves good enough to sell private indicators, right?
Well, there's not many other ways to immediately tell if their products are "quality" if a vendor has no open-source publications to show for themselves as a developer.
If someone is going to sell indicators, we believe in our opinion that they should be able to contribute to the community with open-source work as well in a notable way. This can also be a vendor's way of "giving back" or at least just a way to show they care about the community.
Many vendors completely disregard publishing open source as a means to building a community & also being contributive to the great platform with a userbase they're building a business on top of, while in fact, it does all of this in an extremely productive way.
A possible reason why many vendors do not prioritize publishing open-source scripts could be that they don't know how to do so in any case, so they stick to private script publications mostly (or entirely) to avoid having to be in the public eye of the broader TradingView / Pine Script community.
🔹 2. Don't use misleading marketing practices
Indicators can be marketed as quality, efficient, comprehensive, educational, and supportive tools for traders / investors.
There is a balance a vendor must have when it comes to marketing a technical indicator as a product.
To be clear, of course, it is only logical & common sense to display a product as 'good', and there's nothing wrong with that.
However, if a vendor goes too far, such as saying, "Our indicator has an 89% win rate!" or "How to turn $1k into $100k!" or even "Revealing the game-changing secret weapon that made trader $1M on 1 trade!" - then a vendor is simply using bad practices to acquire customers.
A great analogy can be an advertisement for a food company such as Pizza Hut. Of course, they want to make the pizza look great with excellent visuals, good lighting, & shiny cheese, however, they don't tell you by eating the pizza it will get you a 6-pack rock hard abs.
The same can be applied to marketing technical indicators as products. Of course, a vendor can display their product functioning well in good market conditions primarily, however, by claiming it has any sort of "win-rate" or guaranteed profits, a vendor is being misleading.
The only difference between the Pizza Hut ad & the technical indicator ad being it pertains to the analysis of financial markets, so, in general there should also be proper disclaimers where fit to address consumer expectations using such products.
🔹 3. Don't be misleading in your branding, either.
This goes hand-in-hand with the point made above on marketing.
If a brand itself is in relation to generating profits like "Profit-Bot" or a product / feature is called "10x-Gains-Moving-Average"... the vendor is likely en-route to problems in the long run with the business (bad reviews, business disputes, poor community, etc).
A great business is made on transparency, providing value, caring about customers, and making a difference within an industry for the better.
The more a business does good by customers, the healthier the business will be, & the longer the business will last.
Within the space of technical indicators as products, no matter how transparent the marketing / website is, many customers will still have the impression that they will use these products to help themselves 'make profits'.
While this is of course mostly everyone's goal being involved in financial markets in the first place, it calls for a good balance in the presentation of the indicators as well as setting expectations clear by communicating realistic expectations to customers as best as possible.
One thing vendors can easily do to be transparent, honest, & an overall good actor in the industry is to provide a generous refund policy to ensure consumers who may still have the wrong idea about the intended usage have the opportuntiy to move on with a full refund.
Executing on a good refund policy tends to be the most successful strategy for vendors opposed to free trials even for managing expectations because free trials can attract even less experienced traders who don't want to take the time to learn the product itself no matter how many times they have directed to not follow indicators blindly.
There are many instances of where this is seen as similarly true within digital products in general such as plug-ins, educational programs, etc.
🔹 4. Create unique products
This should be a given, however, it's something we thought we should mention as many vendors tend to impersonate or completely mimic other products already existing in hopes of theirs attaining the same level of attention.
The reality is most technical indicators as products have already seen a high level of adoption from the broader community and it universally is known to them that there are knockoff products existing already.
Joining forces with the knockoffs is not a good bet in any endeavor and we believe that originality can go a long way in this industry as well.
🔶 WHAT MAKES A BAD VENDOR?
Well, this can be easily summed up in 1 image of course.
You know what they say, if something sounds too good to be true... it isn't.
If someone is standing in front of an exotic car, flashing cash, and telling you they got this rad lifestyle by using their trading indicator... it should immediately raise 1,000 red flags for you.
There's no such thing as getting rich quick, especially based on the functionality of a technical indicator. Period.
This type of malicious marketing is extremely harmful to people as it directly gives them false hopes, plays into desperation, and is from a common-sense perspective; a deceptive marketing tactic used by charlatans.
Bad vendors do not publish any open-source contributions and primarily just stick to marketing indicators in misleading ways that overall harm the community.
There are many potential reasons as to why vendors market indicators in misleading ways:
1.) They don't understand indicators & they are actually snake-oil salesmen (image above).
2.) They do understand indicators, maybe have something decent developed, but just don't know how else to market indicators other than promising profits.
3.) They may have tried marketing in non-misleading ways before, found that misleading marketing is producing the most sales for them, so they became fueled with greed & doubled-down on the misleading claims when marketing their product regardless. (Instead of trying to build a reputable business).
🔶 WHY & HOW VENDORS CAN BE GOOD FOR THE COMMUNITY
Vendors have the power to reach more people, since at the end of the day, there is a business established behind them with marketing efforts.
We believe that people will buy indicators no matter what and that this is a real established market as products for traders, regardless of what the majority of investors think of it.
So, as long as there are good actors primarily at the top of the industry, this is what's best for the community overall, and possibly the overall perception of indicator vendors can change eventually.
Good acting vendors with the right practices as listed earlier in this article are able to educate more people through marketing their products, community growth, & open-source contributions that they publish as well.
All in turn, growing the broader interest in the scripting community which helps grow technical analysis further by having a larger number of users provide feedback to each other & further improve the space over time.
In the case of LuxAlgo as a provider for example, it would not have been possible to grow a TradingView following of 200,000+ without the marketing efforts outside of TradingView on platforms like YouTube, Instagram, and even TikTok for all indicators we have created (free & paid).
Which has certainly grown into a large community, which over time has meaningfully contributed to the interest in custom technical indicators & the scripting community overall in general.
In the case of a bad acting vendor, this is the exact opposite & bad for the community overall because they do not make any good contribution to the community and just merely exist to try & sell access to their private indicators.
🔶 DO PAID INDICATORS "WORK" BETTER THAN FREE INDICATORS?
If you are defining the word "work" as "make more profits", then the answer is a hard no in all cases.
If you are defining the word "work" as in "being more useful", then it truly just depends on how comprehensive or unique the indicator is.
We believe that indicators are best used as supportive tools for decision making, so it's important to be asking this question in the right context & with this understanding when considering a product.
In the context of LuxAlgo Premium indicators specifically, we believe the answer is yes due to how the indicators were designed as all-in-one toolkits that include presets, filters, & various customization/optimization methods specifically designed to help traders embrace their trading style.
The position for paid indicators to exist under a subscription model is primarily done since indicators can be frequently updated / improved over time based on the user's feedback.
There are, however, other aspects of paid indicators which could be legitimately more useful than anything you can find for free in some other cases such as unique volume-based tools, extensive market scanner scripts, etc.
Although, it is quite limited when it comes to traditional technical indicators such as moving averages or signal-based indicators to make a strong argument that one is better than another in any meaningful way.
In most cases, you can take one indicator and overfit it to appear "better" or "more accurate" than another indicator by finding more specific market conditions or settings that has an advantage over another.
As a technical analyst, you begin to understand this once you have experimented with vast amounts of technical indicators with different use cases and have thoroughly reflected on its actual benefits to you. It's truly impossible to make an alternative argument in all cases, including debatably all paid technical indicators in existence right now.
🔶 THE REAL VALUE PROPOSITION OF PAID TECHNICAL INDICATORS
Since we can conclude in mostly all scenarios that paid indicators don't "work" better than free indicators in a technical sense when referring to its accuracy or direct visual aid to a trader, it begs to question what the actual value proposition can be for a vendor selling access to indicators.
A large part of the alternative value prop for a vendor may fall under the community & education that it provides under the brand, or additionally, the prospect of a vendor making paid indicators more interoperable with other applications such as large-scale alerts systems or cross-platform functionality.
Many vendors may try to create value propositions for their paid indicators by hosting a signal group where analysts callout trades using their paid indicators, however, this typically will be done in misleading ways over-hyping the usage and is not generally a good practice for vendors or users in our opinion.
With all of this mentioned, it may seem that the entire industry is full of charlatans at times, however, we do not believe the space will remain like this forever.
🔶 SHOULD THIS BE A MORE LEGITIMIZED INDUSTRY?
The history of paid indicators goes all the way back to the 1980's with John Ehlhers & Mark Jurik being two notable figures providing paid tools through websites on various charting platforms.
There was also a rather strange ecosystem of products with generally 'awkward' branding existing on older charting platforms since the early 2,000's. Some of which on these platforms still exist to this day. While interestingly enough, practically none of these brands ever grew past being considered small plug-ins.
Some considerably large educational programs / memberships throughout the 2,000's (& some existing still to this day) have implemented indicators as a part of their offerings, although they typically tend to integrate indicators only to add on to their sales funnel styled websites in hopes to add unique value to their "life changing online course" positioning, so we won't mention any names.
Additionally, while most new traders are likely unaware, TradingView had an app-store marketplace themselves in the 2010's called "marketplace add-ons" where users could purchase indicators from various vendors within their indicators tab alongside the Public Library now called Community Scripts.
Likely as the TradingView platform & Pine Script was mass-adopted on a larger scale, this marketplace was discontinued for various reasons with the adoption of invite-only scripts, where anyone with a premium account can manage access on these types of script publications.
This pivotal shift leveled the playing field for the industry whereas it created a new ecosystem of vendors who all could leverage their ability to manage access to users without appearing as "just another marketplace add-on", but rather, actual brands themselves.
While keeping this piece as un-biased as possible, this is where LuxAlgo was born, & generally speaking, was primarily the inspiration for the hundreds of "Algo" brands popping up all over the internet trying to sell TradingView indicators due to our notoriety in this environment.
In this current landscape, we believe there is an established ecosystem that has potential to mature further into a 'healthy' industry, so to speak... as mentioned earlier, just as long as there are more good actors leading it than bad.
We are also hopeful for platforms to recognize this evolution themselves & directly support the ecosystem to grow more efficiently with stronger operations over time while still allowing these brands their own independence as they have now.
It's very optimistic considering the realization of how popular the ecosystem has become & with the prospect of vendors within it to lead it in positive ways, which overall brings more people to TradingView & grows genuine interest in the Pine Script community from all over the internet very effectively.
🔶 CONCLUSION
We strongly believe indicator vendors will always exist in some capacity considering the 30–40-year history, the rise of digital products on the internet, as well as the growing popularity of indicator vendors in this current landscape. Considering this, it's important to ensure the brands leading the space are good actors so the space itself can mature long-term.
As a prominent figure in this industry, we hope from this article to have provided a lot of transparency for the broader community of traders & investors who may not have been aware of this space in such detail, as well as for any aspiring vendors to hopefully look to us and what we have outlined as a good role model / checklist for the sake of making this industry more legitimized in the future.
Thank you for reading!
- Sean Mackey (Founder @LuxAlgo)
Credits
Alex Pierrefeu (TV profile @alexgrover) for being a massive leader in LuxAlgo since the beginning & going deep all the time creating theories w/ me about technical analysis & the industry with genuine fascination.
John Ehlers for being what we call the grandfather of this entire industry dating back to the 1980's with MESA Software.
Mark Jurik as a serious 'wave maker' with Jurik Research and for leading the way in the early 2,000's as a provider of unique tools.
@ChrisMoody for being a real "OG" in the TradingView community & for some cool discussions about the history of the industry early on.
All of the amazing users of LuxAlgo Premium since early 2020 and the entire community who provide us feedback to improve our indicators over time.
Everyone in the Pine Script community who follows us on TradingView & enjoys our contributions.
The @PineCoders team for being extremely helpful moderating the platform & for listening to our feedback / dealing with us throughout the years.
And lastly @TradingView for being the greatest platform for traders / investors and for making all of this possible in the first place.
How to Choose the Right Indicator?Many traders, especially when starting out find themselves in a constant search of the best trading strategy.
A quick Google search is enough to scare anyone starting out, as the number of indicators and strategies to use under different market conditions is overwhelming.
🗒In this article, we will discuss *1* indicators nature and the correct way to use it, *2* how to choose the right indicator, and most importantly *3* how to know if the indicator is reliable or not.
---------------------------------------------------------------------------------------------------------------------
📌 First, what are indicators? Origin and Nature
Indicators are statistical tools that digest price data, OHLC of each candle, add a formula to it, and then convert it into visual information such as graphs or oscillators. Indicators provide information about the strength of a trend, momentum, and possible reversals.
When it comes to indicators, we can divide them into four classes: Momentum indicators, Trend indicators, Volatility indicators, Volume Indicators.
Knowing which one belongs to which category can help you make much better trading decisions. On the other hand, combining indicators in a wrong way can lead to a lot of confusion, wrong price interpretation, and, subsequently, to wrong trading decisions.
📌 The correct way to use indicators. Indicators don’t provide signals.
Most traders never look at the indicators they are using and even less have ever tried to understand the formula the indicator uses to analyze price. They then use their indicators in the wrong context and wonder why nothing works.
🗒Indicators don’t tell you when to buy or when to sell. They don’t even tell you when something is overbought or oversold.
Indicators are great tools if a trader understands their true purpose. Indicators provide information about price, how the price has moved, how candles have shaped, and how recent price action compares to historical price action. Again, not a direct signal to buy or sell.
Thus, the job of a trader is to interpret the information on their indicators in a meaningful way and turn it into a story about price action and buying/selling pressure.
Who is in control right now? Is the market ranging or trending? Is price losing strength or gaining momentum?
📌 How to choose the right indicator? That suits your trading style and personality
-----------------------------------------------------------------------------
📕 * Meaningful: Represents important information.
-----------------------------------------------------------------------------
Your indicator choice should match your trading style. The purpose of indicators/strategies is to offer a way to identify clues and to provide a framework for traders to work in. Our main job, as traders, is to collect clues and combine them in a meaningful way to have an edge over the market.
🗒 Only add indicators that help you put the odds in your favor. -- If it doesn’t, you don’t need it.
-----------------------------------------------------------------------------------------------------------
📕 * Objective: Has a clear operational definition of what is being measured.
-----------------------------------------------------------------------------------------------------------
Indicators are ideal for rule-based trading as indicators take out the guesswork by providing information that is totally objective especially for newbies who are struggling with discipline.
The most successful strategies/indicators are those where not a lot of individual interpretation is required.
🗒 Only use indicators that help you make objective decisions. -- If it doesn’t, you don’t need it.
-----------------------------------------------------------------------------------
📕 * Understandable: Easy to comprehend and interpret.
-----------------------------------------------------------------------------------
Indicators are great tools especially for amateurs who do not know how to relate price data into meaningful relationships.
Indicators' main purpose is to make your life easier, not more sophisticated.
🗒 Remember: K.I.S.S. Keep it simple stupid! -- If it is complicated, you don’t need it.
📕 Last but not least, less is more:
The problem with indicator redundancy is that when a trader picks multiple indicators that show the same information, he/she ends up giving too much weight to the information provided by the indicators.
🗒 “All Strategies / Indicators are good; if managed properly.”
~ Richard Nasr
---------------------------------------------------------------------------------------------------------------------
📌 How to know if the indicator is reliable? Cheat Sheet Checklist
📕 * Does it repaint, disappear or recalculate?
We have all been there. An indicator looking good /profitable on the chart, but perform horribly under live market conditions. Most indicators are designed to only show/keep winning signals. Do not, ever, include an indicator in your trading plan before testing it on a demo account.
🗒 Here is a simple step by step guide on how to test indicators:
- Attach your indicator to any chart.
- Keep your trading platform running for a while for the indicator to plot a couple of signals.
- Take a screenshot of the chart.
- Refresh by switching between the timeframes.
- Compare your chart with the screenshot
If the indicator’s signals /drawings change location or disappear, then it is a red flag. Such indicators are not reliable and shouldn’t be used in any way.
📕 * Does it lag?
In general, indicators are lagging, but so is price action. An indicator can only analyze what has happened already. Just as a candlestick or chart pattern only includes past price data.
Nothing to worry about so far, as we mentioned above, indicators only provide information and do not offer signals.
However, some indicators are too lagging. This kind of indicators looks good on historical data but appear too late under live market conditions.
🗒 Pro Tip: Always take into consideration when, where, and how does the signal appear.
📕 * Is it TradingView friendly?
90% of custom indicators do not work on TradingView, because PineScript does not allow recalculation. Thus, the signal/drawing can’t be modified once it is generated by the indicator.
Therefore, indicators that are available on TradingView stand out from the crowd, and they are considered more reliable.
---------------------------------------------------------------------------------------------------------------------
📌 In brief, indicators are very famous tools and used by millions of traders. However, often traders don’t really know what their indicators are doing or how to use them.
Always be aware of the objectives of your trading style and what you are trying to accomplish with the indicators. Then, adjust accordingly. Once a trader can stop using indicators as signal-tools, he will be able to transform his trading to new heights.
Happy trading!
Always follow your trading plan regarding entry, risk management, and trade management.
~Rich
TRADINGVIEW PINESCRIPT CODERS PRO+ USER NEEDS TRADERS , I'm looking for pine script coder, programmer to create me a automated indicator that can calculate my new (TDV) TOP DOWN VOLUME ANALYSIS INDICATOR idea, using the multi time frame top down analysis approach, I came up with this idea based on math, time frames, percentages of volume calculating it manually taking the color (red) for bearish/shorts and (green) bullish/longs of the last 3 out of 5 candle volumes in each time frame from 1m to 1w with total time frames (18) giving each TF a value #1-3 giving more value and weight to the higher TF and lower values weight to the lower as that's how top down analysis multi time framing work's I'm putting sample on screen with description and my new TDV ANALYSIS logo. IF ANYONE IS INTERESTED IN BUILDING/CREATING THIS INDICATOR please pm me on here so we can talk, just want to say that many traders believe price is king and most indicators are lagging but i believe VOLUME is the true king because its what pushes price and momentum and volatility so i believe there can be a holy grail indicator that has not been adopted or built yet and i think this idea has very good merits and could be just that, a all 4 in one leading indicator to take buy and sell trades based on volume alone as long as you know if its the bulls or bears with the volume power, a signal of say 100% bullish or bearish volume could be a great catalyst for a nice price move and momentum once alerted or signaled.
thanks guys, tradingbugtech & traderdadzz
TRADINGVIEW PINESCRIPT CODERS PRO+ USER NEEDS YOUR HELP ! traders i am looking for help creating a volume strength indicator i have created and back testing manually, everyone believes price is king but i believe price is just the amount of traders trading and how much volume dictates price action, indicators today are great and i do use them 2nd to price action and volume but believe volume is the true king so i created a idea using multi time frame top down method like dr. elders triple screen, im using (14) time frames and getting the most recent 5 bars volume and taking the average of the 5 bars and giving each time frame a vale 1-3% giving the lowest time frames the lowest number percent and the higher time frames the higher value percentage, then i add up each bull/bear volume and put it in a standard win rate calculator to get the winning volume percentage average, im now back testing manually every 1h if i were looking for trade set ups on the hourly tf and the 4h for day trades and intraday trades have written a pdf with all the details on how im back testing and what i want the indicator to signal for buys and sells based on the percentage of overall volume i have manually calculated using my values, please is anyone interested in building this pine script indicator i want to use on trading view as a paid subscription service once its been back tested and has a good win ratio/rate, anyone ,all trading view coders if u think u are interested in building and testing with myself please pm me, thank you.
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
Tutorial - Convert an indicator into strategy in pineHello Everyone,
I just made this video because, this question came up many times in Pine QA. In this video we are trying to load default Bollinger Band indicator from Tradingview and convert it into strategy.
Below are the steps
Load the indicator on chart
Click on source code (curly brackets next to indicator title) to load the code into your pine editor.
Make copy of the script. Remove the indicator on chart and load your copy of the script from pine editor
Replace indicator call with strategy call
Define your entry/exit conditions for long and short
Add strategy.entry, strategy.exit, strategy.close calls based on the conditions to generate trades on chart
Useful references
Pine Reference Manual
www.tradingview.com
Strategy template in the linked ideas.
Enjoy :)
Making A Signal In Tradingview Pinescript In Under 20 MinutesHave you ever wanted to combine two technical analysis indicators into a single signal to find your own way of making profit? This video is a tutorial where I take two stock Tradingview Pinescript indicators and combine them into a signal that makes it easier for the user to spot with their eyes when an even occurs on a chart. By following along I hope the viewer can learn the basic process of repeating this for their own research!
Candlestick Analysis SOL/USDT Hello Trading Community...
Ive been working on a factual analysis for some time now, it paints a PB text when a candle doesn't close lower than the previous 3,4,5.
As I am new to trading and pine scripts its a very basic script which seems to work when in AOI (Area of Interest) such as Support, lower channel trendline and near 50/100EMA when in an uptrend.
HTF fractals hold more strength and I tend to go with the HTF's and to alert the time of confirmation candle (which is when a either the 2nd or 3rd candle closes higher than the high of the PB)
This on its own doesn't hold weight and I like to see this as a poker game, the stronger my hand is, the more I am inclined to play the hand.
Your feedback would be most appreciated .
One divergence indicator to rule them allGreetings Traders,
We are continuing with our (mini) series in which we break down the (seemingly endless) features of The Divergent indicator.
Today we are going to discuss the various oscillators The Divergent supports detecting divergences on.
In contrast to other divergence indicators on TradingView, The Divergent comes with oscillators built-in. This means you won't have to add it on top of other indicators on your chart; it is completely standalone. Why is that a good thing? It is because The Divergent respects your indicator quota - it will only use up a single slot on your chart.
The Divergent ships with the following oscillators:
MACD (Moving Average Convergence Divergence)
RSI (Relative Strength Index)
CMF (Chaikin Money Flow)
Stochastic RSI
MFI (Money Flow Index)
TCI (Trading Channel Index, aka. WaveTrend)
Balance of Power
CCI (Commodity Channel Index)
Awesome Oscillator
Each oscillator is fully customisable, allowing you to tweak them the way you desire. To choose another oscillator, simply open The Divergent 's settings panel, and select a different one from the list.
A further benefit of having the oscillators built into the indicator, is that it opens up the possibility to apply various filters to the detected divergences. For example, if you have the RSI selected, you can configure The Divergent to only signal those RSI divergences, that manifest under the oversold or above the overbought areas. These filters will be introduced in detail in future articles.
To learn more about The Divergent , please see the related ideas linked at the bottom.
If you liked this post, please don't forget to give it a thumbs up!
If you have any questions, please feel free to ask in the comments section below.
Thank you for your attention!
How to send Divergence signals to your Discord server- Do you have a Discord server set up for your own trading community?
- Do you use divergences as part of your trading strategy?
- Would you like to send automated notifications to your Discord server whenever a divergence appears on any chart?
If you have answered yes to all 3 questions above, please keep on reading.
The easiest way to receive automated Divergence alerts to your Discord server, is to combine the alert messages from "The Divergent" divergence indicator on TradingView with a Webhook endpoint on your Discord server.
Step 1: Open Discord, and go to Server Settings
Step 2: Go to Integrations and create a new Webhook
Step 3 (optional): Rename your Webhook to "The Divergent (Divergence indicator)"
Step 4: Select the channel you wish to receive the divergence signals to (i.e. #divergence-signals)
Step 5: Save your Webhook
Step 6: Copy your Webhook URL to your clipboard and head over to TradingView
Step 7: Apply "The Divergent" or "The Divergent (Pro)" indicator to your chart and configure it as you prefer (The free version of The Divergent can signal Regular Divergences only, while the Pro version can signal both Regular and Hidden Divergences)
Step 8: Create a new alert, select "The Divergent" from the top drop down and select one of the Divergence signals (i.e. Regular Bullish)
Step 9: Use the Webhook URL from your clipboard as the Webhook URL of the alert
Step 10: Use the following alert message:
{"content": "The Divergent detected a Regular Bearish Divergence (RSI) on {{exchange}}:{{ticker}} ({{interval}}) @TradingView #divergence $BTC "}
Sample message delivered on Discord:
"The Divergent detected a Regular Bearish Divergence (RSI) on BINANCE:BTCUSDT (60) @TradingView #divergence $BTC"
Feel free to change the content to match your chart / type of divergence you are signalling in the alert.
Note : It is important that you format your alert message as a JSON string, and that you key the message with "content". If you have never used JSON before, it is a good idea to validate your message via jsonlint.com to make sure it is a valid JSON string.
Repeat the same steps for other charts / divergences. Create as many alerts, as many markets / divergences you want to signal to your Discord server.
If you have any questions, please feel free to post it in the comments section below.
If this tutorial was helpful to you, please consider giving it a thumbs up!
Thank you!
The easiest way to use divergences in your own Pine strategiesDetecting divergences in a Pine indicator / strategy is easy.
You simply have to compare the pivot lows and the pivot highs on the price and the oscillator, and if you can identify a difference between the last & previous pivots made on the price and the oscillator, you have likely found a divergence.
Using this theory, here is an example how you would detect a Regular Bearish divergence:
While the theory of divergence detection is simple, more often than not, things go wrong (the divergence indicator used in the example below is TradingView's built-in Divergence Indicator ):
Would you identify this as a divergence? If not, why not? Is it because the divergence line is slicing through the candles? Or because the line is slicing through the oscillator? Or something else?
Wouldn't it be great if somehow you could filter out invalid divergences from code, such as this one?
We at Whitebox Software were wondering about the same thing, and decided to find a solution to this problem. This is when we realised that while detecting divergences is easy, detecting valid divergences is hard...
After several months in development, we are proud to present to you our divergence indicator called The Divergent .
The Divergent is an advanced divergence indicator with over 2500 lines of Pine Script, exposing over 30 different configuration options, including 9 built-in oscillators, to allow you to tweak every aspect of divergence detection to perfection.
For example, the Line of Sight™ filter in The Divergent would have easily filtered out this invalid divergence above. The Line of Sight™ filter will notice any interruption to the divergence line connecting the price or the oscillator, and will treat the divergence as invalid.
This filter is one of many, which has been created to reduce the false positive detections to a minimum. (In later publications, we will discuss each and every filter in detail).
Alright, so The Divergent knows how to detect accurate divergences, but how is it going to help you detect divergences in your own Pine strategy?
The Divergent is not simply a divergence indicator - it can also emit divergence signals * which you can catch and process in your own strategy. You can think of The Divergent being a DaaS ( D ivergences a s a S ervice)!
* Please note, that divergence signals is a Pro only feature.
To use the signals, simply place The Divergent onto the same chart you have your strategy on, import "The Divergent Library" into your code, link your strategy to The Divergent using a "source" input, and act on the signals produced by The Divergent !
Here is a simple strategy which incorporates divergence signals produced by The Divergent in its entry condition. The strategy will only open a position, if the moving average cross is preceded by a regular bullish or bearish divergence (depending on the direction of the cross):
//@version=5
strategy("My Strategy with divergences", overlay=true, margin_long=100, margin_short=100)
import WhiteboxSoftware/TheDivergentLibrary/1 as tdl
float divSignal = input.source(title = "The Divergent Link", defval = close)
var bool tdlContext = tdl.init(divSignal, displayLinkStatus = true, debug = false)
// `divergence` can be one of the following values:
// na → No divergence was detected
// 1 → Regular Bull
// 2 → Regular Bull early
// 3 → Hidden Bull
// 4 → Hidden Bull early
// 5 → Regular Bear
// 6 → Regular Bear early
// 7 → Hidden Bear
// 8 → Hidden Bear early
//
// priceStart is the bar_index of the starting point of the divergence line drawn on price
// priceEnd is the bar_index of the ending point of the divergence line drawn on price
//
// oscStart is the bar_index of the starting point of the divergence line drawn on oscillator
// oscEnd is the bar_index of the ending point of the divergence line drawn on oscillator
= tdl.processSignal(divSignal)
bool regularBullSignalledRecently = ta.barssince(divergence == 1) < 10
bool regularBearSignalledRecently = ta.barssince(divergence == 5) < 10
float slowSma = ta_sma(close, 28)
float fastSma = ta_sma(close, 14)
longCondition = ta.crossover(fastSma, slowSma) and regularBullSignalledRecently
if (barstate.isconfirmed and longCondition and strategy.position_size == 0)
strategy.entry("Enter Long", strategy.long)
strategy.exit("Exit Long", "Enter Long", limit = close * 1.04, stop = close * 0.98)
shortCondition = ta.crossunder(fastSma, slowSma) and regularBearSignalledRecently
if (barstate.isconfirmed and shortCondition and strategy.position_size == 0)
strategy.entry("Enter Short", strategy.short)
strategy.exit("Exit Short", "Enter Short", limit = close * 0.96, stop = close * 1.02)
plot(slowSma, color = color.white)
plot(fastSma, color = color.orange)
One important thing to note, is that TradingView limits the number of "source" inputs you can use in an indicator / strategy to 1, so the source input linking your strategy and The Divergent is the only source input you can have in your strategy. There is a work around this limitation though. Simply convert the other source inputs to have a string type, and use a dropdown to provide the various sources:
string mySource = input.string("My source", defval = "close", options = )
float sourceValue = switch mySource
"close" => close
"open" => open
"high" => high
"low" => low
=> na
---
This is where we are going to wrap up this article.
We hope you will find the signals produced by The Divergent a useful addition in your own strategies!
For more info on the The Divergent (Free) and The Divergent (Pro) indicators please see the linked pages.
If you have any questions, don't hesitate to reach out to us either via our website or via the comment section below.
If you found value in this article please give it a thumbs up!
Thank you!
POW Edge Reversal is HERE 🚀🚀🚀🚀🚀🚀🚀We've been sharing ideas on this strategy for quite some time now as part of our 'forward testing' approach and log.
In this video, I run through the strategy, how it works and how it can help.
Everything we do at POW is based on 'proof it works' - this is no different and you'll see this in the data I run through for you.
Any questions about gaining access please drop me a DM on here.
This just shows how powerful Pine script is - to automate a strategy and confirm you have an edge in the market.
Removing stress, decisions, overwhelm and all of the emotional struggles trading can bring.
Let me know in the comments what you think please - be nice right 😅?
Please scroll through some of my previous ideas to see some trades in action.
Regards
Darren
Slow progress on the DOGE Coin.While new ideas are great, it is also important to follow up with any results. Here in accordance with the slow move and due to pressure, we traced a new trend line. That, show the little progress and again, pressure as a resistance. We then understand, that it is also important to look for a watch of a break of some kind, when it will happen. The more sell signals shown, the more resistance, the opposite for support.
For educational purposes only and not intended a financial advice of any kind.






















