Lot Size Calculator (Calculateur de Taille de Lot)🚀 Description du Script :
This script is designed to automatically calculate the ideal lot size for your trades based on several risk management parameters. It's particularly useful for traders who want to adjust their position size according to their total capital, the risk percentage per trade, and the stop-loss distance.
Main Features:
Automatic Lot Size Calculation: Based on capital, risk percentage, and stop-loss distance (in points or pips).
Currency Conversion Support: The script allows you to select the currency of your capital (USD, EUR, GBP, JPY, etc.), and automatically adjusts the calculation based on the real-time exchange rate.
Supports Forex and Indices: The script accounts for the specifics of the Forex market (calculating lots in pips) and indices (rounding to whole lots).
Dynamic Language Support: Users can select between English and French to adjust the labels and parameters in the script, providing a bilingual experience.
Dynamic Display: The calculated lot size is displayed directly on the chart for easy and quick reference during trade analysis.
Parameters:
Total Capital: The total amount of your trading capital.
Capital Currency: The currency in which your capital is denominated (USD, EUR, GBP, etc.).
Risk Per Trade (%): The percentage of your capital you are willing to risk per trade.
Stop-Loss Distance (Points/Pips): The distance between your entry price and stop-loss, in pips (for Forex) or points (for indices).
Language: Choose between English or French for the parameter labels and the user interface.
How to Use:
This calculator is ideal for traders looking to manage their risk professionally. Based on your capital and the amount of risk you are willing to take, the script automatically calculates the lot size to help you make informed decisions in the market.
Notes:
Make sure exchange rates for currency conversion are properly retrieved for accurate calculations.
This script is designed for use with Forex pairs as well as stock indices (where lot size must be a whole number).
Feel free to add it to your charts and incorporate it into your risk management strategies!
Version française (pour ceux qui choisissent la langue française) :
🚀 Description du Script :
Ce script est conçu pour calculer automatiquement la taille de lot idéale pour vos transactions en fonction de plusieurs paramètres de gestion des risques. Il est particulièrement utile pour les traders qui souhaitent ajuster la taille de leur position en fonction de leur capital total, du pourcentage de risque par transaction et de la distance du stop-loss.
Fonctionnalités principales :
Calcul automatique de la taille de lot : Basé sur le capital, le pourcentage de risque et la distance du stop-loss (en points ou pips).
Support de la conversion de devises : Le script permet de sélectionner la devise de votre capital (USD, EUR, GBP, JPY, etc.) et ajuste automatiquement le calcul en fonction du taux de change en temps réel.
Support pour le Forex et les indices : Le script prend en compte les spécificités du marché Forex (calcul des lots en pips) et des indices (arrondi à des lots entiers).
Support dynamique des langues : Les utilisateurs peuvent choisir entre l'anglais et le français pour ajuster les libellés et les paramètres dans le script, offrant ainsi une expérience bilingue.
Affichage dynamique : La taille de lot calculée est affichée directement sur le graphique pour une référence rapide et facile pendant l'analyse des transactions.
Paramètres :
Capital Total : Le montant total de votre capital de trading.
Devise du Capital : La devise dans laquelle votre capital est libellé (USD, EUR, GBP, etc.).
Risque par Trade (%) : Le pourcentage de votre capital que vous êtes prêt à risquer par transaction.
Distance du Stop-Loss (Points/Pips) : La distance entre votre prix d'entrée et le stop-loss, en pips (pour le Forex) ou en points (pour les indices).
Langue : Choisissez entre l'anglais ou le français pour les libellés des paramètres et l'interface utilisateur.
Comment l'utiliser :
Ce calculateur est idéal pour les traders qui souhaitent gérer leur risque de manière professionnelle. En fonction de votre capital et du niveau de risque que vous êtes prêt à prendre, le script calcule automatiquement la taille du lot pour vous aider à prendre des décisions éclairées sur le marché.
Notes :
Assurez-vous que les taux de change pour la conversion des devises sont correctement récupérés pour des calculs précis.
Ce script est conçu pour être utilisé avec des paires Forex ainsi que des indices boursiers (où la taille des lots doit être un nombre entier).
N'hésitez pas à l'ajouter à vos graphiques et à l'intégrer dans vos stratégies de gestion des risques !
Gestione portafoglio
EMA 26/55/100/200The script does 26/55/100/200 EMA. This is useful specifically to take swing trading opportunities at 26 and 55 EMA.
Nifty/Gold RatioPrice of Nifty in Gold terms. Lower price is signal to buy nifty and higher price is signal to diversify portfolio using gold.
Nifty/Gold RatioPrice of NIFTY in GOLD. Highs indicate that Gold is getting cheaper, Lows indicate Nifty is getting cheaper.
Average Daily LiquidityIt is important to ensure sufficient stock trading liquidity so that you have sufficient volume to enter the trade and most importantly sufficient liquidity to exit the trade. Because daily trading liquidity can jump around so much by price changes and volume changes, it is important to smooth out the liquidity by using a moving average. Some use a 5 days (trading week) moving average, others use 10 day (2 weeks), 20 day ("month") and some use 65 day (quarter). The default is 10 days based upon the work of Colin Nicholson (The Aggressive Investor and Building Wealth in the Stock Market). Liquidity line changes color dependent upon the chart background luminescence. The amount you are planning to invest in a stock should have a liquidity of 10 (default) times that amount.
Title of Chart [Unitah]Title of Chart
A simple yet effective TradingView indicator designed to enhance your charting experience by displaying essential information directly on your charts.
Key Features:
✅ Customizable Title & Subtitle – Add a personalized title and subtitle to your chart. Customize text, color, size, and alignment to match your preferences.
✅ Date, Symbol & Timeframe Display – Easily view the current trading symbol, timeframe, and date directly on your chart. Customize the position, color, and text size for clear visibility.
✅ Flexible Positioning – Adjust the placement of the title, subtitle, and symbol information anywhere on the chart (top, middle, bottom, left, center, or right).
This indicator is particularly useful for traders who frequently save or share their charts, ensuring that every chart includes clear and professional-looking labels.
PnL MonitorThe PnL Monitor is a customizable tool designed to help traders track the Profit and Loss (PnL) of up to 20 currency pairs or assets in real-time. This script provides a clear and organized table that displays the entry price, and PnL percentage for each pair, making it an essential tool for monitoring open positions or tracking potential trades.
Key Features:
Multi-Asset Tracking:
Monitor up to 20 currency pairs or assets simultaneously. Simply input the pair symbol and your entry price, and the script will calculate the PnL in real-time.
Dynamic Table Positioning:
Choose where the table appears on your chart with the Table Position input. Options include:
Top Left
Top Right
Bottom Left
Bottom Right
Real-Time PnL Calculation:
The script fetches the current price of each pair and calculates the PnL percentage based on your entry price. Positive PnL is highlighted in green, while negative PnL is highlighted in red.
Exchange and Pair Separation:
The script automatically separates the exchange name (if provided) from the pair symbol, making it easier to identify the source of the data.
Customizable Inputs:
Add or remove pairs as needed.
Leave the price field blank for pairs you don’t want to track.
How to Use:
Input Your Pairs:
In the script settings, input the symbol of the pair (e.g., NASDAQ:AAPL or BTCUSD) and your entry price. Leave the price field blank for pairs you don’t want to track.
Choose Table Position:
Select where you want the table to appear on your chart.
Monitor PnL:
The table will automatically update with the current price and PnL percentage for each pair.
Why Use This Script?
Efficiency: Track multiple pairs in one place without switching charts.
Clarity: Easily identify profitable and losing positions at a glance.
Flexibility: Customize the table to fit your trading style and preferences.
Ideal For:
Forex, crypto, and stock traders managing multiple positions.
toolbox🔥 TOOLBOX - The Ultimate Trading Indicator 🔥
The Toolbox indicator is designed to provide advanced technical analysis while integrating essential risk management tools. It caters to both beginner and experienced traders, helping optimize decision-making through a combination of technical indicators and risk management strategies.
⚙️ Features & Detailed Explanation
📌 Built-in Risk Management
✅ Automatic position size calculation: Based on total capital and user-defined risk percentage per trade.
✅ Stop-Loss (SL) & Take-Profit (TP) levels display: Automatically calculated based on a customizable risk/reward ratio.
✅ Smart Break Even (BE): Option to move the stop-loss to entry price after reaching a certain profit level.
🔹 Available Settings:
Total Capital 💰: Defines the trading capital.
Risk Percentage per Trade ⚠: Adjusts position size dynamically.
TP/SL Ratio 🎯: Controls the Take-Profit based on the Stop-Loss.
Break Even Activation 🔹: Secure profits automatically.
📊 Included Technical Indicators
Toolbox combines several powerful technical indicators to identify the best market opportunities.
🔄 Exponential Moving Averages (EMA)
EMA 12 & 25: Used for crossover signals.
EMA 200: Acts as a major trend filter.
✔️ If the price is above EMA 200, the trend is bullish.
✔️ If the price is below EMA 200, the trend is bearish.
New: EMA 199 & EMA 260! 🎯
These two additional EMAs provide an independent trend filter, reducing false signals.
📈 Relative Strength Index (RSI)
A classic RSI (14-period) helps spot overbought and oversold conditions.
✔️ Potential buy when RSI crosses above 30.
✔️ Potential sell when RSI crosses below 70.
📉 Bollinger Bands (BB)
Bollinger Bands (20, 2) help identify volatility expansions and potential reversals.
✔️ A close outside the bands may indicate a reversal.
📊 MACD (Moving Average Convergence Divergence)
The MACD (12, 26, 9) detects momentum shifts in the market and confirms other indicator signals.
✔️ Bullish signal: MACD crosses above the signal line.
✔️ Bearish signal: MACD crosses below the signal line.
📉 Triple EMA (TEMA)
An advanced trend filter using TEMA 9, 21, and 50.
✔️ Crossovers between short and medium TEMA indicate momentum shifts.
🚀 Entry Signals & Graphical Display
The Toolbox indicator automatically generates buy and sell signals based on trend and indicator crossovers.
✔️ TP/SL levels displayed on the chart with text labels.
✔️ Break Even (BE) lines appear when a trade reaches a predefined profit level.
✔️ Entry points marked visually with black crosses.
✅ Each indicator can be individually enabled or disabled from the settings panel.
🎯 Why Use Toolbox?
✅ Comprehensive Indicator combining technical analysis & risk management.
✅ Suitable for all trading styles: scalping, day trading, swing trading.
✅ Fully customizable: Enable or disable any indicator as needed.
✅ Optimized trade execution & risk security through advanced risk settings.
🔥 Future Updates - Version 2 in Progress!
The goal of Toolbox is to continuously evolve based on user feedback to become an even more powerful and competitive indicator. 🚀
💡 Do you have suggestions for improvements or new features?
💬 Leave your feedback in the comments or send a message!
➡ Which additional indicators would you like to see in V2?
📩 Share your thoughts to help make Toolbox even better!
🔥 Thank you for using TOOLBOX - The Ultimate Trading Indicator! 🔥
📈 Happy trading, and stay tuned for V2! 🚀
🔥 TOOLBOX - L'Indicateur Ultime du Trader 🔥
L’indicateur Toolbox est conçu pour fournir une analyse technique avancée, tout en intégrant des outils essentiels de gestion du risque. Il s'adresse aux traders débutants comme expérimentés et permet d’optimiser la prise de décision grâce à une combinaison d’indicateurs techniques et de stratégies de gestion du risque.
⚙️ Fonctionnalités et Explications Détaillées
📌 Gestion du Risque Intégrée
✅ Calcul automatique de la taille de position : En fonction du capital total et du risque défini par l’utilisateur (exprimé en % par trade).
✅ Affichage des niveaux de Stop-Loss (SL) et Take-Profit (TP) : Les niveaux sont calculés dynamiquement en fonction d’un ratio risque/récompense personnalisable.
✅ Break Even (BE) intelligent : Option pour déplacer le stop-loss au point d’entrée après un certain seuil de profit atteint.
🔹 Paramètres disponibles :
Capital Total 💰 : Définit le capital à risque.
% de Risque par trade ⚠ : Ajuste automatiquement la taille de position.
Ratio TP/SL 🎯 : Ajuste le Take-Profit en fonction du Stop-Loss.
Activation du Break Even 🔹 : Permet une sécurisation automatique des gains.
📊 Indicateurs Techniques Inclus
L’outil combine plusieurs indicateurs techniques puissants pour identifier les meilleures opportunités de marché.
🔄 Moyennes Mobiles Exponentielles (EMA)
Les EMA 12 et 25 servent de signaux de croisement, tandis que la EMA 200 est utilisée comme barrière de tendance principale.
✔️ Si le prix est au-dessus de la EMA 200, la tendance est haussière.
✔️ Si le prix est en dessous, la tendance est baissière.
Nouveauté : EMA 199 & EMA 260 ! 🎯
Ces deux moyennes mobiles indépendantes permettent un filtrage supplémentaire de la tendance pour éviter les faux signaux.
📈 RSI (Relative Strength Index)
Un RSI classique en 14 périodes est inclus pour repérer les surachats et surventes.
✔️ Achat potentiel si le RSI passe au-dessus de 30
✔️ Vente potentielle si le RSI passe en dessous de 70
📉 Bandes de Bollinger (BB)
Les Bandes de Bollinger (20, 2) aident à repérer des ruptures de volatilité et des points de retournement.
✔️ Une clôture en dehors des bandes peut signaler une extension excessive et un possible retournement.
📊 MACD (Moving Average Convergence Divergence)
Le MACD (12, 26, 9) est utilisé pour détecter les changements d’élan du marché et confirmer les signaux des autres indicateurs.
✔️ Signal haussier : Croisement du MACD au-dessus de la ligne de signal.
✔️ Signal baissier : Croisement du MACD en dessous de la ligne de signal.
📉 Triple EMA (TEMA)
Un filtre de tendance avancé basé sur le TEMA 9, 21 et 50.
✔️ Les croisements du TEMA court avec le TEMA moyen indiquent des changements de dynamique.
🚀 Signaux d’Entrée & Affichage sur le Graphique
L’indicateur Toolbox génère automatiquement des signaux d’achat et de vente en fonction des tendances et des croisements d’indicateurs.
✔️ Affichage des niveaux TP/SL sur le graphique avec étiquettes textuelles.
✔️ Lignes de Break Even (BE) lorsqu’un certain niveau de profit est atteint.
✔️ Repères visuels pour les points d’entrée sous forme de croix noires.
✅ Option pour activer/désactiver chaque indicateur individuellement depuis le panneau de configuration.
🎯 Pourquoi utiliser Toolbox ?
✅ Indicateur complet combinant analyse technique et gestion du risque.
✅ Adapté à tous les styles de trading : scalping, day trading, swing trading.
✅ Personnalisable : chaque indicateur peut être activé ou désactivé selon les préférences.
✅ Idéal pour optimiser les prises de position tout en sécurisant les trades grâce aux paramètres de risque avancés.
🔥 Évolution et Améliorations Futures - Version 2 en Préparation !
L’objectif de Toolbox est d’évoluer en fonction des retours de la communauté pour devenir un indicateur toujours plus complet et performant. 🚀
💡 Vous avez des idées d’améliorations ou souhaitez voir de nouveaux indicateurs intégrés ?
💬 Laissez vos suggestions en commentaire ou envoyez un message !
➡ Quels autres indicateurs aimeriez-vous voir ajoutés dans la V2 ?
📩 Partagez votre feedback pour rendre Toolbox encore plus puissant !
🔥 Merci d’utiliser TOOLBOX - L’indicateur du trader exigeant ! 🔥
📈 Bon trading et à bientôt pour la V2 ! 🚀
Multi Asset Similarity MatrixProvides a unique and visually stunning way to analyze the similarity between various stock market indices. This script uses a range of mathematical measures to calculate the correlation between different assets, such as indices, forex, crypto, etc..
Key Features:
Similarity Measures: The script offers a range of similarity measures to choose from, including SSD (Sum of Squared Differences), Euclidean Distance, Manhattan Distance, Minkowski Distance, Chebyshev Distance, Correlation Coefficient, Cosine Similarity, Camberra Index, Mean Absolute Error (MAE), Mean Squared Error (MSE), Lorentzian Function, Intersection, and Penrose Shape.
Asset Selection: Users can select the assets they want to analyze by entering a comma-separated list of tickers in the "Asset List" input field.
Color Gradient: The script uses a color gradient to represent the similarity values between each pair of indices, with red indicating low similarity and blue indicating high similarity.
How it Works:
The script calculates the source method (Returns or Volume Modified Returns) for each index using the sec function.
It then creates a matrix to hold the current values of each index over a specified window size (default is 10).
For each pair of indices, it applies the selected similarity measure using the select function and stores the result in a separate matrix.
The script calculates the maximum and minimum values of the similarity matrix to normalize the color gradient.
Finally, it creates a table with the index names as rows and columns, displaying the similarity values for each pair of indices using the calculated colors.
Visual Insights:
The indicator provides an intuitive way to visualize the relationships between different assets. By analyzing the color-coded tables, traders can gain insights into:
Which assets are highly correlated (blue) or uncorrelated (red)
The strength and direction of these correlations
Potential trading opportunities based on similarities and differences between assets
Overall, MASM is a powerful tool for market analysis and visualization, offering a unique perspective on the relationships between various assets.
~llama3
Asset Allocation CalculatorOverview
This script is a tool that automatically calculates asset allocation for your investment portfolio. Users can set the weight of multiple assets and monitor the portfolio value in real time based on price fluctuations.
Key Features
Supports input of asset allocation percentages
Dynamic allocation calculation based on real-time price data
Automatically calculates allocated amounts for each asset based on the total investment amount
User-friendly interface with intuitive visual feedback
Settings
Total Capital : Enter the total capital, including the value of assets.
Quantity rounding : Using the rounding function may cause the target allocation to exceed 100%.
Tickers, Weight, Holdings :
To retrieve accurate asset prices, specify both the exchange and the ticker.
If you want to include cash in your portfolio, use $.
Ensure that the total allocation sums to 100%.
Refer to the pre-filled example for the correct format.
Table Settings : You can adjust the table's position, height, font size, and background color.
How to Use
By buying or selling the quantity shown in the Buy column, you can continuously maintain your target allocation.
Hold - Current holdings
Buy - Quantity to buy or sell to reach the target allocation
Target - Quantity aimed for after buying or selling
Caution
It can only calculate for a single currency, so do not mix multiple currency markets.
자산 배분 계산기
소개
이 스크립트는 투자 포트폴리오의 자산 배분을 자동으로 계산해주는 도구입니다. 사용자는 여러 자산의 비중을 설정할 수 있으며, 가격 변동에 따라 포트폴리오 가치를 실시간으로 모니터링할 수 있습니다.
주요 기능
자산 배분 비율 입력 지원
실시간 가격 데이터를 기반으로 한 동적 배분 계산
총 투자 금액을 기준으로 각 자산에 할당된 금액 자동 계산
직관적인 시각적 피드백을 제공하는 사용자 친화적인 인터페이스
설정
Total Capital : 자산 가치를 포함한 총 자본금을 입력하세요.
Quantity rounding : 반올림 기능을 사용하면 목표 비중이 100%를 초과할 수 있습니다.
Tickers, Weight, Holdings :
정확한 자산 가격을 불러오기 위해 거래소와 티커를 함께 입력하세요.
포트폴리오에 현금을 포함하려면 '$'를 사용하세요.
비중 합계가 반드시 100%가 되도록 설정하세요.
예제 형식을 참고하여 올바르게 입력하세요.
한국(원화) 시장을 위한 입력 예시입니다.
KRX:360750, 17.5, 100
KRX:310960, 17.5, 120
KRX:148070, 25, 20
KRX:305080, 25, 10
KRX:139320, 10, 150
UPBIT:BTCKRW, 5, 0.002
$,0,5000000
Table Settings : 테이블의 위치, 높이, 글자 크기 및 배경색을 조정할 수 있습니다.
사용 방법
Buy 열에 표시된 수량만큼 매수 또는 매도하면 목표 비중을 지속적으로 유지할 수 있습니다.
Hold - 현재 보유 수량
Buy - 목표 비중을 맞추기 위해 매수 또는 매도해야 하는 수량
Target - 매수, 매도 후 목표로 하는 수량
주의
한 가지 통화로만 계산할 수 있으니 여러 통화 시장을 혼용하지 마세요.
Consecutive Bullish/Bearish Candles🔍 Overview:
This indicator detects market manipulation and deception by identifying sequences of consecutive bullish or bearish candles. It highlights potential reversal zones where trends may exhaust or trap traders before reversing.
📌 How It Works:
The user can set a custom number of consecutive bullish or bearish candles (default: 5).
If the set number of consecutive green (bullish) or red (bearish) candles appears, the indicator plots a signal on the chart.
This pattern often signals exhaustion, stop hunts, or market traps, making it useful for traders looking for reversal opportunities.
📊 Features:
✅ Customizable candle count for detection
✅ Visual signals (✅ for bullish, ❌ for bearish)
✅ Alerts support for automated notifications
✅ Works on all timeframes and all markets (crypto, stocks, forex)
⚠️ Note:
This indicator does not guarantee reversals but helps identify areas where traders may be trapped and a trend shift is likely. Always use it with other confluence factors like volume, support/resistance, and market sentiment.
🚀 Use this tool to spot market deception and trade smart!
The Ultimate Lot Size Calculator Backstory
I created this Pine Script tool to calculate lot sizes with precision. While there are many lot size calculators available on TradingView, I found that most had significant flaws. I started teaching myself Pine Script over three and a half years ago with the sole purpose of building this tool. My first version was messy and lacked accuracy, so I never published it. I wanted it to be better than any other available tool, but my limited knowledge back then held me back.
Recently, I received a request to create a similar tool, as the current options still fail to deliver the precision and reliability traders need. This inspired me to revisit my original idea. With improved skills and a better understanding of Pine Script, I redesigned the tool from scratch, making it as precise, reliable, and efficient as possible.
This tool features built-in error detection to minimize mistakes and ensure accuracy in lot size calculations. I've spent more time on this project than on any other, focusing on delivering a solution that stands out on TradingView. While I plan to add more features based on user feedback, the current version is already a powerful, dependable, and easy-to-use tool for traders who value precision and efficiency in their lot size calculations.
How to use the tool ?
At first it might seem complicated, but it is quite easy to use the tool. There are two modes: auto and manual. By default, the tool is set on manual mode. When you apply the tool on the chart, it will ask you to choose the entry price, then the stop-loss price, and at last the take-profit price. Select all of them one by one. These values can be changed later.
Settings
There are various setting given for making the tool as flexible as possible. Here is the explanation for some of most important settings. Play with them and make yourself comfortable.
General settings
Auto mode : Use this mode if you want the the risk reward to be fixed and stop loss to be based on ATR. However the stop loss can be changed to be based on user input.
Manual mode : Use this mode if you want full control over entry, stop loss and take profit.
Contract Size : The tool works perfectly for all forex pairs including gold and silver but as the contract size is different for different assets it is difficult to add every single asset into the script manually so i have provided this option. In case you want to calculate lot size for a asset other then forex, gold or silver make sure to change this. Contract size = Quantity of the asset in 1 standerd lot.
Account settings
Automatic mode settings and ATR stop settings
Manual mode settings
Table and risk-reward box settings are pretty much self-explanatory i guess.
Error handling
A lot size calculator is a complex program. There are numerous points where it may fail and produce incorrect results. To make it robust and accurate, these issues must be addressed and managed properly, which practically all existing lot size calculator scripts fail to do.
Golden tip
When the symbol is changed it will display a symbol change warning as the entry, stop loss and take profit price won't change.
There are 2 ways to get fix this. Either manually enter all three values which i hate the most or remove the script from the chart and re-apply the script on chart again.
So to re-apply the indicator in most easy way follow the following instructions:
Note : If you encounter any other error then read the instruction to fix it and if it is an unknow error pleas report it to me in comments or DM.
DCA Price LevelsThe indicator is used to set price targets in the chart on the basis of waste.
Whenever the price falls from the current DCA price to minus 30 percent, a new price target is set.
There are a total of 10 price targets, so a drop of up to minus 71 percent is covered by the default setting.
The number of price targets can be set individually, up to a maximum of 10, and the percentages can also be changed.
Money Flow Index MTF + Alerts with Candle Opacity & LabelsHow to Use the Money Flow Index MTF + Alerts with Candle Opacity & Labels Indicator
Overview:
This indicator is designed to help you gauge the buying and selling pressure in a market by using the Money Flow Index (MFI). Unlike many momentum oscillators, the MFI incorporates both price and volume, providing a unique perspective on market activity. It is particularly useful when you want to visually assess potential overbought or oversold conditions.
Indicator Components:
Money Flow Index (MFI) Calculation:
The indicator computes the MFI using a user-defined look-back period (default is 14 bars). The MFI is scaled between 0 and 100, where values above 80 typically indicate overbought conditions and values below 20 suggest oversold conditions.
Multi-Timeframe (MTF) Capability:
You can choose to calculate the MFI using either the current chart’s timeframe or a custom timeframe (for example, a 4-hour chart). This flexibility allows you to compare longer-term money flow trends against your primary trading timeframe.
Candle Opacity Based on MFI:
The opacity of the candles on your chart is dynamically adjusted based on the current MFI reading. When the MFI is high (near 100), candles become more opaque; when the MFI is low (near 0), candles appear more transparent. This visual cue can help you quickly spot changes in market momentum.
Visual Labels for Overbought/Oversold Conditions:
When the MFI crosses into the overbought territory, a red label reading “Overbought” is displayed above the high of the bar. Similarly, when it crosses into the oversold territory, a green label reading “Oversold” is placed below the low of the bar. These labels provide an immediate visual alert to potential reversal points or areas of caution.
Alert Conditions:
The script also includes alert conditions for both overbought and oversold signals. You can set up TradingView alerts so that you are notified in real time when the indicator detects these conditions.
Theory Behind the Money Flow Index (MFI):
The Money Flow Index is a momentum oscillator that uses both price and volume to signal the strength behind price moves.
Overbought Conditions: When the MFI is above 80, it suggests that buying pressure is very strong and the asset might be due for a pullback or consolidation.
Oversold Conditions: Conversely, when the MFI falls below 20, selling pressure is high and the asset might be oversold, potentially priming it for a bounce.
Keep in mind that in strong trending markets, overbought or oversold readings can persist for extended periods, so the MFI should be used in conjunction with other technical analysis tools.
Position Management Guidance:
While the indicator is useful for spotting potential overbought and oversold conditions, it is not designed to serve as an automatic signal to completely close a position. Instead, you might consider using it as a guide for pyramiding—gradually adding to your position over several days rather than exiting all at once. This approach allows you to better manage risk by:
Scaling In or Out Gradually: Instead of making one large position change, you can add or reduce your position in increments as market conditions evolve.
Diversifying Risk: Pyramiding helps you avoid the pitfalls of trying to time the market perfectly on a single trade exit or entry.
How to Get Started:
Apply the Indicator:
Add the indicator to your TradingView chart. Adjust the input settings (length, oversold/overbought levels, and resolution) as needed for your trading style and the market you’re analyzing.
Watch the Candles:
Observe the dynamic opacity of your candles. A sudden change in opacity can be a sign that the underlying money flow is shifting.
Monitor the Labels:
Pay attention to the “Overbought” or “Oversold” labels that appear. Use these cues in combination with your broader analysis to decide if it might be a good time to add to or gradually exit your position.
Set Up Alerts:
Configure TradingView alerts based on the indicator’s alert conditions so that you are notified when the MFI reaches extreme levels.
Use as Part of a Broader Strategy:
Remember, no single indicator should dictate your entire trading decision. Combine MFI signals with other technical analysis, risk management rules, and market insights to guide your trades.
Price Action Trend and Margin EquityThe Price Action Trend and Margin Equity indicator is a multifunctional market analysis tool that combines elements of money management and price pattern analysis. The indicator helps traders identify key price action patterns and determine optimal entry, exit and stop loss levels based on the current trend.
The main components of the indicator:
Money Management:
Allows the trader to set risk management parameters such as the percentage of possible loss on the position, the use of fixed leverage and the total capital.
Calculates the required leverage level to achieve a specified percentage of loss.
Price Action:
Correctly identifies various price patterns such as Pin Bar, Engulfing Bar, PPR Bar and Inside Bar.
Displays these patterns on the chart with the ability to customize candle colors and display styles.
Allows the trader to customize take profit and stop loss points to display them on the chart.
The ability to display patterns only in the direction of the trend.
Trend: (some code taken from ChartPrime)
Uses a trend cloud to visualize the current market direction.
The trend cloud is displayed on the chart and helps traders determine whether the market is in an uptrend or a downtrend.
Alert:
Allows you to set an alert that will be triggered when the pattern is formed.
Example of use:
Let's say a trader uses the indicator to trade the crypto market. He sets the money management parameters, setting the maximum loss per position to 5% and using a fixed leverage of 1:100. The indicator automatically calculates the required position size to meet these parameters ($: on the label). Or displays the leverage (X: on the label) to achieve the required risk.
The trader receives an alert when a Pin Bar is formed. The indicator displays the entry, exit, and stop loss levels based on this pattern. The trader opens a position for the recommended amount in the direction indicated by the indicator and sets the stop loss and take profit at the recommended levels.
General Settings:
Position Loss Percentage: Sets the maximum loss percentage you are willing to take on a single position.
Use Fixed Leverage: Enables or disables the use of fixed leverage.
Fixed Leverage: Sets the fixed leverage level.
Total Equity: Specifies the total equity you are using for trading. (Required for calculation when using fixed leverage)
Turn Patterns On/Off: You can turn on or off the display of various price patterns such as Pin Bar, Outside Bar (Engulfing), Inside Bar, and PPR Bar.
Pattern Colors: Sets the colors for displaying each pattern on the chart.
Candle Color: Allows you to set a neutral color for candles that do not match the price action.
Show Lines: Allows you to turn on or off the display of labels and lines.
Line Length: Sets the length of the stop, entry, and take profit lines.
Label color: One color for all labels (configured below) or the color of the labels in the color of the candle pattern.
Pin entry: Select the entry point for the pin bar: candle head, bar close, or 50% of the candle.
Coefficients for stop and take lines.
Use trend for price action: When enabled, will show price action signals only in the direction of the trend.
Display trend cloud: Enables or disables the display of the trend cloud.
Cloud calculation period: Sets the period for which the maximum and minimum values for the cloud are calculated. The longer the period, the smoother the cloud will be.
Cloud colors: Sets the colors for uptrends and downtrends, as well as the transparency of the cloud.
The logic of the indicator:
Pin Bar is a candle with a long upper or lower shadow and a short body.
Logic: If the length of one shadow is twice the body and the opposite shadow of the candle, it is considered a Pin Bar.
An Inside Bar is a candle that is completely engulfed by the previous candle.
Logic: If the high and low of the current candle are inside the previous candle, it is an Inside Bar.
An Outside Bar or Engulfing is a candle that completely engulfs the previous candle.
Logic: If the high and low of the current candle are outside the previous candle and close outside the previous candle, it is an Outside Bar.
A PPR Bar is a candle that closes above or below the previous candle.
Logic: If the current candle closes above the high of the previous candle or below its low, it is a PPR Bar.
Stop Loss Levels: Calculated based on the specified ratios. If set to 1.0, it shows the correct stop for the pattern by pushing away from the entry point.
Take Profit Levels: Calculated based on the specified ratios.
Create a Label: The label is created at the stop loss level and contains information about the potential leverage and loss.
The formula for calculating the $ value is:
=(Total Capital x (Maximum Loss Percentage on Position/100)) / (Difference between Entry Level and Stop Loss Level × Ratio that sets the stop loss level relative to the length of the candlestick shadow × Fixed Leverage Value) .
Labels contain the following information:
The percentage of price change from the recommended entry point to the stop loss level.
Required Leverage (X: ): The amount of leverage required to achieve the specified loss percentage. (Or a fixed value if selected).
Required Capital ($: ): The amount of capital required to open a position with the specified leverage and loss percentage (only displayed when using fixed leverage).
The trend cloud identifies the maximum and minimum price values for the specified period.
The cloud value is set depending on whether the current price is equal to the high or low values.
If the current closing price is equal to the high value, the cloud is set at the low value, and vice versa.
RU
Индикатор "Price Action Trend and Margin Equity" представляет собой многофункциональный инструмент для анализа рынка, объединяющий в себе элементы управления капиталом и анализа ценовых паттернов. Индикатор помогает трейдерам идентифицировать ключевые прайс экшн паттерны и определять оптимальные уровни входа, выхода и стоп-лосс на основе текущего тренда.
Основные компоненты индикатора:
Управление капиталом:
Позволяет трейдеру задавать параметры управления рисками, такие как процент возможного убытка по позиции, использование фиксированного плеча и общий капитал.
Рассчитывает необходимый уровень плеча для достижения заданного процента убытка.
Price Action:
Правильно идентифицирует различные ценовые паттерны, такие как Pin Bar, Поглащение Бар, PPR Bar и Внутренний Бар.
Отображает эти паттерны на графике с возможностью настройки цветов свечей и стилей отображения.
Позволяет трейдеру настраивать точки тейк профита и стоп лосса для отображения их на графике.
Возможность отображения паттернов только в натправлении тренда.
Trend: (часть кода взята у ChartPrime)
Использует облако тренда для визуализации текущего направления рынка.
Облако тренда отображается на графике и помогает трейдерам определить, находится ли рынок в восходящем или нисходящем тренде.
Оповещение:
Дает возможность установить оповещение которое будет срабатывать при формировании паттерна.
Пример применения:
Предположим, трейдер использует индикатор для торговли на крипто рынке. Он настраивает параметры управления капиталом, устанавливая максимальный убыток по позиции в 5% и используя фиксированное плечо 1:100. Индикатор автоматически рассчитывает необходимый объем позиции для соблюдения этих параметров ($: на лейбле). Или отображает плечо (Х: на лейбле) для достижения необходимого риска.
Трейдер получает оповещение о формировании Pin Bar. Индикатор отображает уровни входа, выхода и стоп-лосс, основанные на этом паттерне. Трейдер открывает позицию на рекомендуемую сумму в направлении, указанном индикатором, и устанавливает стоп-лосс и тейк-профит на рекомендованных уровнях.
Общие настройки:
Процент убытка по позиции: Устанавливает максимальный процент убытка, который вы готовы понести по одной позиции.
Использовать фиксированное плечо: Включает или отключает использование фиксированного плеча.
Уровень фиксированного плеча: Задает уровень фиксированного плеча.
Общий капитал: Указывает общий капитал, который вы используете для торговли. (Необходим для расчета при использовании фиксированного плеча)
Включение/отключение паттернов: Вы можете включить или отключить отображение различных ценовых паттернов, таких как Pin Bar, Outside Bar (Поглощение), Inside Bar и PPR Bar.
Цвета паттернов: Задает цвета для отображения каждого паттерна на графике.
Цвет свечей: Позволяет задать нейтральный цвет для свечей неподходящих под прйс экшн.
Показывать линии: Позволяет включить или отключить отображение лейблов и линий.
Длинна линий: Настройка длинны линий стопа, линии входа и тейк профита.
Цвет лейбла: Один цвет для всех лейблов (настраивается ниже) или цвет лейблов в цвет паттерна свечи.
Вход в пин: Выбор точки входа для пин бара: голова свечи, точка закрытия бара или 50% свечи.
Коэффиценты для стоп и тейк линий.
Использовать тренд для прайс экшна: При включении будет показывать прайс экшн сигналы только в направлении тренда.
Отображение облака тренда: Включает или отключает отображение облака тренда.
Период расчета облака: Устанавливает период, за который рассчитываются максимальные и минимальные значения для облака. Чем больше период, тем более сглаженным будет облако.
Цвета облака: Задает цвета для восходящего и нисходящего трендов, а также прозрачность облака.
Логика работы индикатора:
Pin Bar — это свеча с длинной верхней или нижней тенью и коротким телом.
Логика: Если длина одной тени вдвое больше тела и противоположной тени свечи, считается, что это Pin Bar.
Inside Bar — это свеча, полностью поглощенная предыдущей свечой.
Логика: Если максимум и минимум текущей свечи находятся внутри предыдущей свечи, это Inside Bar.
Outside Bar или Поглощение — это свеча, которая полностью поглощает предыдущую свечу.
Логика: Если максимум и минимум текущей свечи выходят за пределы предыдущей свечи и закрывается за пределами предыдущей свечи, это Outside Bar.
PPR Bar — это свеча, которая закрывается выше или ниже предыдущей свечи.
Логика: Если текущая свеча закрывается выше максимума предыдущей свечи или ниже ее минимума, это PPR Bar.
Уровни стоп-лосс: Рассчитываются на основе заданных коэффициентов. При значении 1.0 показывает правильный стоп для паттерна отталкиваясь от точки входа.
Уровки тейк-профита: Рассчитываются на основе заданных коэффициентов.
Создание метки: Метка создается на уровне стоп-лосс и содержит информацию о потенциальном плече и убытке.
Формула для вычисления значения $:
=(Общий капитал x (Максимальный процент убытка по позиции/100)) / (Разница между уровнем входа и уровнем стоп-лосс × Коэффициент, задающий уровень стоп-лосс относительно длины тени свечи × Значение фиксированного плеча).
Метки содержат следующую информацию:
Процент изменения цены от рекомендованной точки входа до уровня стоп-лосс.
Необходимое плечо (Х: ): Уровень плеча, необходимый для достижения заданного процента убытка. (Или фиксированное значение если оно выбрано).
Необходимый капитал ($: ): Сумма капитала, необходимая для открытия позиции с заданным плечом и процентом убытка (отображается только при использовании фиксированного плеча).
Облако тренда определяет максимальные и минимальные значения цены за указанный период.
Значение облака устанавливается в зависимости от того, совпадает ли текущая цена с максимальными или минимальными значениями.
Если текущая цена закрытия равна максимальному значению, облако устанавливается на уровне минимального значения, и наоборот.
Broad Market MOEX non normalazeBroad Market MOEX - Relative Strength Indicator for MOEX Stocks
This indicator allows you to compare the price dynamics of major Moscow Exchange stocks relative to the selected asset during the trading session.
Features:
• Tracks 10 key MOEX stocks: Sberbank, Rosneft, Lukoil, Gazprom Neft, NOVATEK, Nornickel, Polyus, Tatneft, Surgutneftegas, Severstal
• Shows the percentage price change of each stock relative to the base price at the start of trading (default 9:00 MSK)
• Allows you to customize the base time for reference
• Clearly displays the strength and weakness of individual stocks relative to each other
• Helps identify leaders and laggards during the trading session
How to use:
1. Add the indicator to any MOEX stock chart
2. Adjust the base time if needed (default 9:00)
3. Monitor the relative dynamics of stocks
4. Use for:
- Finding strong/weak stocks
- Identifying sector rotation
- Intraday trading
- Correlation analysis
Color coding of lines helps easily identify each stock on the chart.
The indicator is useful for intraday traders and anyone monitoring the relative strength of stocks on the Moscow Exchange.
Live Portfolio P<his script calculates live P&L (Profit & Loss) for up to 40 instruments — stocks, ETFs, options, futures, and Forex pairs supported by TradingView. Instead of juggling numerous inputs, you paste your portfolio in CSV format into a single text field, and the script handles the rest. It parses each position and displays a comprehensive table showing the symbol, current price, position value, total P&L, and today’s P&L—all updated in real time.
Key Features
CSV Portfolio Input – Effortlessly import all your positions at once without filling in multiple fields. You can export the position from your broker, save it in the required format, and paste it into this script.
Supports Various Asset Classes – Works with any instrument that TradingView provides data for, including futures, options, and Forex.
Up to 40 Instruments – Track a broad and diverse set of holdings in one place.
Real-Time Updates – Get immediate feedback on live price changes, total value, and current P&L.
Today’s P&L – Monitor your daily performance to gauge short-term trends.
CSV is consumed in the following format:
Symbol (supported TradingView instruments)
Entry Price
Quantity (negative for short position)
Lot Size (for futures/options, it might not be one)
For example:
AAPL,237,100,1
TSLA,400,-150,1
ESM2025,6000,5,50
Planned Enhancements
Multi-Currency Support – Automatically convert and display your positions’ values in different currencies.
Advanced Metrics – Get deeper insights with calculations for drawdown, Sharpe ratio, and more.
Risk Management Tools – Set stop-loss and take-profit levels and receive alerts when thresholds are hit.
Option Greeks & Margin Calculations – Manage complex option strategies and track margin requirements.
Questions for You
What additional features would you like to see?
Are there any specific metrics or analytics you’d find especially valuable?
How might this script fit into your current trading workflow?
Feel free to share your thoughts and suggestions. Your feedback will help shape future updates and make this tool even more helpful for traders like you!
Disclaimer
Please remember that past performance may not be indicative of future results.
Due to various factors, including changing market conditions, the strategy may no longer perform as well as in historical backtesting.
This post and the script don’t provide any financial advice.
Position Tracker 1.0Position Tracker 1.0 allows users to input their position using USD, quantity, or a DCA approach while setting take profit (TP) and stop loss (SL) levels based on either fixed dollar values or percentages. The indicator provides optional markers for TP/SL crossings and an entry label showing key trade details. A live tracker can be enabled for real-time P&L updates, and all visual elements are customizable for clarity and preference.
Instructions for Position Tracker 1.0
1. Input Method & Position Details:
* Choose between USD, Quantity, or DCA.
* Enter your entry price, entry time, investment amount, or quantity as needed.
2. TP & SL Setup:
* For each TP (up to 5) and the SL, select whether to use a fixed dollar target or a percentage
target relative to your entry price.
* Enter the corresponding price (if using Dollar) or percentage (if using Percentage).
* For TPs, specify the percentage of your position to sell when the level is hit.
3. Marker & Display Options:
* Toggle the TP and SL crossing markers on or off.
* Adjust which details (Price, Diff, Sell for TP; Price, Diff, Loss for SL) are shown on the labels.
* The entry label always shows the Avg. Cost and can optionally include the quantity, invested
amount, and live tracker (real-time P&L).
4. Visual Customization:
* Change text size, marker size, and colors for profit, loss, TP, and SL lines as desired.
Binance Pseudo Funding FeeThe indicator calculates the Funding Fee for Binance based on the Premium Index provided by TradingView. The calculation formula can be found here: Binance Funding Rate Introduction . This is NOT the official rate visible on binance.com and used for settlements, but rather an estimated rate, which is inherently INACCURATE . The accuracy of the calculation heavily depends on the timeframe, with almost perfect results on minute-based timeframes.
For the most accurate calculations, you need to visit Binance Funding History and fill in the corresponding Interval , Interest Rate , and Funding Cap/Floor settings for the specific symbol in the indicator's settings. I understand this is not convenient, but for now, this is how it works.
The blue bars indicate the settlement time. Funding can be smoothed using moving averages. Both the funding rate and the moving averages are displayed using plot and are labeled, so you can set alerts on them.
Sharpe and Sortino Ratios with Date RangeThis indicator calculates the Sharpe and Sortino ratios using a chart symbol's periodic price returns.
I added the ability to calculate SORTINO and Sharpe based on CUSTOM DATES within the option menu.
It builds on the script here: by adding this feature.
A little about the Sortino Ratio.
www.nasdaq.com
I want equity market returns, but I don’t want equity market volatility. This is the sentiment many investors naturally feel. This sentiment often grows stronger as one approaches or is in the phase where they desire distributions from their savings to improve lifestyle. This is why there is a need for active management in the investment arena. The desire to control downside volatility, but also participate in the upside growth is a very fundamental human desire. The Sortino Ratio measures how well a particular investment meets this fundamental human desire.
There is the old adage, “volatility is the price you pay for returns.” However, what if we could measure the historical performance of an investment and see if it has given above average returns compared to the downside volatility. This is a simple division problem. It will tell us if the volatility “price we are paying for returns” is good. We can then compare that to other investments to see how they compare.
Let us take the return and subtract the risk-free interest rate and then simply divide that by the downside movement from the average. A basic division problem yielding a number that measures a very basic human desire: How well did this investment do compared to the downside risk it experienced.
In the world of financial analysis and investment management, ratios are abundant. There are many ratios that are truly important to a particular analysis. However, the sheer abundance of ratios that are available often overwhelms the casual investor, leading them to disregard ratios altogether. I would argue for those investors that desire a way to rank an investment by its ability to satisfy this very fundamental human desire, the Sortino Ratio is the number they need to consider.
Disappointing in the marketplace for research, the Sortino Ratio is not featured prominently. It is much easier to find the inflows a particular ETF has experienced than the Sortino Ratio. Inflows are important. They measure how much people are investing into an ETF. However, they are mostly only important to the fund manager, not the investor. What investors care about is the Risk-Adjusted Return. This is the Sortino Ratio.
Rolling CAGRRolling CAGR (Compound Annual Growth Rate) Indicator
This indicator calculates and plots the rolling Compound Annual Growth Rate (CAGR) for any selected data source. CAGR represents the mean annual growth rate of an investment over a specified time period, taking into account the effect of compounding.
Features:
• Customizable data source (default: close price)
• Adjustable time period in years
• Configurable trading days per year (252 for stocks, 365 for crypto)
• Results displayed as percentage values
• Works on daily timeframes
Input Parameters:
• Data Source: Select the price or indicator data to analyze
• Number of Years: Set the lookback period for CAGR calculation
• Trading Days in a Year: Adjust based on market type (252 for stocks, 365 for crypto)
Usage:
Perfect for analyzing long-term growth rates and comparing investment performance across different periods. The indicator provides a rolling view of compound growth, helping traders and investors understand the sustained growth rate of an asset over their chosen timeframe.
Note: This indicator is designed for daily timeframes as CAGR calculations are most meaningful over longer periods.
Formula Used:
CAGR = (End Value / Start Value)^(1/number of years) - 1
Position Size Calculator (MOEX Futures)Описание на русском языке
Этот скрипт для TradingView создан специально для трейдеров, работающих с фьючерсами на Московской бирже. Его основная цель – помочь трейдерам быстро и точно рассчитывать параметры позиции, такие как количество контрактов, риск на сделку, общий размер маржи, а также цены стоп-лосса и тейк-профита.
Функционал:
Расчет цены контракта: учитывает цену актива (в пунктах) и стоимость одного пункта.
Риск на сделку: определяется как процент от общего капитала.
Размер позиции: рассчитывается на основе риска на сделку и стоп-лосса.
Количество контрактов: округляется до целого числа вниз.
Общий размер маржи: определяется исходя из количества контрактов и маржи на один контракт.
Цены стоп-лосса и тейк-профита: вычисляются как для лонг-, так и для шорт-позиций.
Интерактивная таблица: статично отображается в правом верхнем углу графика и обновляется автоматически при изменении входных данных.
Скрипт заточен исключительно под специфику фьючерсов Московской биржи и позволяет трейдерам оптимизировать расчёты, минимизировать ошибки и экономить время.
Description in English
This TradingView script is specifically designed for traders working with futures on the Moscow Exchange. Its primary purpose is to help traders quickly and accurately calculate position parameters, such as the number of contracts, risk per trade, total margin size, and stop-loss and take-profit prices.
Features:
Contract price calculation: Takes into account the asset price (in points) and the price per point.
Risk per trade: Defined as a percentage of the total capital.
Position size: Calculated based on the risk per trade and stop-loss percentage.
Number of contracts: Rounded down to the nearest whole number.
Total margin size: Determined based on the number of contracts and margin per contract.
Stop-loss and take-profit prices: Calculated for both long and short positions.
Interactive table: Statically displayed in the top-right corner of the chart and dynamically updated when input parameters change.
This script is tailored exclusively to the specifics of futures trading on the Moscow Exchange, enabling traders to optimize calculations, minimize errors, and save time.
[Helper] Trade Journal TableThis indicator serves as a starting point for creating a customized trade journal that meets individual requirements. It provides a basic structure for visualizing trade data in table form which can be adapt to specific needs. The trade data must be maintained directly within the script using the Pine Editor.
Basic Structure:
The example table consists of six columns: Date, Entry Price, Exit Price, Profit/Loss (color-coded), Strategy, and Notes. It is displayed centrally on the chart and dynamically adjusts to the number of recorded trades.
Example Data:
To demonstrate its functionality, the indicator includes predefined example trades, which should be replaced with actual trading data. Additional information, such as strategies and notes, can be added to improve trade documentation.