Technical Analysis Notes👉 Hello trader.
- In the process of monitoring the list of trading pairs such as stocks, cryptocurrencies... I often mark signals such as: RSI divergence, MACD, Stochatic, RSI trendline, Trendline..."by hand" , like recording on a drawing board, or excell, notepad... Therefore, taking notes is very limited. In addition, each time frame gives different, inconsistent signals and it is difficult to analyze the trend of a trading pair. somehow.
- After a period of careful research, I created the "Technical Analysis notes" indicator to solve the problems mentioned above, and after using it, I personally found it very effective to mark it. Trading signals as well as trend analysis across time frames from small to large.
- For example: On weekends, I often use automatic scanning indicators (about 200 codes) RSI divergence, RSI trendline, Trendlines, MACD-histogram .. within a week, then mark trading pairs when there are signals. Signals such as RSI cutting its trend line, price breaking through the trend line, Histogram MACD divergence... in the weekly frame, from there look to the D1, H4 frames to see the next signals in those frames to find the direction of intersection. Move in the same direction as the weekly frame signal to trade in the same trend. From that analysis, I limit my ability to go against the trend, and wait patiently for the signals that have been noted before.
- On this board you can monitor 10 transaction codes (in real time)
- On this table I have given 4 different time frames (can be customized in settings)
- I add Kumo Cloud (ichimoku) signals on 4 time frames so that people can easily recognize the trend when the price is above the cloud (green circle), in the cloud (white circle), below the cloud (green circle). red circle)
- I add fast typing mode, shortcut typing depending on each person's description including 16 fast typing modes (for example: "ru:RSI br up" in my understanding means the RSI line has broken above the trend line direction)
- From the above example "ru:RSI br up" the sign ' : ' is the separator that must be present to interpret the word 'ru' as being typed quickly, and 'RSI br up' is the part that explains the content of that word typed quickly.
- In those 16 quick typing boxes (divided into 4 rows), the first 3 rows are colored with custom boxes for each person. The last remaining row is not filled.
- The content of note boxes can be hidden in the settings using the check box.
- In particular, the private notes column cannot be hidden, because it is the column for recording, synthesizing, analyzing, identifying main trends, or waiting points to place orders... (This box is the most important in my opinion. ..)
- Has a super smart warning mode (customizable) when Kumo cloud signals are in the same color on 4 time frames for the most certain trend (green - bullish, red - bearish)
- In the warning section, you can adjust from 4 time frames to 3 time frames, 2 time frames, 1 time frame.
- Alert mode lists exact code names when one or more codes qualify. (eg BTC, ADA, BNB...)
--------------------------------------------------------------------------------------------------------------------
👉 Vietnamess
- Trong quá trình theo dõi danh sách các cặp giao dịch như cổ phiếu, tiền điện tử...tôi thường đánh dấu các tín hiệu như : phân kì RSI, MACD, Stochatic, trendline RSI, Trendline ..."bằng tay", như ghi trên bảng vẽ, hoặc excell, notepad...Vì vậy ghi chép rất hạn chế ngoài ra mỗi khung thời gian cho các tín hiệu khác nhau, không đồng nhất và rất khó để phân tích xu hướng của một cặp giao dịch nào đó.
- Sau một thời gian nghiên cứu kĩ lưỡng tôi có lập lên được chỉ báo "ghi chép Phân tích kĩ thuật " nhằm giải quyết các vấn đề nêu như trên, và sau quá trình dùng, cá nhân tôi thấy rất hiệu quả khi đánh dấu các tín hiệu giao dịch cũng như phân tích xu hướng qua các khung thời gian từ nhỏ đến lớn.
- Ví dụ: Cuối tuần tôi thường dùng chỉ báo quét tự động(khoảng 200 mã) RSI phân kì, RSI trendline, Trendlines , MACD-histogram .. trong khung 1 tuần, sau đó đánh dấu những cặp giao dịch khi có những tín hiệu như RSI cắt đường xu hướng của nó, giá đột phá đường xu hướng, phân kì Histogram MACD.. trong khung tuần, từ đó tìm đến những khung D1,H4 xem các tín hiệu tiếp theo trong các khung đó để tìm hướng giao dịch cùng hướng với tín hiệu khung tuần để giao dịch cùng xu hướng. Từ những phân tích đó tôi hạn chế được đi ngược xu hướng, và kiên nhẫn chờ đợi khi có tín hiệu được đã ghi chú từ trước.
- Trên bảng này có thể theo õi được 10 mã giao dịch(theo thời gian thực)
- Trên bảng này tôi có đưa ra 4 khung thời gian khác nhau(có thể tùy chỉnh trong thiết lập)
- Tôi đưa thêm tín hiệu Mây Kumo( ichimoku) trên 4 khung thời gian để mọi người từ đó dễ dàng nhận biết xu hướng khi giá trên mây(dấu tròn xanh lá) , trong mây(dấu tròn trắng) , dưới mây(dấu tròn đỏ)
- Tôi đưa thêm chế độ gõ nhanh, gõ tắt tùy theo diễn tả của mỗi người gồm 16 chế độ gõ nhanh (ví dụ: "ru:RSI br up" theo ý hiểu của tôi là đường RSI đã phá vỡ lên trên đường xu hướng)
- Từ ví dụ trên "ru:RSI br up" dấu ' : ' là ngăn cách phải có để diễn giải từ 'ru' là gõ nhanh, còn 'RSI br up' là phần diễn giải nội dung của từ gõ nhanh đó
- Trong 16 ô gõ nhanh đó(được chia làm 4 hàng) có 3 hàng đầu được tô màu ô tùy chỉnh cầu mỗi người. hàng cuối cùng còn lại không được tô.
- Nội dung các ô ghi chú có thể được ẩn hiện trong mục cài đặt bằng ô dấu tích.
- Đặc biệt cột ghi chú riêng tư không ẩn được, vì đó là cột ghi chép, tổng hợp , phân tích , nhận định xu hướng chính, hay điểm chờ để đặt lệnh...(ô này theo tôi là quan trọng nhất...)
- Có chế độ cảnh báo siêu thông minh(có thể tùy chỉnh) khi tín hiệu mây Kumo cùng trên 4 khung thời gian cùng màu cho xu hướng chắc chắn nhất(xanh- tăng giá, đỏ- giảm giá)
- Trong mục cảnh báo có thể điều chỉnh từ 4 khung thời gian xuống còn 3 khung thời gian, 2 khung thời gian, 1 khung thời gian.
- Chế độ cảnh báo được liệt kê tên mã chính xác khi một hay nhiều mã đủ điều kiện .(ví dụ BTC , ADA , BNB...)
Educational
ProfitView Strategy TemplateHello traders,
This script took me a full week of coding/testing, sweat, and tears - and I’m too nice as I’m giving it for free to the community.
If you're tired of manual trading and looking for a solid strategy template to pair with your indicators, look no further.
This Pine Script v5 strategy template is engineered for maximum customization and risk management.
Best part?
This Pine Script v5 template facilitates the dynamic construction of ProfitView alerts, sparing users the time and effort of mastering the ProfitView syntax and manually creating alert commands.
This powerful tool gives much power to those who don't know how to code in Pinescript and want to automate their indicators' signals via the ProfitView Chrome extension.
IMPORTANT NOTES
ProfitView is a trading bot software that forwards TradingView alerts to your brokers (examples: Binance, Oanda, Coinbase, Bybit, etc.) for automating trading.
Many traders don't know how to dynamically create ProfitView-compatible alerts using the data from their TradingView scripts.
Traders using trading bots want their alerts to reflect the stop-loss/take-profit/trailing-stop/stop-loss to break options from your script and then create the orders accordingly.
This script showcases how to create ProfitView alerts dynamically.
TRADINGVIEW ALERTS
1) You'll have to create one alert per asset X timeframe = 1 chart.
Example: 1 alert for EUR/USD on the 5 minutes chart, 1 alert for EUR/USD on the 15-minute chart (assuming you want your bot to trade the EUR/USD on the 5 and 15-minute timeframes)
2) Select the Order fills and alert() function calls condition
3) For each alert, the alert message is pre-configured with the text below
{{strategy.order.alert_message}}
Please leave it as it is.
It's a TradingView native variable that will fetch the alert text messages built by the script.
4) ProfitView doesn't use webhook technology, so setting a webhook URL from the alerts notifications tab is unnecessary.
KEY FEATURES
I) Modular Indicator Connection
* plug your existing indicator into the template.
* Only two lines of code are needed for full compatibility.
Step 1: Create your connector
Adapt your indicator with only 2 lines of code and then connect it to this strategy template.
To do so:
1) Find in your indicator where the conditions print the long/buy and short/sell signals.
2) Create an additional plot as below
I'm giving an example with a Two moving averages cross.
Please replicate the same methodology for your indicator, whether a MACD , ZigZag, Pivots , higher-highs, lower-lows or whatever indicator with clear buy and sell conditions.
//@version=5
indicator("Supertrend", overlay = true, timeframe = "", timeframe_gaps = true)
atrPeriod = input.int(10, "ATR Length", minval = 1)
factor = input.float(3.0, "Factor", minval = 0.01, step = 0.01)
= ta.supertrend(factor, atrPeriod)
supertrend := barstate.isfirst ? na : supertrend
bodyMiddle = plot(barstate.isfirst ? na : (open + close) / 2, display = display.none)
upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.green, style = plot.style_linebr)
downTrend = plot(direction < 0 ? na : supertrend, "Down Trend", color = color.red, style = plot.style_linebr)
fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps = false)
fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps = false)
buy = ta.crossunder(direction, 0)
sell = ta.crossunder(direction, 0)
//////// CONNECTOR SECTION ////////
Signal = buy ? 1 : sell ? -1 : 0
plot(Signal, title = "Signal", display = display.data_window)
//////// CONNECTOR SECTION ////////
Important Notes
🔥 The Strategy Template expects the value to be exactly 1 for the bullish signal and -1 for the bearish signal
Now, you can connect your indicator to the Strategy Template using the method below or that one.
Step 2: Connect the connector
1) Add your updated indicator to a TradingView chart
2) Add the Strategy Template as well to the SAME chart
3) Open the Strategy Template settings, and in the Data Source field, select your 🔌Connector🔌 (which comes from your indicator)
Note it doesn’t have to be named 🔌Connector🔌 - you can name it as you want - however, I recommend an explicit name you can easily remember.
From then, you should start seeing the signals and plenty of other stuff on your chart.
🔥 Note that whenever you update your indicator values, the strategy statistics and visuals on your chart will update in real-time
II) BOT Risk Management:
- Max Drawdown:
Mode: Select whether the max drawdown is calculated in percentage (%) or USD.
Value: If the max drawdown reaches this specified value, set a value to halt the bot.
- Max Consecutive Days:
Use Max Consecutive Days BOT Halt: Enable/Disable halting the bot if the max consecutive losing days value is reached.
- Max Consecutive Days: Set the maximum number of consecutive losing days allowed before halting the bot.
- Max Losing Streak:
Use Max Losing Streak: Enable/Disable a feature to prevent the bot from taking too many losses in a row.
- Max Losing Streak Length: Set the maximum length of a losing streak allowed.
Margin Call:
- Use Margin Call: Enable/Disable a feature to exit when a specified percentage away from a margin call to prevent it.
Margin Call (%): Set the percentage value to trigger this feature.
- Close BOT Total Loss:
Use Close BOT Total Loss: Enable/Disable a feature to close all trades and halt the bot if the total loss is reached.
- Total Loss ($): Set the total loss value in USD to trigger this feature.
Intraday BOT Risk Management:
- Intraday Losses:
Use Intraday Losses BOT Halt: Enable/Disable halting the bot on reaching specified intraday losses.
Mode: Select whether the intraday loss is calculated in percentage (%) or USD.
- Max Intraday Losses (%): Set the value for maximum intraday losses.
Limit Intraday Trades:
- Use Limit Intraday Trades: Enable/Disable a feature to limit the number of intraday trades.
- Max Intraday Trades: Set the maximum number of intraday trades allowed.
Restart Intraday EA:
- Use Restart Intraday EA: Enable/Disable a feature to restart the bot at the first bar of the next day if it has been stopped with an intraday risk management safeguard.
III) Order Types and Position Sizing
- Choose between market, limit, or stop orders.
- Set your position size directly in the template.
Please use the position size from the “Inputs” and not the “Properties” tab.
I know it's redundant. - the template needs this value from the "Inputs" tab to build the alerts, and the Backtester needs it from the "Properties" tab.
IV) Advanced Take-Profit and Stop-Loss Options
- Choose to set your SL/TP in either pips or percentages.
- Option for multiple take-profit levels and trailing stop losses.
- Move your stop loss to break even +/- offset in pips for “risk-free” trades.
V) Miscellaneous
Retry order openings if they fail.
Order Types:
Select and specify order type and price settings.
Position Size:
Define the type and size of positions.
Leverage:
Leverage settings, including margin type and hedge mode.
Session:
Limit trades to specific sessions.
Dates:
Limit trades to a specific date range.
Trades Direction:
Direction: Specify the market direction for opening positions.
VI) Notifications (Telegram/Discord/Email/IFTTT/Twilio/SMS)
Customize notifications sent to Telegram, Discord, Email, IFTTT, Twilio, and ProfitView Logger.
VII) Logger
The ProfitView commands are logged in the TradingView logger.
You'll find more information about it in this TradingView blog post .
WHY YOU MIGHT NEED THIS TEMPLATE
1) Transform your indicator into a ProfitView trading bot more easily than before
Connect your indicator to the template
Create your alerts
Set your EA settings
2) Save Time
Auto-generated alert messages for ProfitView.
I tested them all and checked with the support team what could/couldn’t be done.
3) Be in Control
Manage your trading risks with advanced features.
4) Customizable
Fits various trading styles and asset classes.
REQUIREMENTS
* Make sure you have your ProfitView account and do the settings correctly in your Chrome extension. If you don't know how to do it, read the documentation + ask for help in the ProfitView Discord support channel.
* If there is any issue with the template, ask me in the comments section - I’ll answer quickly.
BACKTEST RESULTS FROM THIS POST
1) I connected this strategy template to a dummy Supertrend script.
I could have selected any other indicator or concept for this script post.
I wanted to share an example of how you can quickly upgrade your strategy, making it compatible with ProfitView.
2) The backtest results aren't relevant for this educational script publication.
I used realistic backtesting data but didn't look too much into optimizing the results, as this isn't the point of why I'm publishing this script.
This strategy is a template to be connected to any indicator - the sky is the limit. :)
3) This template is made to take 1 trade per direction at any given time.
Pyramiding is set to 1 on TradingView.
The strategy default settings are:
* Initial Capital: 100000 USD
* Position Size: 1%
* Commission Percent: 0.075%
* Slippage: 1 tick
* No margin/leverage used
Best regards,
Dave
[BCT] Option Pricing via Markov Chain Monte Carlo SimulationOverview:
This script offers a toolkit for quantitative options trading, using Monte Carlo simulations based on actual historical returns to model potential future price paths for underlying assets. A range of metrics related to options trading are also provided.
Monte Carlo Simulations:
The script employs Monte Carlo simulations to model future price paths based on the historical returns of the underlying asset. These simulated paths are represented as parabolas at the 2-sigma, 25th percentile, and median levels for quick reference.
Methodologies:
For calculating options prices at At-the-Money (or any user-selected strike), two methodologies are used:
Simple Averaging: Takes the mean of the simulated asset price paths.
Kernel Density Estimation (KDE): Applied to the simulated asset price paths to produce a smoothed estimate of its probability density function, thereby aiding in a more nuanced option price calculation.
Bootstrap Resampling:
Bootstrap resampling is specifically applied to the simulated asset price paths to generate an estimate of the standard deviation of the options prices. Note that while bootstrap methods are employed, they serve as statistical tools and do not guarantee statistical reliability.
Metrics Displayed:
Model-Estimated At-the-Money (or selected strike) Straddle Price
Model-Estimated At-the-Money (or selected strike) Call Price
Model-Estimated At-the-Money (or selected strike) Put Price
Model-Estimated Standard deviation for Option Prices from simulated price paths
Underlying Monte Carlo Simulation Results (represented as parabolas at the 2 sigma, 25 percentile and median)
This is not financial advice. Use at your own risk.
Disclaimer: Options trading carries a high level of risk and may not be suitable for all investors. This script is intended to serve as an educational tool and should not be considered financial advice. While designed to aid in decision-making, the script's indicators are not guarantees of performance or outcomes. Always conduct your own due diligence before making trading decisions.
Machine Learning using Neural Networks | EducationalThe script provided is a comprehensive illustration of how to implement and execute a simplistic Neural Network (NN) on TradingView using PineScript.
It encompasses the entire workflow from data input, weight initialization, implicit neuron calculation, feedforward computation, backpropagation for weight adjustments, generating predictions, to visualizing the Mean Squared Error (MSE) Loss Curve for monitoring the training phase.
In the visual example above, you can see that the prediction is not aligned with the actual value. This is intentional for demonstrative purposes, and by incrementing the Epochs or Learning Rate, you will see these two values converge as the accuracy increases.
Hyperparameters:
Learning Rate, Epochs, and the choice between Simple Backpropagation and a verbose version are declared as script inputs, allowing users to tailor the training process.
Initialization:
Random initialization of weight matrices (w1, w2) is performed to ensure asymmetry, promoting effective gradient updates. A seed is added for reproducibility.
Utility Functions:
Functions for matrix randomization, sigmoid activation, MSE loss calculation, data normalization, and standardization are defined to streamline the computation process.
Neural Network Computation:
The feedforward function computes the hidden and output layer values given the input.
Two variants of the backpropagation function are provided for weight adjustment, with one offering a more verbose step-by-step computation of gradients.
A wrapper train_nn function iterates through epochs, performing feedforward, loss computation, and backpropagation in each epoch while logging and collecting loss values.
Training Invocation:
The input data is prepared by normalizing it to a value between 0 and 1 using the maximum standardized value, and the training process is invoked only on the last confirmed bar to preserve computational resources.
Output Forecasting and Visualization:
Post training, the NN's output (predicted price) is computed, standardized and visualized alongside the actual price on the chart.
The MSE loss between the predicted and actual prices is visualized, providing insight into the prediction accuracy.
Optionally, the MSE Loss Curve is plotted on the chart, illustrating the loss trajectory through epochs, assisting in understanding the training performance.
Customizable Visualization:
Various inputs control visualization aspects like Chart Scaling, Chart Horizontal Offset, and Chart Vertical Offset, allowing users to adapt the visualization to their preference.
-------------------------------------------------------
The following is this Neural Network structure, consisting of one hidden layer, with two hidden neurons.
Through understanding the steps outlined in my code, one should be able to scale the NN in any way they like, such as changing the input / output data and layers to fit their strategy ideas.
Additionally, one could forgo the backpropagation function, and load their own trained weights into the w1 and w2 matrices, to have this code run purely for inference.
-------------------------------------------------------
While this demonstration does create a “prediction”, it is on historical data. The purpose here is educational, rather than providing a ready tool for non-programmer consumers.
Normally in Machine Learning projects, the training process would be split into two segments, the Training and the Validation parts. For the purpose of conveying the core concept in a concise and non-repetitive way, I have foregone the Validation part. However, it is merely the application of your trained network on new data (feedforward), and monitoring the loss curve.
Essentially, checking the accuracy on “unseen” data, while training it on “seen” data.
-------------------------------------------------------
I hope that this code will help developers create interesting machine learning applications within the Tradingview ecosystem.
NCI Trading Plan - By LightNCINCI Trading Plan - By LightNCI
NCI, which stands for New Concept Integration by Jayce PHAM, is a comprehensive approach that incorporates various critical aspects of trading to provide a logical, structured, and integrated approach to the financial markets. NCI covers market structure, key levels, smart money concepts, multiple timeframes and market cycles
About the NCI Trading Plan Indicator
The NCI Trading Plan is just a table allowing traders to keep track of multiple assets on a single chart, ensuring a comprehensive overview of trading statuses and strategies for each asset. The status is not automatically update. Using the NCI strategy, you may update it yourself the status of each asset.
Features
1. Display up to 10 different assets: Designed to support multi-asset trading strategies.
2. Dynamic Status Indication: Visualize the trading status for each asset:
i. Monitor: Asset is under review or surveillance.
ii. Confirmation: A potential trading signal or setup is being confirmed.
iii. Entry Set: An order for the asset has been placed.
iv. Forward-Test: An asset under monitored for it to being forward test.
3. Strategy Indication: Each asset can be tagged with a specific strategy identifier:
i. CKL: Confluence Key Level
ii. UKL: Un-Confluence Key Level
iii. SMC: Smart Money Concept
iv. BRT: Break & Re-Test
v. RTNKL: Re-Test of New Key Level
4. Customisable Display: Choose which assets you wish to display with a simple toggle on/off feature.
5. Stylisation: Color-code the statuses, table and fonts to suit your visual preference.
How to use
1. Toggle Display: Use the "Show Asset" checkboxes to determine which assets are visible.
2. Asset Name: Assign a name or symbol to each asset.
3. Status Selection: Choose the current trading status for each asset.
4. Strategy Selection: Assign a trading strategy to each asset.
5. Style: Customise the appearance of your trading plan by selecting preferred colours for different statuses and headers.
Conclusion
The NCI Trading Plan ensures a systematic and organised approach to multi-asset trading. By maintaining a visual overview of various assets and their corresponding trading statuses and strategies, traders can efficiently manage their portfolio and ensure timely decision-making.
Tip: To reset or modify an asset's status or strategy, simply adjust the settings in the panel on the left. The table will update in real-time.
WealthElf - Major Market DrawdownsThis simple indicator plots major market events onto the face of any chart, thus providing context to the effect the incident on any ticker
Treasury Yields Heatmap [By MUQWISHI]▋ INTRODUCTION :
The “Treasury Yields Heatmap” generates a dynamic heat map table, showing treasury yield bond values corresponding with dates. In the last column, it presents the status of the yield curve, discerning whether it’s in a normal, flat, or inverted configuration, which determined by using Pearson's linear regression coefficient. This tool is built to offer traders essential insights for effectively tracking bond values and monitoring yield curve status, featuring the flexibility to input a starting period, timeframe, and select from a range of major countries' bond data.
_______________________
▋ OVERVIEW:
______________________
▋ YIELD CURVE:
It is determined through Pearson's linear regression coefficient and considered…
R ≥ 0.7 → Normal
0.7 > R ≥ 0.35 → Slight Normal
0.35 > R > -0.35 → Flat
-0.35 ≥ R > -0.7 → Slight Inverted
-0.7 ≥ R → Inverted
_______________________
▋ INDICATOR SETTINGS:
#Section One: Table Setting
#Section Two: Technical Setting
(1) Country: Select country’s treasury yields data
(2) Timeframe: Time interval.
(3) Fetch By:
(3A) Date: Retrieve data by beginning of date.
(3B) Period: Retrieve data by specifying the number of time series back.
Enjoy. Please let me know if you have any questions.
Thank you.
Zigzag Chart Points█ OVERVIEW
This indicator displays zigzag based on high and low using latest pine script version 5 , chart.point which using time, index and price as parameters.
Pretty much a strip down using latest pine script function, without any use of library .
This allow pine script user to have an idea of simplified and cleaner code for zigzag.
█ CREDITS
LonesomeTheBlue
█ FEATURES
1. Label can be show / hide including text can be resized.
2. Hover to label, can see tooltip will show price and time.
3. Tooltip will show date and time for hourly timeframe and below while show date only for day timeframe and above.
█ NOTES
1. I admit that chart.point just made the code much more cleaner and save more time. I previously using user-defined type(UDT) which quite hassle.
2. I have no plan to extend this indicator or include alert just I thinking to explore log.error() and runtime.error() , which I may probably release in other publications.
█ HOW TO USE'
Pretty much similar inside mentioned references, which previously I created.
█ REFERENCES
1. Zigzag Array Experimental
2. Simple Zigzag UDT
3. Zig Zag Ratio Simplified
4. Cyclic RSI High Low With Noise Filter
5. Auto AB=CD 1 to 1 Ratio Experimental
Pineconnector Strategy Template (Connect Any Indicator)Hello traders,
If you're tired of manual trading and looking for a solid strategy template to pair with your indicators, look no further.
This Pine Script v5 strategy template is engineered for maximum customization and risk management.
Best part?
It’s optimized for Pineconnector, allowing seamless integration with MetaTrader 4 and 5.
This powerful tool gives a lot of power to those who don't know how to code in Pinescript and are looking to automate their indicators' signals on Metatrader 4/5.
IMPORTANT NOTES
Pineconnector is a trading bot software that forwards TradingView alerts to your Metatrader 4/5 for automating trading.
Many traders don't know how to dynamically create Pineconnector-compatible alerts using the data from their TradingView scripts.
Traders using trading bots want their alerts to reflect the stop-loss/take-profit/trailing-stop/stop-loss to break options from your script and then create the orders accordingly.
This script showcases how to create Pineconnector alerts dynamically.
Pineconnector doesn't support alerts with multiple Take Profits.
As a workaround, for 2 TPs, I had to open two trades.
It's not optimal, as we end up paying more spreads for that extra trade - however, depending on your trading strategy, it may not be a big deal.
TRADINGVIEW ALERTS
1) You'll have to create one alert per asset X timeframe = 1 chart.
Example: 1 alert for EUR/USD on the 5 minutes chart, 1 alert for EUR/USD on the 15-minute chart (assuming you want your bot to trade the EUR/USD on the 5 and 15-minute timeframes)
2) Select the Order fills and alert() function calls condition
3) For each alert, the alert message is pre-configured with the text below
{{strategy.order.alert_message}}
Please leave it as it is.
It's a TradingView native variable that will fetch the alert text messages built by the script.
4) Don't forget to set the Pineconnector webhook URL in the Notifications tab of the TradingView alerts UI.
You’ll find the URL on the Pineconnector documentation website.
EA CONFIGURATION
1) The Pyramiding in the EA on Metatrader must be set to 2 if you want to trade with 2 TPs => as it's opening 2 trades.
If you only want 1 TP, set the EA Pyramiding to 1.
Regarding the other EA settings, please refer to the Pineconnector documentation on their website.
2) In the EA, you can set a risk (= position size type) in %/lots/USD, as in the TradingView backtest settings.
KEY FEATURES
I) Modular Indicator Connection
* plug in your existing indicator into the template.
* Only two lines of code are needed for full compatibility.
Step 1: Create your connector
Adapt your indicator with only 2 lines of code and then connect it to this strategy template.
To do so:
1) Find in your indicator where the conditions print the long/buy and short/sell signals.
2) Create an additional plot as below
I'm giving an example with a Two moving averages cross.
Please replicate the same methodology for your indicator, whether it's a MACD , ZigZag , Pivots , higher-highs, lower-lows, or whatever indicator with clear buy and sell conditions.
//@version=5
indicator("Supertrend", overlay = true, timeframe = "", timeframe_gaps = true)
atrPeriod = input.int(10, "ATR Length", minval = 1)
factor = input.float(3.0, "Factor", minval = 0.01, step = 0.01)
= ta.supertrend(factor, atrPeriod)
supertrend := barstate.isfirst ? na : supertrend
bodyMiddle = plot(barstate.isfirst ? na : (open + close) / 2, display = display.none)
upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.green, style = plot.style_linebr)
downTrend = plot(direction < 0 ? na : supertrend, "Down Trend", color = color.red, style = plot.style_linebr)
fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps = false)
fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps = false)
buy = ta.crossunder(direction, 0)
sell = ta.crossunder(direction, 0)
//////// CONNECTOR SECTION ////////
Signal = buy ? 1 : sell ? -1 : 0
plot(Signal, title = "Signal", display = display.data_window)
//////// CONNECTOR SECTION ////////
Important Notes
🔥 The Strategy Template expects the value to be exactly 1 for the bullish signal and -1 for the bearish signal
Now, you can connect your indicator to the Strategy Template using the method below or that one.
Step 2: Connect the connector
1) Add your updated indicator to a TradingView chart
2) Add the Strategy Template as well to the SAME chart
3) Open the Strategy Template settings, and in the Data Source field, select your 🔌Connector🔌 (which comes from your indicator)
Note it doesn’t have to be named 🔌Connector🔌 - you can name it as you want - however, I recommend an explicit name you can easily remember.
From then, you should start seeing the signals and plenty of other stuff on your chart.
🔥 Note that whenever you update your indicator values, the strategy statistics and visuals on your chart will update in real-time
II) Customizable Risk Management
- Choose between percentage or USD modes for maximum drawdown.
- Set max consecutive losing days and max losing streak length.
- I used the code from my friend @JosKodify for the maximum losing streak. :)
Will halt the EA and backtest orders fill whenever either of the safeguards above are “broken”
III) Intraday Risk Management
- Limit the maximum intraday losses both in percentage or USD.
- Option to set a maximum number of intraday trades.
- If your EA gets halted on an intraday chart, auto-restart it the next day.
IV) Spread and Account Filters
- Trade only if the spread is below a certain pip value.
- Set requirements based on account balance or equity.
V) Order Types and Position Sizing
- Choose between market, limit, or stop orders.
- Set your position size directly in the template.
Please use the position size from the “Inputs” and not the “Properties” tab.
Reason : The template sends the order on the same candle as the entry signals - at those entry signals candles, the position size isn’t computed yet, and the template can’t then send it to Pineconnector.
However, you can use the position size type (USD, contracts, %) from the “Properties” tab for backtesting.
In the EA, you can define the position size type for your orders in USD or lots or %.
VI) Advanced Take-Profit and Stop-Loss Options
- Choose to set your SL/TP in either pips or percentages.
- Option for multiple take-profit levels and trailing stop losses.
- Move your stop loss to break even +/- offset in pips for “risk-free” trades.
VII) Logger
The Pineconnector commands are logged in the TradingView logger.
You'll find more information about it in this TradingView blog post .
WHY YOU MIGHT NEED THIS TEMPLATE
1) Transform your indicator into a Pineconnector trading bot more easily than before
Connect your indicator to the template
Create your alerts
Set your EA settings
2) Save Time
Auto-generated alert messages for Pineconnector.
I tested them all, and I checked with the support team what could/can’t be done
3) Be in Control
Manage your trading risks with advanced features.
4) Customizable
Fits various trading styles and asset classes.
REQUIREMENTS
* Make sure you have your Pineconnector license ID.
* Create your alerts with the Pineconnector webhook URL
* If there is any issue with the template, ask me in the comments section - I’ll answer quickly.
BACKTEST RESULTS FROM THIS POST
1) I connected this strategy template to a dummy Supertrend script.
I could have selected any other indicator or concept for this script post.
I wanted to share an example of how you can quickly upgrade your strategy, making it compatible with Pineconnector.
2) The backtest results aren't relevant for this educational script publication.
I used realistic backtesting data but didn't look too much into optimizing the results, as this isn't the point of why I'm publishing this script.
This strategy is a template to be connected to any indicator - the sky is the limit. :)
3) This template is made to take 1 trade per direction at any given time.
Pyramiding is set to 1 on TradingView.
The strategy default settings are:
* Initial Capital: 100000 USD
* Position Size: 1 contract
* Commission Percent: 0.075%
* Slippage: 1 tick
* No margin/leverage used
WHAT’S COMING NEXT FOR YOU GUYS?
I’ll make the same template for ProfitView, then for AutoView, and then for Alertatron.
All of those are free and open-source.
I have no affiliations with any of those companies - I'm publishing those templates as they will be useful to many of you.
Dave
USD BRL Exchange Rate Discrepancy Analysis ScriptThe script is designed to visualize and analyze discrepancies in the exchange rates of USDT to BRL (Tether to Brazilian Real) and USDT to BRZ (Tether to Brazilian Digital Token) across various trading platforms. It fetches the closing prices of multiple trading pairs from different platforms like Bybit, Binance, and Uniswap. The primary focus is to calculate and plot the conversion rate of BTCBRZ (Bitcoin to Brazilian Real) to USD. Additionally, the script highlights the differences in buy and sell rates for USDT-BRL and USDT-BRZ pairs, including fees and percentage adjustments. Visual elements like lines and areas are used to represent these rates, offering a comprehensive view of potential arbitrage opportunities in the Bitcoin market across different exchanges.
ES/SPX/SPY conversion indicatorOverview:
This indicator helps with giving a conversion from ES, SPX and SPY to each other. Will help with setting levels on the chart based on the one of the 3 securities. For example, if you have a level from ES (futures) and want to correlate that level in the SPY, then you can put the ES option and the level you want to watch and will put the line in the corresponding level of the SPY.
How it works/Calculations:
It will use a mathematical equation to calculate the ratio between ES/SPY/SPX. Using this ratio equation, if ES price point A is wanted, then it will be correlated to the SPY and will help with knowing what levels correspond to the futures and vice versa. One thing to be aware is that Tradingview has a 15 min delayed on futures so you will not have updated pricing unless you pay for it, but for this indicator main purpose is for the people that want to correlate certain levels from futures to SPY based on technical analysis. On the settings you can choses the ticker that you want to put the levels, whether is ES, SPX or SPY and then you have multiple areas to put those levels as active or inactive. If the line is below the price point it will color red and if the line is above the price, then will be green.
Potential Pitfalls:
No potential pitfalls except as mentioned above, the delay in futures unless you pay for it.
How to use:
You should not be using this indicator for entries or stop. This indicator will help correlate levels from ES, SPX and SPY among themselves.
Who will benefit from this indicator? Whoever likes to do technical analysis on the futures and want to watch those levels into the spy and correlate them.
Settings:
-Very simple settings, first you chose the one that you want to compare with. You will have 3 choices, ES, SPX, SPY. If you have the SPY chart and want to compare with ES, then chose ES and then put the levels from ES that you want to mark on the SPY.
Disclaimer:
This is still an indicator that is being tested and in no way should be used alone. Currently will be in closed beta to find bugs and to work on accuracy.
The information contained in this script does not constitute financial advice or a solicitation to buy or sell any securities of any type. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from the use of or reliance on such information.
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, backtest, or individual's trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs.
My Scripts are only for educational purposes!
[AlbaTherium] Sessional & Daily's liquidities - Beta Sessional & Daily Liquidities - Beta: Harnessing the Power of the Institutional Funding Candle (IFC) in Trading
Introduction:
The Sessional & Daily Liquidities - Beta indicator places the Institutional Funding Candle (IFC) at its core. Within the realm of trading, the IFC stands as a key signal for identifying Points of Interest (POIs) , offering traders invaluable insights into market dynamics. This document aims to illuminate the central role of the IFC within the Sessional & Daily Liquidities - Beta indicator, explaining how it can be effectively utilized to spot significant changes in the market and seize trading opportunities.
Chapter 1: Sessional Liquidity concepts
The forex market can be broken up into four major trading sessions: the Sydney session, the Tokyo session, the London session, and Trump’s favorite time to tweet (before he was banned), the New York session.
Historically, the forex market has three peak trading sessions. Traders often focus on one of the three trading periods, rather than attempt to trade the markets 24 hours per day. This is known as the “forex 3-session system“. These sessions consist of the Asian, European, and North American sessions, which are also called Tokyo, London, and New York sessions.
For that reason, a lot of trader put their stoploss right at the High or Low of their session, filling these price levels with liquidities. The market loves liquidities, they are like the “fuel” of the market. Price usually goes to these levels, takes out all the liquidities, and then returns to its original direction. This price behaviour indicates the presence of players – banks, institutions,... – driving the market to their own profit.
The same logic applies with Daily, Weekly and Monthly high/low levels.
Chapter 2: Deciphering the Institutional Funding Candle
2.1 Unveiling the Essence of the Institutional Funding Candle (IFC)
- IFC concept is the core of this indicator. It is recommended to use this indicator on high timeframes, like 1H or 4H charts, as those are the timeframes which big players look at.
- The presence of IFC candles means a significant amount of stop loss is triggered, and price have a tendency to reverse.
2.2 Criteria for IFC Identification
The definition of specific conditions that characterize an IFC within the Sessional & Daily Liquidities - Beta indicator:
- A breach of Previous day, Previous week, or Previous month’s High or Low levels or a breach of major Session Highs or Lows.
- Price made an immediate reverse, creating a decent distance from the wicks.
Chapter 2: Trading Strategies with the IFC
User should treat these signals with cautions, and only take trades with multi confluences.
This pictures below demonstrate a strategy to trade with this indicator, taking 1H HTF trend and 5m LTF ChoCh and Single Candle Order Block as confluences.
Conclusion:
The Sessional & Daily Liquidities - Beta indicator, centered around the Institutional Funding Candle (IFC), stands as a potent tool for traders, offering them the means to spot critical inflection points in the market. By understanding the role of the IFC in violating significant swing highs or lows and major session highs or lows, traders can make informed decisions and seize opportunities within the ever-evolving realm of financial markets. It's crucial to note that while IFC candle colors can provide insights, they do not unilaterally dictate market direction. Furthermore, candle closure can be a valuable consideration in specific situations, particularly when evaluating other High Time Frame POIs.
The real-world examples presented in this document within the Sessional & Daily Liquidities - Beta indicator offer a tangible insight into the world of IFC trading. Harness the potential of the Institutional Funding Candle within the Sessional & Daily Liquidities - Beta indicator to elevate your trading strategies and make well-informed decisions in the dynamic landscape of financial markets.
[AbaTherium] Internal ranges analysis - Beta Internal Ranges Analysis - IRA - Beta
Introduction:
Internal Ranges Analysis - IRA - Beta is a cutting-edge technical analysis tool designed to enhance your trading prowess. This beta version introduces three vital concepts: "Liquidity Sweep" , "Single Candle Mitigation Entry" , and "Single Candle Order Block Entry" . These concepts provide traders with a nuanced perspective on price action dynamics and opportunities for entry into the market.
Chapter 1: Understanding Liquidity Sweep
1.1 Liquidity Sweep Defined
- Liquidity Sweep occurs when the market price reacts after taking out a historical pivot. This phenomenon often signifies a swift move designed to clear resting buy or sell orders in the market. IRA - Beta excels at identifying and visualizing Liquidity Sweep events, allowing traders to capitalize on them.
Chapter 2: Single Candle Mitigation Entry
2.1 Introduction to Single Candle Mitigation Entry
- Single Candle Mitigation (SCM) Entry is a strategic approach employed when price action takes out the high or low of the preceding candle. This entry method is designed to capitalize on potential reversals or shifts in market sentiment. IRA - Beta offers effective tools to identify and act upon Single Candle Mitigation opportunities.
2.2 Single Candle Order Block Entry
- Traders can also explore the concept of Single Candle Order Blocks, where specific price levels act as potential entry points. This feature is integrated into IRA - Beta, providing traders with additional options for making well-informed entry decisions.
Chapter 3: Real-World Examples
Trading with internal structures needs to be done carefully with multiple confluences, like current market bias or LTF confirmations.
Here is an example on using liquidities concept and break of SCOB as confluences to enter a trade:
Conclusion:
Internal Ranges Analysis - IRA - Beta is a valuable asset for traders seeking to gain an edge in today's dynamic markets. By focusing on concepts like Liquidity Sweep, Single Candle Mitigation Entry , and Single Candle Order Block Entry , this tool equips traders with the knowledge and tools needed to make informed entry decisions. Whether you're a seasoned trader or just starting your journey, IRA - Bet a can help you navigate through the complexities of price action and make more informed trading choices.
This document serves as a comprehensive guide to Internal Ranges Analysis - IRA - Beta , highlighting its significance in understanding market dynamics and leveraging key trading concepts. Incorporating these principles into your trading strategies can lead to improved decision-making and potentially more profitable outcomes.
[AlbaTherium] Structure Mapping with Demand & Supply Zones Structure Mapping v3.0 with Demand & Supply Zones
Introduction:
Structure Mapping v3.0 with Demand & Supply Zones marks a significant advancement in the realm of technical analysis and trading tools. This latest version of the indicator is designed to offer traders a comprehensive understanding of market structure and key demand and supply zones based on a refined version of Smart Money Concepts. All the concepts integrated into this method are meticulously defined, empowering users to map the market structure with confidence. With this indicator, there's no need to doubt the accuracy of your markings; it performs this task effectively. There are no hidden 'magic' properties underlying this indicator, ensuring that our users can independently verify each and every feature. It is our unwavering commitment to transparency that distinguishes us and makes us unique in the market.
Chapter 1: Understanding Market Structure
1.1 Market Structure Defined:
- Market structure forms the bedrock upon which successful trading strategies are constructed. It encompasses the highs, lows, and significant price levels that shape a market's behavior. Structure Mapping v3.0 provides a clear visualization of market structure, enabling traders to identify crucial support and resistance levels.
1.2 The Power of Structural Analysis:
- Structural analysis is a pivotal component of this indicator. By recognizing the fundamental elements of market structure, traders can make informed decisions regarding trend direction, potential reversals, and optimal entry and exit points.
1.3 Rules for Structure Mapping:
Let's explore some key definitions:
- Inside bars: These are candles that exist within the range of a preceding candle.
- Pullbacks: In an uptrend, a valid pullback occurs when the low of a previous candle's range (excluding inside bars) is breached, and the price continues to rise.
- Inducements (IDM): An inducement is a price level. In an uptrend, it is defined as the low of the latest pullback before the highest high. It is considered a liquidity area, often revisited by the market to access liquidity before continuing its upward movement.
- Break of Structure (BoS): In an uptrend, after surpassing an IDM , the highest high becomes a Confirmed structure high, or a Major High . If the price then closes above this Major High, a Bullish Break of Structure (Bullish BoS) is confirmed. Similarly, the lowest point between these movements becomes a Confirmed structure low or Major Low in a downtrend.
Change of Character (ChoCh):
In an uptrend, if the price falls below a Major Low, it indicates a shift in market bias from Bullish to Bearish, or a Bearish Change of Character.
Example of a bullish ChoCh:
Chapter 2: Demand & Supply Zones
2.1 Introduction to Demand & Supply Zones:
- Demand and Supply zones are critical areas on a price chart where significant buying or selling pressure is expected. This indicator highlights these zones, enabling traders to anticipate potential price reactions.
2.2 Identifying Demand and Supply Zones:
A Demand or Supply zone is the first candle of a pullback that leaves a Fair value gap.
Classic example of a trade with our indicator:
Conclusion:
Structure Mapping v3.0 with Demand & Supply Zones is a potent tool for traders seeking to gain an advantage in the financial markets. By focusing on market structure and identifying key demand and supply zones, this indicator equips traders with the knowledge they need to make informed decisions. Whether you're a novice or an experienced trader, this tool can enhance your technical analysis and trading strategies in the dynamic world of trading.
This document serves as a comprehensive guide to Structure Mapping v3.0 with Demand & Supply Zones, emphasizing its significance in understanding market dynamics and identifying critical trading zones. Applying these principles in your trading endeavors can lead to improved decision-making and more profitable outcomes.
[AlbaTherium] Structure Mapping & Order Blocks Advanced - Beta An Insight into Structure Mapping and Order Block Identification with Smart Money Concepts
Introduction:
Structure Mapping & Order Blocks Advanced - Beta serves as a fundamental pillar in the realm of Smart Money Concepts . This indicator adeptly charts the market structure based on a refined version of SMC while identifying Order Blocks. All the concepts embedded in this method are meticulously defined, offering users the ability to chart the market structure with heightened confidence. With this indicator, there is no need for excessive questioning of the accuracy of your markings; it diligently strives to perform this task effectively. There are no hidden 'magic' properties underlying this indicator, ensuring that our users can independently verify each and every feature. It is this commitment to transparency that sets us apart and makes us unique in the market.
In this discussion, we delve into the intricacies of Break of Structure , Change of Character , and SMART MONEY TRAP . We also introduce the concepts of Extreme Order Blocks , Decisional Order Blocks , and Smart Money Trap Order Blocks .
Chapter 1: Understanding Structure Mapping:
Let's begin with some definitions:
- Inside bars are candles that lie within the range of a preceding candle.
- Pullbacks occur in an uptrend when the low of a preceding candle's range (excluding inside bars) is breached, and the price continues to rise.
- Inducements (IDM) are price levels defined as the low of the latest pullback before the most recent high. They often act as liquidity points that the market revisits before continuing its move.
- Break of Structure (BoS):
In an uptrend, after surpassing an IDM , the most recent high becomes a Confirmed structure high, or a Major High . If the price then closes above this Major High , a Bullish Break of Structure (Bullish BoS) is confirmed. Similarly, the lowest point between these movements becomes a Confirmed structure low or Major Low in a downtrend.
- Change of Character (ChoCh):
In an uptrend, if the price falls below a Major Low , it indicates a shift in market bias from Bullish to Bearish, or a Bearish Change of Character .
Example of a bullish ChoCh :
Chapter 2: The Significance of Order Blocks:
Order Blocks (OB) play a pivotal role in Smart Money Concepts during entry points. Understanding what they represent and how to identify them is essential. For a Bullish/Bearish Order Block to be confirmed, specific conditions, including price imbalance and breaching the previous candle's high or low, must be met. We will delve into the finer details of identifying and trading Order Blocks, with an emphasis on the fact that price often reacts from Decisional Order Blocks, Extreme Order Blocks , and Smart Money Trap Order Blocks .
- An OB is the initial candle range of a pullback that creates a Fair value gap .
These are zones where proactive traders enter the market, resulting in significant price changes indicated by Fair value gaps . It is believed that when the price revisits these zones in the future, it tends to bounce back. This property makes Order Blocks excellent potential entry points.
Order Blocks are categorized as follows:
- Extreme OB : The first and lowest OB between the Major Low and Major High.
- Decisional OB : The most recent OB lower than the current IDM.
- Smart Money Traps : All OBs between Extreme and Decisional OB.
- Demand above IDM / Supply below IDM
Chapter 3: Understanding SMART MONEY TRAP (SMT):
SMART MONEY TRAP is a concept that brings clarity to the distinction between Structure and Order Blocks within Smart Money Concepts and is a unique feature of this indicator. While many Smart Money Traders base their trades on Structure and Order Blocks, it's crucial to recognize that Order Blocks serve as an additional confirmation for buy or sell decisions. Blindly trading based on Order Blocks is not advisable. Instead, traders should exercise patience and await other confirmations like inducement or Liquidity sweep before executing trades on Order Blocks. We will illustrate how this concept works in practice.
In the example above, the market largely disregards all the SMT s and responds favorably to the Extreme OB . This presents a promising trading opportunity, with a stop loss placed below the OB and a take profit set at the fill of the Fair value gap.
Conclusion:
Structure Mapping & Order Blocks Advanced - Beta embodies the essence of Smart Money Concepts , serving as a powerful tool for traders. This indicator effectively combines the elements of structure mapping and Order Blocks to guide trading decisions. By comprehending the dynamics of Impulsive Moves and Corrections, distinguishing between Bearish and Bullish Order Flow, and mastering the identification and trading of Order Blocks while considering SMART MONEY TRAP, traders can gain a competitive edge in the dynamic landscape of financial markets.
This document serves as a comprehensive guide to Structure Mapping & Order Blocks Advanced - Beta, highlighting its significance within the Smart Money Concepts framework. It is essential to apply these concepts judiciously to enhance trading.
Risk Reward Optimiser [ChartPrime]█ CONCEPTS
In modern day strategy optimization there are few options when it comes to optimizing a risk reward ratio. Users frequently need to experiment and go through countless permutations in order to tweak, adjust and find optimal in their data.
Therefore we have created the Risk Reward Optimizer.
The Risk Reward Optimizer is a technical tool designed to provide traders with comprehensive insights into their trading strategies.
It offers a range of features and functionalities aimed at enhancing traders' decision-making process.
With a focus on comprehensive data, it is there to help traders quickly and efficiently locate Risk Reward optimums for inbuilt of custom strategies.
█ Internal and external Signals:
The script can optimize risk to reward ratio for any type of signals
You can utilize the following :
🔸Internal signals ➞ We have included a number of common indicators into the optimizer such as:
▫️ Aroon
▫️ AO (Awesome Oscillator)
▫️ RSI (Relative Strength Index)
▫️ MACD (Moving Average Convergence Divergence)
▫️ SuperTrend
▫️ Stochastic RSI
▫️ Stochastic
▫️ Moving averages
All these indicators have 3 conditions to generate signals :
Crossover
High Than
Less Than
🔸External signal
▫️ by incorporating your own indicators into the analysis. This flexibility enables you to tailor your strategy to your preferences.
◽️ How to link your signal with the optimizer:
In order to be able to analysis your signal we need to read it and to do so we would need to PLOT your signal with a defined value
plot( YOUR LONG Condition ? 100 : 0 , display = display.data_window)
█ Customizable Risk to Reward Ratios:
This tool allows you to test seven different customizable risk to reward ratios , helping you determine the most suitable risk-reward balance for your trading strategy. This data-driven approach takes the guesswork out of setting stop-loss and take-profit levels.
█ Comprehensive Data Analysis:
The tool provides a table displaying key metrics, including:
Total trades
Wins
Losses
Profit factor
Win rate
Profit and loss (PNL)
This data is essential for refining your trading strategy.
🔸 It includes a tooltip for each risk to reward ratio which gives data for the:
Most Profitable Trade USD value
Most Profitable Trade % value
Most Profitable Trade Bar Index
Most Profitable Trade Time (When it occurred)
Position and size is adjustable
█ Visual insights with histograms:
Visualize your trading performance with histograms displaying each risk to reward ratio trade space, showing total trades, wins, losses, and the ratio of profitable trades.
This visual representation helps you understand the strengths and weaknesses of your strategy.
It offers tooltips for each RR ratio with the average win and loss percentages for further analysis.
█ Dynamic Highlighting:
A drop-down menu allows you to highlight the maximum values of critical metrics such as:
Profit factor
Win rate
PNL
for quick identification of successful setups.
█ Stop Loss Flexibility:
You can adjust stop-loss levels using three different calculation methods:
ATR
Pivot
VWAP
This allows you to align risk-reward ratios with your preferred risk tolerance.
█ Chart Integration:
Visualize your trades directly on your price chart, with each trade displayed in a distinct color for easy tracking.
When your take-profit (TP) level is reached , the tool labels the corresponding risk-reward ratio for that specific TP, simplifying trade management.
█ Detailed Tooltips:
Tooltips provide deeper insights into your trading performance. They include information about the most profitable trade, such as the time it occurred, the bar index, and the percentage gain. Histogram tooltips also offer average win and loss percentages for further analysis.
█ Settings:
█ Code:
In summary, the Risk Reward Optimizer is a data-driven tool that offers traders the ability to optimize their risk-reward ratios, refine their strategies, and gain a deeper understanding of their trading performance. Whether you're a day trader, swing trader, or investor, this tool can help you make informed decisions and improve your trading outcomes.
01 Position CalculatorI present to your attention a calculator for calculating the volume per position.
This calculator is tested on cryptocurrency trading and MOEX liquid shares!
This calculator is suitable for beginners to make it easier to study trading and not get confused at the very beginning with volume calculations, I also use it for virtual trading, a position is drawn on the chart in real time, which shows the amount of loss or profit, that is, with the help of it I I practice different strategies without losing real money on experiments.
All calculations are made at your risk.
You need to indicate what your working deposit is, what percentage of it you are willing to risk per day, the number of your losing trades for one trading session, after which you will stop trading for that day, the amount of risk will be divided by the number of unprofitable trades.
The principle of operation is as simple as possible, you need to indicate three lines on the chart 1 - time line: it is needed so that a position on the chart can be drawn from it. 2 – Entry line for entering a position: the price at which you want to buy an asset. 3 – stop loss line “SL”: the price upon reaching which your losing trade will be closed. If the 3-stop loss line is placed below the 2-Entry line, then a long position will be calculated, if the stop loss line is above the Entry line, then a short position will be calculated. take profit "TP" is calculated automatically according to your settings in the menu.
And so on in order through the menu from top to bottom.
1. Rounding the volume to a whole number: if you select “round”, then the volume of the acquired asset (shares, coins, etc.) will be rounded to a whole number, but be careful if your deposit is $100, and the cost of 1 unit of the asset is more than $1000, then the calculator will give error. MOEX shares are traded only in whole lots, so rounding occurs automatically.
2. Automatic calculation of SL in 1 ATR of the selected TF (auto/manual) (ATR...): if you select auto and specify, for example, ATR 1h, then your “SL” will be calculated automatically and set at a distance from Entry of 1 ATR of the hourly time frame (this is the average price change over 1 hour)
3. Cryptocurrency deposit commission, MOEX deposit commission: I made two different deposits on purpose so as not to change the settings each time, depending on the schedule you choose, MOEX or cryptocurrency, the required deposit and commission will be automatically taken into account.
4. Slippage: this is the percentage of slippage on closing a position at a stop loss.
5. Daily drawdown % (...): this is the percentage of your trading deposit that you are willing to risk for one trading session, the amount at risk.
6. Ratio rice /profit 1/ (...): you need to indicate the SL/TP ratio, based on this your income per trade is calculated and the distance to TP is outlined on the graph.
7. Number of losing trades (...): this is the number of your trades per trading session after receiving which you will end trading for that day, the amount of risk will be divided by the number of losing trades.
8. Position: you can enter the start date of the position and Entry and SL prices
9. ATR – specify the number of last candles to calculate the average price movement of the selected time frame
Now, as for the tables located by default on the left and right at the bottom of the screen, I made windows with descriptions; when you hover the cursor over a cell, a description pops up.
RU
Этот калькулятор проверен, на торговле криптовалюты и ликвидных акциях MOEX!
Этот калькулятор подойдет начинающим, чтоб облегчить изучение торговли и не запутаться в самом начале с расчётами объемов, так же я использую его для виртуальной торговли, на графике в реальном времени рисуется позиция, на которой видно суму убытка или прибыли, то есть с помощью него я отрабатываю разные стратегии, не теряя реальные деньги на эксперименты.
Все расчеты делаются от вашего риска.
Вам необходимо указать какой ваш рабочий депозит, каким процентом от него вы готовы рискнуть на день, количество ваших убыточных сделок на одну торговую сессию, после которых вы прекратите торговлю на этот день, сумма риска будет поделена на количество убыточных сделок.
Принцип работы максимально прост, вам нужно указать на графике три линии 1 - линия время: она нужна чтоб от нее рисовался позиция на графике. 2 –линия Entry входа в позицию: цена по которой вы хотите купить актив. 3 – линия stop loss «SL»: цена при достижении которой закроется ваша убыточная сделка. Если линию 3-stop loss разместить под линией 2-Entry то будет рассчитываться длинная позиция, ели лини stop loss будет над линией Entry то будет рассчитываться короткая позиция. take profit «TP» рассчитывается автоматически согласно вашим настройкам в меню.
И так по порядку по меню с верху в низ.
1. Округление объема до целого: если выбрать «round -округлить», то объем приобретаемого актива (акции, монеты и другого) будет округлен до целого числа, но будьте внимательны если ваш депозит 100$, а стоимость 1 единицы актива более 1000$ то калькулятор выдаст ошибку. Акции MOEX торгуются только целыми лотами потому округление происходит автоматически.
2. Авто расчёт SL в 1 ATR выбранного TF (auto/manual) (ATR…): если выбрать auto и указать, к примеру ATR 1h, то ваш «SL», будет рассчитан автоматически и выставлен на расстоянии от Entry в 1 ATR часового time frame (это усредненное изменение цены за 1 час)
3. Депозит крипто валюты комиссия, депозит MOEX комиссия: сделал специально два разных депозита чтоб каждый раз не менять настройки, в зависимости от выбранного вами графика, MOEX или криптовалюта, будет автоматически браться в расчет нужный депозит и комиссия.
4. Проскальзывание: это процент на проскальзывание закрытия позиции по stop loss.
5. Просадка на день % (…): это процент от вашего торгового депозита, которым вы готовы рискнуть на одну торговую сессию, сумма риска надень.
6. Соотношение рис /прибыль 1/ (…): вам нужно указать соотношение SL/TP на основе этого рассчитывается ваш доход на сделку и на графике обрисовывается расстояние до TP.
7. Количество убыточных сделок (…): это количество ваших сделок на торговую сессию после получения, которых вы закончите торговлю на этот день, сумма риска надень будет поделена на количество убыточных сделок.
8. Позиция: можно вписать дату начала позиции и цены Entry и SL
9. ATR – укажите количество последних свечей для расчета среднего движения цены выбранного time frame
Теперь что касается таблиц расположенных по умолчанию с лева и справа в низу экрана, я сделал окна с описаниями, при наведении курсора на ячейку всплывает описание.
LBR-Volatility Breakout BarsThe originator of this script is Linda Raschke of LBR Group.
This Pine Script code is the version 5 of LBR Paintbars for TradingView, called "LBR-Bars." It was originally coded for TradingView in version 3 by LazyBear. It is a complex indicator that combines various features such as coloring bars based on different conditions, displaying Keltner channels, and showing volatility lines.
Let me break down the key components and explain how it works:
1. Inputs Section: This section defines various input parameters that users can adjust when adding the indicator to their charts. These parameters allow users to customize the behavior and appearance of the indicator. Here are some of the key input parameters:
- Users can control whether to color bars under different conditions. For example,
they can choose to color LBR bars, color bars above/below Kelts, or color non-LBR
bars.
- Users can choose whether to show volatility lines or shade Keltner channels' area
with the Mid being the moving average on the chart.
- In the calculation of Keltner channels, users can set the length of the moving
average that the Keltner channels use as the mid and then set the Keltner multiplier.
If users want to use "True Range" to determine calculations, they can turn it on or
off; it defaults to off.
- Users can change the calculation of volatility lines and set the length for finding the
lowest and highest prices. The user sets the ATR length and multiplier for the ATR.
2. Calculation Section: This section defines the calculation of the upper and lower standard deviation bands based on the input parameters. It uses Exponential Moving Averages (EMAs) and optionally True Range to calculate these bands if turned on. These bands are used in the Keltner channel calculation.
3. Keltner Channel Section: This section calculates the upper, middle, and lower lines of the Keltner channels. It also plots these lines on the chart. The colors and visibility of these lines are controlled by user inputs.
4. Volatility Lines Section: This section calculates the upper and lower volatility lines based on the lowest and highest prices over a specified period and the ATR. It also checks whether the current close price is above or below these lines accordingly. The colors and visibility of these lines are controlled by user inputs.
5. Bar Colors Section: This section determines the color of the bars on the chart based on various conditions. It checks whether the current bar meets conditions like being an LBR bar, being above or below volatility lines, or being in "No Man's Land." The color of the bars is set accordingly based on user inputs.
This Pine Script creates an indicator that provides visual cues on the chart based on Keltner channels, volatility lines, and other customizable conditions. Users can adjust the input parameters to tailor the indicator's behavior and appearance to their trading preferences.
Heatmap MACD Strategy - Pineconnector (Dynamic Alerts)Hello traders
This script is an upgrade of this template script.
Heatmap MACD Strategy
Pineconnector
Pineconnector is a trading bot software that forwards TradingView alerts to your Metatrader 4/5 for automating trading.
Many traders don't know how to dynamically create Pineconnector-compatible alerts using the data from their TradingView scripts.
Traders using trading bots want their alerts to reflect the stop-loss/take-profit/trailing-stop/stop-loss to breakeven options from your script and then create the orders accordingly.
This script showcases how to create Pineconnector alerts dynamically.
Pineconnector doesn't support alerts with multiple Take Profits.
As a workaround, for 2 TPs, I had to open two trades.
It's not optimal, as we end up paying more spreads for that extra trade - however, depending on your trading strategy, it may not be a big deal.
TradingView Alerts
1) You'll have to create one alert per asset X timeframe = 1 chart.
Example : 1 alert for EUR/USD on the 5 minutes chart, 1 alert for EUR/USD on the 15-minute chart (assuming you want your bot to trade the EUR/USD on the 5 and 15-minute timeframes)
2) For each alert, the alert message is pre-configured with the text below
{{strategy.order.alert_message}}
Please leave it as it is.
It's a TradingView native variable that will fetch the alert text messages built by the script.
3) Don't forget to set the webhook URL in the Notifications tab of the TradingView alerts UI.
EA configuration
The Pyramiding in the EA on Metatrader must be set to 2 if you want to trade with 2 TPs => as it's opening 2 trades.
If you only want 1 TP, set the EA Pyramiding to 1.
Regarding the other EA settings, please refer to the Pineconnector documentation on their website.
Logger
The Pineconnector commands are logged in the TradingView logger.
You'll find more information about it from this TradingView blog post
Important Notes
1) This multiple MACDs strategy doesn't matter much.
I could have selected any other indicator or concept for this script post.
I wanted to share an example of how you can quickly upgrade your strategy, making it compatible with Pineconnector.
2) The backtest results aren't relevant for this educational script publication.
I used realistic backtesting data but didn't look too much into optimizing the results, as this isn't the point of why I'm publishing this script.
3) This template is made to take 1 trade per direction at any given time.
Pyramiding is set to 1 on TradingView.
The strategy default settings are:
Initial Capital: 100000 USD
Position Size: 1 contract
Commission Percent: 0.075%
Slippage: 1 tick
No margin/leverage used
For example, those are realistic settings for trading CFD indices with low timeframes but not the best possible settings for all assets/timeframes.
Concept
The Heatmap MACD Strategy allows selecting one MACD in five different timeframes.
You'll get an exit signal whenever one of the 5 MACDs changes direction.
Then, the strategy re-enters whenever all the MACDs are in the same direction again.
It takes:
long trades when all the 5 MACD histograms are bullish
short trades when all the 5 MACD histograms are bearish
You can select the same timeframe multiple times if you don't need five timeframes.
For example, if you only need the 30min, the 1H, and 2H, you can set your timeframes as follow:
30m
30m
30m
1H
2H
Risk Management Features
All the features below are pips-based.
Stop-Loss
Trailing Stop-Loss
Stop-Loss to Breakeven after a certain amount of pips has been reached
Take Profit 1st level and closing X% of the trade
Take Profit 2nd level and close the remaining of the trade
Custom Exit
I added the option ON/OFF to close the opened trade whenever one of the MACD diverges with the others.
Help me help the community
If you see any issue when adding your strategy logic to that template regarding the orders fills on your Metatrader, please let me know in the comments.
I'll use your feedback to make this template more robust. :)
What's next?
I'll publish a more generic template built as a connector so you can connect any indicator to that Pineconnector template.
Then, I'll publish a template for Capitalise AI, ProfitView, AutoView, and Alertatron.
Thank you
Dave
Interactive MA Stop Loss [TANHEF]This indicator is "Interactive." Once added to the chart, you need to click the start point for the moving average stoploss. Dragging it afterward will modify its position.
Why choose this indicator over a traditional Moving Average?
To accurately determine that a wick has crossed a moving average, you must examine the moving average's range on that bar (blue area on this indicator) and ensure the wick fully traverses this area.
When the price moves away from a moving average, the average also shifts towards the price. This can make it look like the wick crossed the average, even if it didn't.
How is the moving average area calculated?
For each bar, the moving average calculation is standard, but when the current bar is involved, its high or low is used instead of the close. For precise results, simply setting the source in a typical moving average calculation to 'Low' or 'High' is not sufficient in calculating the moving average area on a current bar.
Moving Average Options:
Simple Moving Average
Exponential Moving Average
Relative Moving Average
Weighted Moving Average
Indicator Explanation
After adding indicator to chart, you must click on a location to begin an entry.
The moving average type can be set and length modified to adjust the stoploss. An optional profit target may be added.
A symbol is display when the stoploss and profit target are hit. If a position is create that is not valid, "Overlapping MA and Bar" is displayed.
Alerts
'Check' alerts to use within indicator settings (stop hit and/or profit target hit).
Select 'Create Alert'
Set the condition to 'Interactive MA''
Select create.
Alert messages can have additional details using these words in between two Curly (Brace) Brackets:
{{stop}} = MA stop-loss (price)
{{upper}} = Upper MA band (price)
{{lower}} = Lower MA band (price)
{{band}} = Lower or Upper stoploss (word)
{{type}} = Long or Short stop-loss (word)
{{stopdistance}} = Stoploss Distance (%)
{{targetdistance}} = Target Distance (%)
{{starttime}} = Start time of stoploss (day:hour:minute)
{{maLength}} = MA Length (input)
{{maType}} = MA Type (input)
{{target}} = Price target (price)
{{trigger}} = Wick or Close Trigger input (input)
{{ticker}} = Ticker of chart (word)
{{exchange}} = Exchange of chart (word)
{{description}} = Description of ticker (words)
{{close}} = Bar close (price)
{{open}} = Bar open (price)
{{high}} = Bar high (price)
{{low}} = Bar low (price)
{{hl2}} = Bar HL2 (price)
{{volume}} = Bar volume (value)
{{time}} = Current time (day:hour:minute)
{{interval}} = Chart timeframe
{{newline}} = New line for text
I will add further moving averages types in the future. If you suggestions post them below.
Clone Pivots. Oct_2023Conceptually very simple.
The all time high or low of the chart (this indicator can be used with non-price sources as well), is used to divide the price pane continuously by 2.
For example the first pivot is (All Time High + All Time Low)/2.
From this point the price chart is further divided by 2.
The user can set the depth of division, and the lines for depth are only shown around the price.
About clone pivots.
- they can be used for ladder trading
- they are based on the range of the stock or instrument price
An alternative is available to use Fib divisions rather than simple divide by 2 method.
Labels may be placed with price or without. And depth of labelling is also an option.
Clone pivots at 50% tend to work very well with price structures - give it a try and see if it helps your trading!
Pine source uses UDTs, Methods, Arrays and Maps.
Manual Buy&Sell Alerts [Starbots]This is a simple Strategy created to help you manually execute open or close orders via Alerts on Exchanges or Platforms.
More and more Exchanges and Platforms allow Tradingview Alert trading and sometimes we come to a problem that we can not sell an open order on the exchanges other way than signaling a sell or buy from Tradingview Alerts.
This is a tool to solve that problem as your are able to manually:
- send alert on limit targets (Long limit target, Short limit target, Take Profit limit target, Stop Loss limit target)
- send alert when new live bar opens on the market (simple way for closing your open trades on the Exchange/Platform - it will sell your open Long/Short order after new live bar is opened on the market)
Functions:
- 🕛Start
Define a start time for strategy to open/close trades
- 🕐Stop Trading after your Order is Closed
If you wish to stop opening/closing trades after your first position is successfully closed keep this turned on. If you wish to keep opening/closing trades indefinitely when the conditions are met keep this turned off.
🏁Buy&Sell By Limit Target
-Buy Price
-Take Profit
-Stop Loss
-🟢Enable Long Limit Orders
-🔴Enable Short Limit Orders
If you enable Enable Long or Short limit orders you will be able to execute trades when the price reaches your limit target lines.
Please Note that if you turn on Shorting, your Take Profit limit target must be 'UNDER' your buy price and Stop Loss limit target must be 'ABOVE' your buy price.
Type in your limit values manually or re-apply the strategy to your chart to select limit targets again with a mouse - you can also drag the limit lines to your wanted areas.
(I recommend using low time-frame charts - 30s, 1minute for fast executions)
🏁Buy&Sell After New Bar Opens
-🟢Open Long
-Close Long on a new Open Bar
-🔴Open Short
-Close Short on a new Open Bar
This is a simple way for closing your open trade on Exchanges. If you select Open Long/Short and then Close Long/Short on a new Open bar it will sell your open order and send sell alert when the new bar is opened on the market. Choose your time-frame and execute immediate sell order when a new bar is opened. You can select low 15s-30s-1minute charts to quickly get a sell alert.
Alerts
Long Message
Short Message
Exit Long Message
Exit Short Message
You can type in your webhook alert messages in this inputs. Write this code in 'Message' when creating Alert for strategy to send your Buy/Sell messages from above inputs.
{{strategy.order.alert_message}}
If you trade on exchanges and use different dynamic alert message to trade from Strategies, then you can just leave Alert inputs empty and write down your message alert in 'Message' box when creating new alert normally.
>> Do not forget to also set order size and pyramiding in properties tab correctly in this case.
Double RSI 00 1.0This script creates a custom indicator, visualizes two RSI values (RSI1 and RSI2) on the chart and generates alerts based on different RSI-related conditions, which can be used for technical analysis and trading strategies. Users can customize the RSI parameters and alert levels according to their preferences.
It includes several input parameters that allow the user to customize the RSI calculations and overbought/oversold levels. These parameters include:
length_1: RSI1 Length (default: 7)
length_2: RSI2 Length (default: 12)
overbought_1: Overbought Signal level for RSI1 (default: 75)
oversold_1: Oversold Signal level for RSI1 (default: 25)
overbought_2: High Overbought Signal level for RSI1 (default: 85)
oversold_2: High Oversold Signal level for RSI1 (default: 15)
The script calculates two RSI values: rsi_1 and rsi_2, based on the high and low prices averaged (hl2) and the specified RSI lengths.
It plots these RSI values on the chart using different colors and line widths.
Several horizontal lines are drawn on the chart to represent key levels:
h0: 0 (Lower Band)
h1: 50 (Middle Band)
h2: 100 (Upper Band)
h3: The Oversold level (customizable)
h4: The Overbought level (customizable)
h5: The High Oversold level (customizable)
h6: The High Overbought level (customizable)
The script defines alert conditions for various signals, including overbought, oversold, high overbought, high oversold, long (crossover between RSI1 and RSI2), and short (crossunder between RSI1 and RSI2).
It sends alerts when these conditions are met, indicating potential trading signals.
Please note that this script is meant for educational purposes and should be used cautiously in a real trading environment. It's important to have a thorough understanding of technical analysis and risk management when using such indicators in actual trading.