Thinking in Pine - Study References Too Many Bars In the HistoryWelcome to "Thinking in Pine" short video series on the topics of Pine Script.
Today's topic is handling the error - "The study references too many candles in the history" and other bar_index related issues.
If you are not familiar with Pine Script time series concepts, please go through our previous videos.
Thinking in Pine - Time Series
Thinking in Pine - Special Cases of Time Series
🎲 Points Discussed
When do we get the error "Study references too many candles in the history" and how to overcome this issue.
bar_index limitations with drawing objects on the chart.
🎯 Example Program - Historical Reference Alternative Implementation
// When we are trying to refer to history more than or equal to 10000 bars older
// float value = close
// plot(value)
// Alternative implementation
var values = array.new()
values.unshift(close)
// Throws error on first bar since the number of items is less than 10000
// float valueFromArray = values.get(10000)
// plot(valueFromArray)
//Option 1 - Get the last available value when the number of bars available is less than 10000
float valueFromArray1 = values.get(math.min(bar_index, 10000))
plot(valueFromArray1)
// Option 2 - If number of available bars less than 10000, then set value to na else get the value of 10000 bars back
float valueFromArray2 = values.size() <= 10000? na : values.get(10000)
plot(valueFromArray2)
🎯 Example Program - Drawing Object Limitations with Bar Index
// Trying to create a line too far in history or in future
// if(barstate.islast)
// Throws error as can only draw upto 9999 bars before
// ln1 = line.new(bar_index, high, bar_index-10000, high)
// Throws error as we can only draw upto 500 bars in the future.
// ln2 = line.new(bar_index, high, bar_index+501, high)
startingPoint = ta.valuewhen(bar_index == last_bar_index-10000, time, 0)
float price = 0.0
if(barstate.islast)
// However, we can draw more than 10000 bars back or more than 500 bars in the future using time instead of bar _index
ln = line.new(time, high, startingPoint, high, xloc=xloc.bar_time)
// Cannot use line.get_price when the line is drawn using xloc = xloc.bar_time
// price := ln.get_price(last_bar_index-5000)
Trendoscope
Thinking in Pine - Tricks and Tips of DebuggingWelcome to "Thinking in Pine" short video series on the topics of Pine Script.
Today's discussion point is debugging and tools that Pine script provide us to debug our programs.
🎲 Points Discussed
Debugging using `plot` for numerical series values.
Using Pine Logs to debug for cases where `plot` is not suitable
🎯 Example Program - Debugging using plot
length = input.int(14, 'Length')
multiplier = input.float(4, 'Multiplier')
var dir = 1
var stopDistance = ta.atr(length) * multiplier
// Remove var to fix the first issue
// stopDistance = ta.atr(length) * multiplier
buyStopCurrent = close-stopDistance
sellStopCurrent = close + stopDistance
var buyStop = buyStopCurrent
var sellStop = sellStopCurrent
buyStop := dir > 0? math.max(buyStop, buyStopCurrent) : buyStopCurrent
sellStop := dir < 0? math.min(sellStop, sellStopCurrent) : sellStopCurrent
// Use nz to overcome na issues with math.max/ math.min
// buyStop := dir > 0? math.max(nz(buyStop, buyStopCurrent), buyStopCurrent) : buyStopCurrent
// sellStop := dir < 0? math.min(nz(sellStop, sellStopCurrent), sellStopCurrent) : sellStopCurrent
dir := dir == 1 and close < buyStop? -1 : dir == -1 and close > sellStop ? 1 : dir
// Plot statements used for debugging. display is set to display.data_window as the debugging plots do not need to appear on the charts
plot(stopDistance, 'Stop Distance', color.purple, display = display.data_window)
plot(buyStopCurrent, 'buyStopCurrent', color.red, display = display.data_window)
plot(sellStopCurrent, 'sellStopCurrent', color.green, display = display.data_window)
plot(buyStop, 'buyStop', color.red, display = display.data_window)
plot(sellStop, 'sellStop', color.green, display = display.data_window)
plot(dir, 'Direction', color.white, display = display.data_window)
plot(dir > 0? buyStop : sellStop, 'Supertrend', dir > 0? color.red : color.green)
🎯 Example Program - Pine Logs
sum = 0
arr = array.new()
for i = 0 to 10
sum+=i
// Log on every bar and also on every tick on real time
// log.info('Sum at iteration {0} is {1}', i, sum)
// Run only for the first bar
// if(barstate.isfirst)
// log.info('Sum at iteration {0} is {1}', i, sum)
// Run on the last confirmed bar
// if(barstate.islastconfirmedhistory)
// log.warning('Sum at iteration {0} is {1}', i, sum)
// if(barstate.isrealtime)
// log.warning('Sum at iteration {0} is {1}', i, sum)
// Display only once
// varip showLog = true
// if(barstate.isrealtime and showLog)
// log.warning('Sum at iteration {0} is {1}', i, sum)
// if (i == 10)
// showLog := false
// Extract through the array and log outside the loop
arr.push(sum)
// Log the extracted array on real time and print only once
varip showLog = true
if(barstate.isrealtime and showLog)
log.error('Sum at different iterations : {0}', arr)
showLog := false
plot(sum)
🎲 References
Pine Logs - Reference Manual
plot - Reference Manual
Thinking in Pine - Execution Model and Rollback on Realtime BarsHello All,
Welcome to another session of "Thinking in Pine" - short video tutorials on Pine Script.
Before continuing with this video, if you are not familiar with var, varip and regular variables, please watch our previous video - "Thinking in Pine - var, varip and regular variables"
🎲 Today's discussion points
How var, varip and regular variable modification code works with historical and real time bar updates.
Rollback concept of var variables
🎯 Example Program Used
// The statements execute on every tick
count = 0.0
count+=1
varip varipcount = 0 //executes only once on the first bar
varipcount+=1
// Reset counter on every bar
// if(barstate.isconfirmed)
// varipcount:=0
// Rollbacks and assigns on every tick
var varcount = 0.0 //executes only once on the first bar
varcount+=1
// varcount:=varcount -- Rollback
// varcount := varcount + 1 -- execute again
plot(varipcount, 'Varip Count')
plot(varcount, 'Var Count')
plot(count, 'Çount')
arrRegular = array.new()
var arrVar = array.new()
varip arrVarip = array.new()
if(bar_index >= last_bar_index -5)
arrRegular.push(close)
arrVar.push(close)
arrVarip.push(close)
log.info('Regular : {0}', arrRegular)
log.info('Var : {0}', arrVar)
log.info('Varip : {0}', arrVarip)
🎲 References
Pine Script® User Manual - Execution Model
Thinking in Pine - Functions Containing Var VariablesHello everyone, welcome back to "Thinking in Pine" short video tutorials. In this video, we have discussed special cases of using var variables inside function definitions.
If you are not familiar with var variables, please take a step back and watch our earlier video - "Thinking in Pine - var, varip and regular variables"
🎲 Summary
Using var within a function scope and how it behaves with multiple invocations.
Using the functions containing var variable definitions within a loop.
🎯 Example Program Used
increment()=>
var i = 0
i+=1
var1 = increment()
var2 = increment()
var3 = increment()
// The code above is equivalent to
// var i1 = 0
// i1+=1
// var1 = i1
// var i2 = 0
// i2+=1
// var2 = i2
// var i3 = 0
// i3+=1
// var3 = i3
plot(var1, "Counter 1", color=color.blue)
plot(var2, "Counter 2", color=color.red)
plot(var3, "Counter 3", color=color.purple)
arr = array.from(var1, var2, var3)
for i=1 to 3
arr.push(increment())
// The code above is equivalent to
// var i4 = 0
// i4+=1
// arr.push(i4)
if(bar_index == 4)
log.info('Value of array containing incremental values : {0}', arr)
🎲 References
Pine Script® User Manual - Variable declarations
Pine Script® Reference Manual - var
Thinking in Pine - Time Series Special CasesHello Everyone,
Welcome back to "Thinking in Pine" short video series. In this session, we have discussed few special cases of time series variables and using historical operator within local scope.
If you have not watched our previous video - "Thinking in Pine - Time Series" , request you to do that before continuing this video.
🎲 Summary of our today's discussion
How historical operator works for variables defined inside an conditional block
How historical operator works for variables defined in a loop.
🎯 Example Program Used
// Time series for variables within a condition
varip showLogInLoop = true
if(bar_index%3 == 0)
specialBarIndex = bar_index
if(bar_index > last_bar_index-3 and showLogInLoop)
log.info('Current and Previous special bar index are : {0} and {1}', specialBarIndex, specialBarIndex )
showLogInLoop := false
// Time series of variables within a loop
arrayOfX = array.new()
arrayOfLastX = array.new()
for i = 1 to 5
x = i*10
arrayOfX.push(x)
arrayOfLastX.push(x )
if(barstate.islastconfirmedhistory)
log.info('Array of X : {0}', arrayOfX)
log.info('Array of last X : {0}', arrayOfLastX)
🎲 References:
Pine Script® User Manual - Execution Model
Pine Script® User Manual - Time Series
Pine Script® User Manual - History Referencing Operator
Pine Script® Reference Manual - History Referencing Operator
Thinking in Pine - Time SeriesHello everyone,
Welcome back to "Thinking in Pine" short video series. In this video, we discuss the concept of time series variables in Pinescript.
If you are not familiar with var and varip type of variables - please step back and watch this video before continuing - "Thinking in Pine - var, varip and regular variables"
🎲 Summary of our discussion is as follows
What are time series variables, and how are they used in Pinescript?
How do we access historical values of time series?
Limitations of accessing historical values
🎯 Example Program Used
currentBar = bar_index
var currentBarUsingVar = 0
currentBarUsingVar := bar_index
varip showLog = true
valueAt200thBar = ta.valuewhen(bar_index == 500, currentBar, 0)
if(barstate.islast and showLog)
log.info("Current Bar Values using regular and var variables : {0}, {1}", currentBar, currentBarUsingVar)
log.info("Last Bar Values using regular and var variables : {0}, {1}", currentBar , currentBarUsingVar )
log.info("Values 500 bars ago using regular and var variables : {0}, {1}", currentBar , currentBarUsingVar )
offset = bar_index-25000
log.info("Values at 25000th bar using regular and var variables : {0}, {1}", currentBar , currentBarUsingVar )
showLog := false
plot(bar_index, "Bar Index", color = color.blue, display = display.data_window)
There are pitfalls of using historical operators within loop or under if condition. We will discuss that in our next video.
🎲 References:
Pine Script® User Manual - Execution Model
Pine Script® User Manual - Time Series
Pine Script® User Manual - History Referencing Operator
]Pine Script® Reference Manual - History Referencing Operator
Thinking in Pine - var, varip and regular variablesThis is our first video session on "Thinking in Pine" series. Before we start, we want to explain a bit about our new initiative.
🎲 What is "Thinking in Pine"?
In our journey to empower the trading community, we're excited to introduce "Thinking in Pine," a series of concise, 5-10 minute videos dedicated to unraveling the complexities of Pine Script®. We have our own list of topics to be covered, and we will start releasing the videos one by one. However, if you're grappling with any aspect of Pine Script® or stuck on an implementation, we encourage you to reach out to us or drop a comment here. We aim to address your queries by breaking down challenging concepts or implementations into easily digestible content.
What kind of videos are covered in "Thinking in Pine"?
Pine Script® Focus: We try to keep our focus on Pine Script® concepts and implementations.
General Utility: We prioritize topics that offer broader learning value. Though it's challenging to quantify this, we'll use our judgment to select topics that benefit the wider audience.
Time-Efficient Demonstrations: Ideally, we want to keep our demonstrations to 5–10 mins of time.
We're here to demystify Pine Script®, one topic at a time, making it accessible for everyone from beginners to advanced users. Stay tuned for insightful sessions with "Thinking in Pine"!
🎲 Demonstrating var, varip and regular variables in Pine Script®
In this video, we have demonstrated the difference between var, varip and regular variables by using an example implementation of OBV indicator.
🎯 Logic of OBV Calculation
Start with the value 0
On each bar, add volume to the indicator if close price is higher than previous bar close price.
On each bar, remove volume from the indicator is close price is lesser than previous bar close price
🎯 Highlights
Regular variables are initialized separately on each bar and does not propagate value to next bar unless coded to do it.
var variables are initialized once and then can be reassigned any number of times using := operator . The variables declared as var will propagate the current values to the next bar.
varip variables are initialized once and then can be reassigned any number of times using := operator . varip will behave similar to var on historical bars. However, on real time bars, they are recalculated on every tick, and they remember the state of each tick.
🎯 Example Program Used
Here is the example program used in the demonstration.
//Plot built-in OBV value for reference
plot(ta.obv, "OBV Built In", color=color.yellow)
//Volume multiplied by +-1 based on change in close price compared to previous bar.
volumeBySign = math.sign(nz(ta.change(close), 0))*volume
//Obv calculation by using regular variable. Code need to access and add last bar value using obvByRegular
obvByRegular = 0.0
obvByRegular += nz(obvByRegular , 0) + volumeBySign
plot(obvByRegular, "OBV By Regular Variable", color=color.blue)
//Obv calculation using var variable. Since var variables propagate values to next bar,
// we do not need to use historical operator to get the last bar value
var obvByVar = 0.0
obvByVar += volumeBySign
plot(obvByVar, "OBV by var Variable", color = color.maroon)
//Obv implementation using varip. The OBV is calculated based on every tick. Histoical values will match the same as that of other implementation.
//However, in real time, the calculations are done based on the tick values
varip obvByVarip = 0.0
varip lastPrice = close
varip lastVolume = volume
if(barstate.isnew)
lastVolume := 0
obvByVarip += math.sign(close-lastPrice)*(volume-lastVolume)
lastPrice := close
lastVolume := volume
plot(obvByVarip, "OBV by varip Variable", color = color.purple)
🎲 References:
Pine Script® User Manual - Variable declarations
Pine Script® Reference Manual - var
Pine Script® Reference Manual - varip
Pine Script® User Manual - Operators
Revisiting Automatic Access Management API for VendorsThis video explains how to automate access management for vendors who build and sell invite only scripts based on subscription or one time fee. I have made videos about this earlier as well. But, due to high demand, I have been asked to make this video again.
🎲 Tools Required
Replit - Used for hosting the service that automates access management
Postman - To test the services hosted
🎲 Prerequisites
User should have premium tradingview account and be able to publish invite only scripts by following the house rules.
User should disable 2FA on their account in order to allow programs to login remotely and manage access.
🎲 Steps
All the steps are also mentioned in the githup repository: github.com
🎯 Run the access management service
Fork the replit repository: replit.com
Update Environment Variables tvusername and tvpassword
Run the repl
🎯 Use postman to test the service methods
Detailed explanation of the API calls are present in the github link provided above. The service is capable of doing following things.
Check if the given tradingview username is valid or not
Get the access details of given user to list of scripts identified by pub id.
Delete the access to given user to list of scripts identified by pub id.
Provide/Extend access to given user to list of scripts identified by pub id for specific duration.
🎲 Notes
Please follow house rules while publishing and selling subscriptions to invite only scripts.
Do not commercialize these API calls or do not turn it into product. The mechanism is built on backend calls that are not officially supported by tradingview. While tradingview is tolerant on individual use, any malicious activity may force them to shut this down for everyone.
HOW-TO: Historical Pattern Matcher [Trendoscope]Hello everyone, here is a short video on how to use the indicator Historical Pattern Matcher . In this video, we went through the indicator components and settings in detail. All the information are also available on the script page. Please go through and let me know if you have further questions.
HOW-TO: Auto Harmonic Pattern - Screener [Trendoscope]Hello Everyone,
Here is a short walkthrough on our latest indicator cum screener - Auto Harmonic Pattern Screener. In this video we talk about few things.
Auto Harmonic Pattern Screener and how to use it
Different settings and Chart components
Differences between Auto Harmonic Pattern UltimateX and Screener and how to use them together to find patterns and study them in depth.
Common settings between the scripts and different use cases
This is a premium script which is part of Trendoscope Premium Indicator subscription. Please read the "Author's instructions" section of the script to know how to request for trial and subscription.
Please try and let me know if you have any feedbacks and report if you notice any bugs. Thanks very much for watching the video and using our indicators. Have a good day and enjoy your rest of the weekend :)
Overview of Reversal Chart Pattern IndicatorHello Everyone,
In this video, we discussed briefly about
Different Reversal Chart Patterns
Zigzag and Patterns Ecosystem of Libraries and Indicators developed in Pinescropt
Recursive Reversal Chart Pattern Indicator
Adding the snapshot for reference
Link to the Indicator:
Search for Zigzag and Pattern Ecosystem libraries and indicators in my profile if you like the subject :)
How to create auto trading bots for zero costHello Everyone,
Following are the things we discussed
🎲 Minimal Components of Auto Trading System:
Source where signals are generated
Exchange/Broker where orders are placed
Integration component which bridges both
🎲 In this example
Source - is our tradingview system and a sample script which generate alerts. Do not use this script for trading as it is only created for demonstration.
Exchange - We are going to use BingX exchange for this example as we only have this implementation in our integration system.
Integration System - www.pipedream.com is used for integration. This is cloud based integration product which is very flexible. Platform also allows users to contribute towards the product. Hence, it is very easy for us to develop integration to any broker or exchange which has API support.
🎲 Limitations
BingX APIs are fairly new and hence there are not much features. There is no option to place stop order.
It has option to place only limit/market orders
Stop loss is not possible via API
🎲 Steps:
🎯BingX
- Create account and enable perpetual futures trading
- Setup google authenticator and add valid email and phone.
- Create API - it will ask for Google authenticator code and email and phone OTPs.
- Store api key and secret key in safe place.
🎯Tradingview
- Create a script which can send stop, target, ticker information as signal.
- Study the existing idea about customising alerts for better understanding on how to achieve this.
🎯Pipedream
- Create account and setup BingX as source (needs API Key and Secret Key derived from BingX)
- Create Webhook trigger and capture webhook URL.
- Provide this URL in alerts to generate alert messages which are sent to webhook by default.
- Once alert is sent, load the alert in pipedream source and built rest of the workflow including calculate leveraged position and bracket order trades.
- Once tested, deploy the workflow so that workflow will keep listening to incoming alerts to generate trades.
Please note: the discrepancy in leverage calculation caused due to two things:
Lower timeframe used for generating faster alerts. Since the volatility is small, gaps can be huge.
The workflow did not run at once. Hence the delay caused rest of the issues resulting in miscalculations.
These problems however will not come when orders are placed via alerts and executed automatically.
Using scatterplot to understand the impact of RSI eventHello Everyone,
In this video we have discussed following things.
Scatter plot and implementation in Pine using heat map representation on tables.
Different quadrants and what it means.
RSI use case implemented in the indicator - RSI Impact Heat Map
How to use different settings and how to interpret the derived output.
General belief is when RSI crosses over 70, it is considered as overbought and people expect price to drop and when RSI crosses under 30, it is considered oversold and people expect price to move up. But, using this indicator, we can measure and plot the outcome of these events as scatter plot and use that to understand if these sentiments about overbought/oversold is right.
This can also be used with any entry condition. I look forward to developing a generic library for this so that other developers can make use of this to test their own criteria.
Thanks for watching this video. Let me know if you have any questions :)
Tradingview Telegram Webhook Bot with Chart Snapshot (Revised)Hello Everyone,
In this video, we will try to go through revised implementation of Tradingview-Telegram-Bot which can be used to send alert messages from tradingview to telegram along with current chart snapshot.
🎲 Base
Initial version of the same idea are as below:
How-to-create-simple-web-hook-to-send-alerts-to-Telegram
How-to-capture-chart-snapshot-in-tradingview-telegram-alert-bot
🎲 Prerequisite
Before proceeding with the current video, please watch the first video - How-to-create-simple-web-hook-to-send-alerts-to-Telegram which covers lots of basic things such as
Creating Telegram Bot using botfather and capturing required information such as TOKEN and CHANNEL
Basic usage of replit - a cloud based hosting service which lets us define our webhooks with little to no cost.
Postman - tool which is required to test the webhooks created
Other information such as keeping the bot alive via cronjob, using the webhooks in tradingview alert widget etc.
🎲 Setup
Clone/fork replit repo
Set mandatory environment variables CHANNEL and TOKEN
Set optional environment variables username/password or sessionid
Run the bot and start using webhooks
🎲 Usage
Webhook URL will be of the format.
https://Tradingview-Telegram-Bot. .repl.co/webhook?
🎲 Important Query parameters
jsonRequest - can be set as true/false. Default is false. If set to true, the payload should be a standard json. Output to telegram will be sent in tabular format. If not set or if set to false, output to telegram will be clear text.
tblfmt - table format to be used when jsonRequest is set to true. Default is plain. The values are exactly same as the ones required for tabulate package.
chart - Send the chart id if required to send chart snapshot along with alert message. For this to work - chart needs to be either a shared chart or environment variables for tvusername and tvpassword should be set to the user who has access to given chart.
ticker - Chart ticker. You no longer need to use different chart for different tickers. You can have a common chart and pass ticker to it so that chart will automatically switch to given ticker before taking screenshot
delivery - Taking chart snapshot takes time. This also delays the delivery of alert message. To avoid this, we can use this option - delivery=asap so that alert message will be sent as soon as possible and chart is sent later. If this parameter is not set, then both the messages will be delivered together.
🎲 Repository URLs
Tradingview-Telegram-Bot-Github
Tradingview-Telegram-Bot-Replit
How to draw trend lines in objective (algorithmic) wayHello everyone,
In this video, we explore how to draw trend lines in more subjective and algorithmic way.
Problem with drawing trend lines manually are
Subjective and may be influenced by personal factors
Easy to fit on historical data based on our biases.
Chances of overfitting to confirm our biases/ideas.
We can avoid these drawbacks by using an algorithmic method to achieve the same.
I have also developed several scripts which can help achieve this automatically. Users can refer to them for learning and practicing. Few of them are:
Auto TrendLines
Wedge and Flag Finder (Multi - zigzag)
Trendline Pairs (Deep Search)
Coming back to process of drawing trend lines manually, here are the steps.
Use and apply any zigzag indicator on the chart. In the demonstration, we have used Recursive Zigzag
Draw lines which joins more than 2 pivot lows for lower trendline and more than 2 pivot highs for higher trend line.
Make sure from starting pivot to ending pivot, price has not broken trendline convincingly, there can be rejections (touches) or fakeouts (just one or two bars outside trend line)
Higher number of candles touching the trendline, higher the strength of trend line.
If both higher and lower trend lines can be established, we can identify it as pattern - which can be triangles, wedges, channels etc.
Use different levels and lengths of zigzag to find different combinations. And then zero down to best possible pattern or use them in confluence.
Hope it was helpful and please let me know if you have any questions.
HOW-TO: Auto Harmonic Pattern - BacktesterHi All,
Here is a short video on how to use Auto-Harmonic-Pattern-Backtester-Trendoscope for building strategies using harmonic patterns.
CAUTION: THIS IS NOT A STRATEGY AND SHOULD NOT BE FOLLOWED BLINDLY. WE ENCOURAGE USERS TO UTILISE THIS AS BACKTESTING TOOL FOR BUILDING THEIR STRATEGY BASED ON HARMONIC PATTERNS
Notes about Strategy Properties
Qty is percentage based and non leveraged. Since pattern size is not uniform, risk per trade is not uniform per trade as well.
Default pyramiding is set to 4 - which means not all patterns will have trade if number of open trades is already 4
Key Settings
Can be either long or short mode but not not both. This is due to pine limitations.
Entry, Stop and Target settings along with Base are important in defining your strategy.
External filters plays a major role in adding external elements to the strategy. This also enables users to build their own filters. More details in this video
Strategy based alerts are different than custom alerts defined in settings. Custom alerts will fire for every pattern whereas strategy alerts will only fire upon generated trade signals. More details about Alert customisation is explained here .
When setting alerts, please turn off displays - pattern drawing and tables. And also limit backtest to minimal bars.
Please let me know if you have further questions.
HOW-TO: Wolfe Strategy [Trendoscope]Just made this short video to explain the concepts of Wolfe Strategy which I recently published.
Wolfe wave is popular concept among option traders. However, I have made some tweaks in this strategy to standard wolfe pattern trade rules.
Entry price based on breakout
No moving target - using flat target.
Entry is done based on risk reward
Not time bound
Intelligently decides whether to place stop order or limit order
Few possible future improvements
Make bidirectional trades possible
Better filters to chose long and short trades or when to trade
Lot can be improved on Wolfe scanner to identify more patterns
Exit strategy - can introduce optional trailing
Thanks for listening. Hope you enjoyed and learnt something from this :)
Relation between Win Ratio and Risk RewardHello Everyone,
In this video, I have tried explaining the relationship between win ratio and risk reward.
🎲 Two sides of the coin
People often asked me if a strategy win rate is less than 50% then why do we need to follow it? And also we can see in social media - lots of people claiming 90%+ win ratio for their strategy.
There is also another set of people who are more infatuated with how much percent profit they can get out of strategy. In social media, we can see people bragging about 1000% + profit trades.
The question here is, is it really possible to achieve this consistently or is the expectation to achieve such success reliable?
Simple answer for this is yes, it is possible to achieve both 99% win rate and 1000%+ profitability. But, it is almost impossible to achieve both together. Thing we need to understand is,
We can have 99% win rate and still lose money!!
We can have 1000% profitable trades and still lose money!!
How??
That's because people claiming both these things do not talk about other side of the coin.
Example 1 : Option Selling for premium
Selling options is very popular trading strategy which can often have very high win rates. But, the risk reward for this is very low.
You may get premium of $1 where you will be risking $100 on every trade. With that, you will lose money even if you have 99% win rate.
99 X $1 = 99 profit
1 X $100 = 100 loss
----------------------
$1 Loss
----------------------
Example 2 : High Leverage Trades
When you are trading with high leverage, profits and losses are magnified. This may lead to lots of losses and also some trades with huge profit.
Lets say you are targeting 1000% win per trade with 100X leverage. This means, your position is liquidated upon 1% price drop or less. So, your threshold for withstanding drawdown in a trade is less. To make 1000% profit, you the price need to go up by 10%
Risk = $1
Leverage = 100X
Buy price = 100
Your position will liquidate if price hits 99. So, by just 1% drop.
To achieve 1000% profit, price need to go up by 10%
This means, your expectations of profit per trade is very high. This also mean, you are most likely to have more failed trades than wins. So, lets say you will end up with Win ratio of 5% with this expectation. The equation can look something like this.
5 X $10 = 50 profit
95 X $1 = 95 loss
-----------------------
$45 loss
-----------------------
🎲 The balance
What we learn from above examples is that there is no meaning of considering only Win Ratio or only Risk Reward while trying to build your strategy. What you need to consider is the combination of both together.
Here is a formula to understand how much win ratio do you need to breakeven with given risk reward.
Win Ratio = 1/(Risk Reward+1)
Similarly here is a formula to understand how much Risk Reward you should target to breakeven with given win ratio.
Risk Reward = 1/(Win Ratio -1)
Here is google sheet containing the formula applied on various values. docs.google.com
You can use this formula to understand overall profitability while building or evaluating strategies.
Hope this is helpful. Thanks very much.
RepaintingHello All,
In this video - we discussed about what is repainting, different types of repainting, how we can identify them and some resources for programmers to avoid them programmatically.
Here are some quick resources for programmers:
www.tradingview.com
Please let me if there are further questions
HOW-TO: Auto Harmonic Patterns - UltimateX (Revised)Hello Everyone,
Here is a video on detailed settings guide to invite only script -
In this video, we discuss about:
* Few important settings and how to use them
* Few references to other tutorials for extended help
Also please refer to linked ideas about:
* How to customise alerts in Auto Harmonic scripts
* How to use external filters
Let me know if you have any questions.
HOW-TO : Auto Chart Patterns UltimateHello All,
I have made this video which covers briefly on following points for Auto-Chart-Patterns-Ultimate-Trendoscope
1. Indicator components
2. Detailed settings
3. Few key features
4. Info about trading different patterns included
I could not cover alerts in the video due to time constraints. But, alerts is same as that of HOW-TO-Customize-Alerts-in-Auto-Harmonic-Scripts
Let me know if you have any question. For trial access and subscription please look at the script page - 'Author's Instructions' section.
HOW-TO: Using Data Gathered in Divergence BacktesterHello Everyone,
Here is a small video describing the idea on studying divergence data based on divergence backtester script.
To understand further, you can study some of my older scripts on divergence. You can find them under my profile: www.tradingview.com
Filter only open source scripts so that you will see only free to use scripts with code available. This is not a fully fledged strategy. But, just means for studying the impact of divergence data on price action. Please let me know if you have any questions.
How to create fully customisable alerts in pinescriptHi All,
As discussed in the video, below are the steps to define fully customisable alert templates and alerts in pine script. This is a generic idea which can be implemented for any script.
Step 1. What all parameters(keys) need to be sent in alerts.
Step 2. Create a default alert template
Step 3. Create a user input where users can alter the default alert template
Step 4. Define your alert condition.
Step 5. Calculate the values for all the keys
Step 6. In the template, replace all keys with values and send alert
Sample script developed during the video.
//@version=5
indicator("Fully Customizable Alerts", overlay=true)
import HeWhoMustNotBeNamed/RecursiveAlerts/2 as ra
//Step 1. What all parameters(keys) need to be sent in alerts.
keys = array.from("{entry}", "{stop}", "{target1}", "{target2}")
//Step 2. Create a default alert template
template = '{
\t"entry" : {entry},
\t"stop" : {stop},
\t"target1" : {target1},
\t"target2" : {target2}
}'
//Step 3. Create a user input where users can alter the default alert template
inputTemplate = input.text_area(template, 'Alert Template')
//Step 4. Define your alert condition.
ma = ta.sma(close, 20)
condition = ta.crossover(close, ma)
atr = ta.atr(14)
if(condition)
//Step 5. Calculate the values for all the keys
entry = high + atr
stop = low - atr
risk = entry - stop
target1 = entry + risk
target2 = entry + 2*risk
//Step 6. In the template, replace all keys with values and send alert
values = array.from(str .tostring(entry), str .tostring(stop), str .tostring(target1), str .tostring(target2))
alertMessage = ra.updateAlertTemplate(inputTemplate, keys, values)
alert(alertMessage, alert.freq_once_per_bar)
plot(ma, "Moving Average")