Reverse Repo CorrelationReverse Repo Correlation Indicator
This TradingView indicator calculates the correlation between the current stock's close price and the value of the Reverse Repo Rate (`RRPONTSYD`). It uses the Pearson correlation coefficient to measure the strength and direction of the relationship.
Inputs
- **Correlation Length**: The number of bars used to calculate the correlation.
- **Background Transparency**: The transparency level (0-100) for the background color indicating positive or negative correlation.
### How it works
1. The indicator retrieves the close price of the current stock and assigns it to the `stockClose` variable.
2. The **Correlation Length** input determines the number of bars used to calculate the correlation.
3. The `pearson_corr` function calculates the Pearson correlation between the `stockClose` and `rrpontsydValue` variables over the specified length.
4. The `rrpontsydValue` is retrieved using the `request.economic` function, which fetches the Reverse Repo Rate value (`RRPONTSYD`) for the "US" economic calendar.
5. The correlation value is plotted on the chart as a line, with positive correlations displayed in green and negative correlations in red.
6. The **Background Transparency** input determines the transparency level of the background color, which changes based on the correlation value. Positive correlations have a green background, while negative correlations have a red background.
Adjust the `correlationLength` and `transparency` inputs as needed.
Statistics
Cross Period Comparison IndicatorReally excited to be sharing this indicator!
This is the cross-period comparison indicator, AKA the comparison indicator.
What does it do?
The cross-period comparison indicator permits for the qualitative assessment of two points in time on a particular equity.
What is its use?
At first, I was looking for a way to determine the degree of similarity between two points, such as using Cosine similarity values, Euclidean distances, etc. However, these tend to trigger a lot of similarities but without really any context. Context matters in trading and thus what I wanted really was a qualitative assessment tool to see what exactly was happening at two points in time (i.e. How many buyers were there? What was short interest like? What was volume like? What was the volatility like? RSI? Etc.)
This indicator permits that qualitative assessment, displaying things like total buying volume during each period, total selling volume, short interest via Put to Call ratio activity, technical information such as Stochastics and RSI, etc.
How to use it?
The indicator is fairly self explanatory, but some things require a little more in-depth discussion.
The indicator will display the Max and Min technical values of a period, as well as a breakdown in the volume information and put to call information. The user can then make the qualitative determination of degrees of similarity. However, I have included some key things to help ascertain similarity in a more quantitative way. These include:
1. Adding average period Z-Score
2. Adding CDF probability distributions for each respective period
3. Adding Pearson correlations for each respective period over time
4. Providing the linear regression equation for each period
So let us discuss these 4 quantitative measures a bit more in-depth.
Adding Period Z-Score
For those who do not know, Z-Score is a measure of the distance from a mean. It generally spans 0 (at the mean) to 3 (3 standard deviations away from the mean). Z-Score in the stock market is very powerful because it is actually our indicator of volatility. Z-Score forms the basis of IV for option traders and it generally is the go to, to see where the market is in relation to its overall mean.
Adding Z-Score lets the user make 2 big determinations. First and foremost, it’s a measure of overall volatility during the period. If you are getting a Z-Score that is crazy high (1.5 or greater), you know there was a lot of volatility in that period marked by frequent deviations from its mean (since on average it was trading 1.5 standard deviations away from its mean).
The other thing it tells you is the overall sentiment of that time. If the average Z Score was 1.5 for example, we know that buying interest was high and the sentiment was somewhat optimistic, as the stock was trading, on average, + 1.5 SDs away from its mean.
If, on the other hand, the average was, say, - 1.2, then we know the sentiment was overall pessimistic. There was frequent selling and the stock was frequently being pushed below its mean with heavy selling pressure.
We can also check these assumptions of buying / selling buy verifying the volume information. The indicator will list the Buy to Sell Ratio (number of Buyers to Sellers), as well as the total selling volume and total buying volume. Thus, the user can see, objectively, whether sellers or buyers led a particular period.
Adding CDF Probability
CDF probabilities simply mean the extent a stock traded above or below its normal distribution levels.
To help you understand this, the indicator lists the average close price for a period. Directly below that, it lists the CDF probabilities. What this is telling you, is how often and how likely, during that period, the stock was trading below its average. For example, in the main chart, the average close price for BTC in Period A is 29869. The CDF probability is 0.51. This means, during Period A, 51% of the time, BTC was trading BELOW 29869. Thus, the other 49% of the time it was trading ABOVE 29869.
CDF probabilities also help us to assess volatility, similar to Z-Score. Generally speaking, the CDF should consistently be reading about 0.50 to 0.51. This is the point of an average value, half the values should be above the average and half the values should be below. But in times of heightened volatility, you may actually see the CDF creep up to 0.54 or higher, or 0.48 or lower. This means that there was extremely extensive volatility and is very indicative of true “whipsaw” type price action history where a stock refuses to average itself out in one general area and frequently jumps up and down.
Adding Pearson Correlation
Most know what this is, but just in case, the Pearson correlation is a measure of statistical significance. It ranges from 0 (not significant) to 1 (very significant). It can be positive or negative. A positive signifies a positive relationship (i.e. as one value increases so too does the other value being compared). If it is a negative value, it means an inverse relationship (i.e. one value increases proportionately to the other’s decline).
In this indicator, the Pearson correlation is measured against time. A strong positive relationship (a value of 0.5 or greater) indicates that the stock is trading positive to time. As time goes by, the stock goes up. This is a normal relationship and signifies a healthy uptrend.
Inversely, if the Pearson correlation is negative, it means that as time increases, the stock is going down proportionately. This signifies a strong downtrend.
This is another way for the user to interpret sentiment during a specific period.
IF the Pearson correlation is less than 0.5 or -0.5, this signifies an area of indecision. No real trend formed and there was no real strong relationship to time.
Adding Linear Regression Equation
A linear regression equation is simply the slope and the intercept. It is expressed with the formula y= mx + b.
The indicator does a regression analysis on each period and presents this formula accordingly. The user can see the slope and intercept.
Generally speaking, when two periods share the same slope (m value) but different intercept (b value), it can be said that the relationship to time is identical but the starting point is different.
If the slope and intercept are different, as you see in the BTC chart above, it represents a completely different relationship to time and trajectory.
Indicator Specific Information:
The indicator retains the customizability you would expect. You can customize all of your lengths for technical, change and Z-Score. You can toggle on or off Period data, if you want to focus on a single period. You can also toggle on a difference table that directly compares the % difference between Period A to Period B (see image below):
You will also see on the input menu a input for “Threshold” assessments. This simply modifies the threshold parameters for the technical readings. It is defaulted to 3, which means when two technical (for example Max Stochastics) are within +/- 3 of each other, the indicator will light these up as green to indicate similarities. They just clue the user visually to areas where there are similarities amongst the qualitative technical data.
Timeframes
This is best used on the daily timeframe. You can use it on the smaller timeframe but the processing time may take a bit longer. I personally like it for the Daily, Weekly and 4 hour charts.
And this is the indicator in a nutshell!
I will provide a tutorial video in the coming day on how to use it, so check back later!
As always, leave your comments/questions and suggestions below. I have been slowly modifying stuff based on user suggestions so please keep them coming but be patient as it does take some time and I am by no means a coder or expert on this stuff.
Safe trades to all!
Rate of DeviationThe Rate of Deviation indicator calculates and displays the amount the current price varies above or below the average price over Length bars. A deviation value greater than the base level indicates that the current price is higher than the price average while a deviation less than the base level indicates that the current price is lower than the price average.
StatBox📊 StatBox: A Comprehensive Trading Indicator for RSI, Volume Percent, and ADD 📈💼
Introducing StatBox, the ultimate trading indicator designed to provide traders with a powerful analytical toolset for making informed trading decisions. With StatBox, you gain access to real-time data on Relative Strength Index (RSI), Volume Percent, and ADD (Advance/Decline Differential). This dynamic combination of indicators empowers you to navigate the market with greater precision and confidence. 📊🔍
Key Features of StatBox:
1️⃣ RSI (Relative Strength Index): RSI is a widely recognized momentum oscillator that measures the speed and change of price movements. StatBox displays RSI as a numerical value, ranging from 0 to 100, allowing you to quickly assess whether a security is overbought or oversold. This information is invaluable for identifying potential reversal points and optimizing entry or exit strategies.
2️⃣ Volume Percent: StatBox provides a visual representation of the Volume Percent, which reflects the relative trading volume compared to a specified period. By monitoring volume dynamics, you gain insights into market sentiment and potential price trends. A higher volume percentage often indicates stronger market participation, suggesting increased interest in a particular security.
3️⃣ ADD (Advance/Decline Differential): ADD is a breadth indicator that calculates the difference between advancing (upward moving) and declining (downward moving) securities. StatBox presents ADD as a histogram, enabling you to assess the overall strength or weakness of the market. Positive values indicate bullish sentiment, while negative values suggest bearish sentiment. By tracking ADD, you can identify potential market reversals or confirm existing trends.
With StatBox, you can:
✅ Quickly gauge the overbought or oversold conditions of a security using RSI.
✅ Monitor volume dynamics to assess market sentiment and potential price trends.
✅ Analyze the breadth of the market and identify bullish or bearish signals with ADD.
✅ Make well-informed trading decisions based on a comprehensive view of multiple indicators.
StatBox provides a user-friendly interface, allowing you to seamlessly integrate it into your preferred trading platform or charting software. Its intuitive design and real-time data updates ensure you have the most accurate and up-to-date information at your fingertips.
Upgrade your trading arsenal and unlock the potential of RSI, Volume Percent, and ADD with StatBox. Experience the power of multiple indicators in a single comprehensive tool. Download StatBox today and gain a competitive edge in the dynamic world of trading! 🚀📈
Grid Spot Trading Algorithm V2 - The Quant ScienceGrid Spot Trading Algorithm V2 is the last grid trading algorithm made by our developer team.
Grid Spot Trading Algorithm V2 is a fixed 10-level grid trading algorithm. The grid is divided into an accumulation area (red) and a selling area (green).
In the accumulation area, the algorithm will place new buy orders, selling the long positions on the top of the grid.
BUYING AND SELLING LOGIC
The algorithm places up to 5 limit orders on the accumulation section of the grid, each time the price cross through the middle grid. Each single order uses 20% of the equity.
Positions are closed at the top of the grid by default, with the algorithm closing all orders at the first sell level. The exit level can be adjusted using the user interface, from the first level up to the fifth level above.
CONFIGURING THE ALGORITHM
1) Add it to the chart: Add the script to the current chart that you want to analyze.
2) Select the top of the grid: Confirm a price level with the mouse on which to fix the top of the grid.
3) Select the bottom of the grid: Confirm a price level with the mouse on which to fix the bottom of the grid.
4) Wait for the automatic creation of the grid.
USING THE ALGORITHM
Once the grid configuration process is completed, the algorithm will generate automatic backtesting.
You can add a stop loss that destroys the grid by setting the destruction price and activating the feature from the user interface. When the stop loss is activated, you can view it on the chart.
[MAD] Position starter & calculatorThe tool you're using is a financial instrument trading planner and analyzer.
Here is how to use it:
Trade Planning: You can plan your trade entries and exits, calculating potential profits, losses, and their ratio (P/L ratio).
You can define up to five target closing prices with varying volumes, which can be individually activated or deactivated (volume set to 0%).
Risk Management: There's a stop-loss function to calculate and limit potential losses.
Additionally, it includes a liquidation pre-calculation for adjustable leverages and position maintenance(subject to exchange variation).
Customization: You can customize the tool's appearance with five adjustable color schemes, light and dark.
-----------------
Initiation: This tool functions as an indicator.
To start, add it as an indicator.
Once added, you can close the indicator window.
Now wait, till you'll see a blue box at the bottom of the input window.
Parameter Input:
Enter your parameters (SL, box left, box right, TP1, TP2, TP3, TP4, TP5) in the direction of the desired trade.
Click from top to bottom for a short trade or bottom to top for a long trade.
Adjustment: If you want to move the box in the future, adjust the times in the indicator settings directly as click input is not yet platform-supported.
This tool functions as a ruler and doesn't offer alerts (for now).
Here is another examples of how to set up a Position-calculation but here for a short:
Have fun trading
Position_controlLibrary "Position_control"
This is a library for defining positions and working with them.
f_calculateLeverage(_Leverage, _maintenance, _value, _direction)
Calculate the leverage used in a trade.
@description This function calculates the leverage used in a trade, based on the value of the trade, the maintenance margin, and the direction of the trade.
Parameters:
_Leverage (float) : The leverage used in the trade, as a floating point number.
_maintenance (float) : The maintenance margin percentage, as a floating point number.
_value (float) : The value of the trade, as a floating point number.
_direction (string) : The direction of the trade, either "long" or "short".
Returns: The leverage used in the trade, as a floating point number.
f_calculate_PL(_Position, _max_TP, _Position_index, _show_profit, _i_decimals_contracts, _i_decimals_prercent)
Calculate the profit or loss for a given trade.
@description This function calculates the profit or loss for a given trade, based on the position type, maximum take profit, position index, and whether to show the profit as a percentage or a value.
Parameters:
_Position (t_Position_type ) : An array of position types for the trade.
_max_TP (int) : The maximum take profit for the trade, as an integer value.
_Position_index (int) : The index of the position in the array, as an integer value.
_show_profit (bool) : A boolean value indicating whether to show the profit as a percentage or a value.
_i_decimals_contracts (int)
_i_decimals_prercent (int)
Returns: The profit or loss for the trade, as a floating point number.
f_drawposition(_Position, _Parameters, _Position_index)
draws a position on the chart
@description via sending in a typo of Position this function is able to drawout Stoploss, Entrybox, Takeprofits and the required labels with information
Parameters:
_Position (t_Position_type ) : array of type t_Position_type containing the position information.
_Parameters (t_drawing_parameters)
_Position_index (int) : the index of the current position.
Returns: None but boxes / lines / labels on the chart itself
t_TP_Variant
Fields:
TP_Type (series__string)
TP_Parameter_1 (series__integer)
TP_Parameter_2 (series__integer)
TP_Parameter_3 (series__float)
TP_Parameter_4 (series__float)
t_TPs
Fields:
TP_Price (series__float)
TP_Lot (series__float)
TP_Variant (|t_TP_Variant|#OBJ)
TP_Active (series__bool)
t_SLs
Fields:
SL_Price (series__float)
SL_Lot (series__float)
SL_Active (series__bool)
t_Position_type
Fields:
Lot (series__float)
Leverage (series__float)
Maintenance (series__float)
Starttime (series__integer)
Entry_Start (series__float)
Stoptime (series__integer)
Entry_Stop (series__float)
Entryprice (series__float)
TPs (array__|t_TPs|#OBJ)
SLs (array__|t_SLs|#OBJ)
t_drawing_parameters
Fields:
ShowPos (series__bool)
ShowLIQ (series__bool)
A_Colors (array__color)
Prolong_lines (series__bool)
Str_fontsize (series__string)
Textshift (series__integer)
Decimals_contracts (series__integer)
Decimals_price (series__integer)
Decimals_percent (series__integer)
bartime (series__integer)
Metrics using Alternative Portfolio TheoryLibrary "APT_Metrics"
Portfolio metrics using alternative portfolio theory
metrics(init, cur, start, end, alpha)
Calculates APT metrics
Parameters:
init (float) : Starting Equity (strategy.initial)
cur (float)
start (int) : Start date (UNIX)
end (int) : End Date (UNIX)
alpha (float) : Confidence interval for DaR/CDaR. Defval = 0.05
Returns: Plots table with APT metrics
The metrics are shown in the bottom pane being applied to a buy-and-hold strategy.
PLEASE NOTE: This is the first draft of the library. Some calculations may be incorrect. If you spot any mistakes then please let me know and I will correct them as soon as possible. I am also open to suggestions on how to improve this.
At the moment this only works on the daily timeframe until I can find a way to universally calculate annualized volatility.
See inside Candles: Directionality %; Constituent Bars & GapsSee inside candles based on user-input LTF setting: get data on 'Directionality' of your candle; Gaps (total and Sum; UP and DOWN); Number of Bull or Bear constituent candles
//Features:
-DIRECTIONALITY: compare length of the 'zig-zag' random walk of lower time frame constituent candles, to the full height of the current candle. Resulting % I refer to as 'directionality'.
-GAPs: what i refer to as 'gaps' are also known as Volume imbalances: the gap between previous candles close and current candle's open (if there is one).
--Gaps total (up vs down gaps). Number of Up gaps printed above bar in green, down gaps printed below bar in red.
--Gaps Sum (total summed UP gap, total summed down gaps. Sum of Up gaps printed above bar in green, Sum of down gaps printed below bar in red.
-Candles Total: Numer of LTF up vs down candles within current timeframe candle. Number of up candles printed above bar in green, Number of down candles printed below bar in red.
//USAGE:
-Primary purpose in this was the Directionality aspect. Wanted to get a measure of how choppy vs how directional the internals of a candle were. Idea being that a candle with high % directionality (approaching 100) would imply trending conditions; while a candle which was large range and full bodies but had a low % directionality would imply the internals were back-and-forth and => rebalanced, potentially indicating price may not need to retrace back into it and rebalance further. All rather experimental, please treat it as such: have a play around with it.
-Number of gaps, Sums of up and down gaps, ratio of up and down constituent candles also intended to serve a similar purpose as the above.
-Set the input lower timeframe; this must obviously be lower then your current timeframe. You will significant differences in results depending on the ratio your timeframes (chart timeframe vs user-input timeframe).
//User Inputs:
-Lower timeframe input (setting child candle size within current chart parent candle).
-Choose function from the four listed above.
-typical formating options: Bull color/bear color txt for gaps functions.
-display % unit or not.
-display vertical or horizontal text.
-Set min / max directionality thresholds; and color code results.
-Toggle on/off 'hide results outside of threshold' to declutter the chart.
-choose label style.
//NOTES:
-Directionality thresholds can be set manually; Max and Min thresholds can be set to filter out 'non-extreme' readings.
-Note that directionality % can sometimes exceed 100%, in cases where price trends very strongly and gaps up continuously such that sum of constituent candles is less than total range of parent candle.
-Personally i like the idea of seeking bold, large-range, full bodied candles, with a lower than typical directionality %; indicating that a price move is both significant and it's already done it's rebalancing; I would see this as potentially favourable for continuation (obviously depending on context).
---- Showcase of the other functions beyond Directionality percentage ----
Candles Total (bull vs Bear). ES1! Hourly; ltf = 5min: Candles total: LTF up candles and LTF down candles making up the current HTF candle (constituent number of UP candles printed above in green, Down candles printed below in red):
Gaps SUM. SPX hourly, ltf = 5min. Sum of 'UP' gaps within candle printed above in green, sum of 'DOWN' gaps printed below in red:
Gaps TOTAL: SPX hourly, ltf = 1min. Simply the total of 'up' gaps vs 'down' gaps withing our candle; based on the user input constituent candles within:
SPX ES SpreadA very simple indicator to display the spread between ES and SPX. The table by default displays in the upper right corner of the chart. If you are on the chart for SPX, it will show the current price of ES, as well as the difference in points between the two. Similarly, if on the chart for ES, it will show the price for SPX as well as the difference in points between the two. The table does not appear at all if the chart symbol is anything other than ES or SPX. The specific symbols used can be defined by the user.
PSESS1 - Learn PineScript InputsThis is a script written exclusively for people who are trying to learn Pine Script.
PSESS stands for "Pine Script Educational Script Series" which is a series of scripts that helps Pine Script programmers in 2 ways:
1. Learn Pine Script at more depth by an interactive environment where they can immediately see the effects of any change in the pre-written code and also comparing different lines code having tiny differences so they can grasp the details.
2. Have this script open while coding in order to copy the line they find useful
Pine Script Library couldn't be used for this purpose since this script has educational aspect and needs to be executable individually.
This is Script 1 of PSESS and focuses on inputs in Pine Script.
The script is densly commented in order to make it understandable. here is the outline of the script:
1. Inputs that can be received through the indicator() function
2. 12 possible types of input
3. Input() function arguments: defval - title - tooltip - inline - group - confirm
4. The different display of tooltip when inputs are inline
5. Multiple price and time inputs (on single request or multiple requests)
6. What happens when title argument is not specified
7. References and key points from them
Expected VolatilityExpected Volatility
Hello and welcome to my first indicator! I'm publishing this indicator as free to use and modify because I think it's a great place to learn and I hope I can teach you something.
There are some terms which you need to understand before I begin explaining this indicator and what it does for you:
Daily Settlement - The price at which a market closes when the trading day closes (RTH or Regular Trading Hours close)
Standard Deviation - A measure in statistics that declares how far away a data point is from the mean when compared with all the data points before it to an extent
Now for the history behind this indicator:
Rule of 16. This goes back to the VIX, or S&P 500 volatility index. The idea behind the volatility index is to determine what magnitude of movement could be expected from the market the following day based on recent movement. The rule of 16 is an easier way to refer to the square root of the number of trading days in a year. There are 252 trading days in a year and the square root of 252 is approximately 15.87. We estimate it to be 16 because it's easier to talk about when it's easier to say and therefore easier to remember.
The relevance of this rule is that when the VIX is at 16, we can expect a market movement of 1% or so unless some special circumstances overrule this estimate. To get the expected market movement, we take 16 and divide by 16 and get 1, or 1%. If the VIX is trading at 24, we get 24/16 or 1.5 which is 1.5% movement. This indicator seeks to simplify the math and lay it out in a visual way to show the highest probability of range the market is expected to trade.
Thanks for taking the time to read my description, I hope you like my indicator.
Special thanks to my trading friends and coaches for helping me complete this indicator.
Manual PnL (Profit and Loss) % Tracker - spot long only
This is a manual profit and loss tracker. It takes the user's manual input of total cost and quantity, and then outputs a table on the bottom right of the chart showing the profit or loss %, average purchase price, gross profit or loss, and market value.
Instructions:
1. Double click the indicator title at the top left of the chart
2. Select the "Inputs" tab and click the empty field next to "Symbol" to enter the traded symbol+exchange. This entry MUST be the same as the chart you are on, for example BTCUSDT/BINANCE (indicator will not display otherwise)
3. Enter the Total Cost and Qty of shares/coins owned
4. Optional - change positive or negative colors
5. Optional - under the "Style" tab, change the color of the average price (AVG) line
Note that for the average price (AVG) line to be shown/hidden you must enable/disable "Indicator and financials labels" in the scales settings.
For crypto or other tickers that have prices in many decimal places I would suggest, for the sake of accuracy, adjusting the decimal places in the code so that for prices under $1 you will display more info.
For example let's say you purchase x number of crypto at a price of 0.031558 you should change the code displaying "0.00" on line 44 to "0.000000"
This will ensure that the output table and plotted line will calculate an average price with the same number of decimals.
Monte Carlo Price ProbabilitiesMonte Carlo simulations have been a popular tool in the world of finance, risk analysis, and decision making for decades. In this post, I will take you through the history of Monte Carlo simulations and explain how I implemented this powerful technique in Pine Script. This implementation can help traders and investors in various time frames to better understand the potential future price movements of financial instruments based on historical data.
History of Monte Carlo Simulations
The Monte Carlo method was named after the famous Monte Carlo Casino in Monaco, as the technique involves using random sampling to approximate solutions to mathematical problems. The method was first introduced by Stanislaw Ulam, a mathematician working on the Manhattan Project in the 1940s. Ulam realized that using random sampling could provide approximate solutions to complex problems that were otherwise difficult or impossible to solve analytically.
Over the years, Monte Carlo simulations have found applications in various fields, including physics, engineering, and finance. In the world of finance, the method has been used to model stock price movements, option pricing, portfolio optimization, and risk management.
Implementation in Pine
In my implementation of Monte Carlo simulations in Pine, I created a script that allows users to input several parameters such as the arbitrary price, number of simulations, number of steps into the future, and the start bar index. The start bar index is a crucial setting for running the script on lower time frames, as it helps to ensure that the script runs smoothly for a given symbol.
The script then calculates the log return of each bar and categorizes them into green (positive) or red (negative) moves. It uses these historical price movements to calculate the probabilities of future price movements for each step in the simulation.
The core of the Monte Carlo simulation lies in the `monte()` function, which generates random numbers to determine if the next price movement will be green or red, and then selects a move size based on its probability. The `sim()` function runs multiple simulations using the `monte()` function and stores the results in an array.
Finally, the script calculates the probability of the arbitrary price being reached in the future based on the results of the simulations. It also plots the probability on the chart, allowing users to visually assess the potential future price movements of the financial instrument.
Using the Monte Carlo Simulation
To use the Monte Carlo simulation in Pine, you need to input the desired parameters such as the arbitrary price, number of simulations, number of steps into the future, and the start bar index. For some symbols, you may need to set the start bar index to around 10k to ensure that the script runs smoothly.
Once you have input the parameters and run the script, you will see the probability of reaching the arbitrary price plotted on the chart. This can provide a valuable insight into the potential future price movements of the financial instrument based on historical data, helping you make more informed trading and investment decisions.
Conclusion
Monte Carlo simulations have a rich history and have proven to be a valuable tool in various fields, including finance. My implementation of Monte Carlo simulations in Pine allows traders and investors to better understand the potential future price movements of financial instruments in various time frames. By evaluating the probabilities of reaching specific price levels, users can make more informed decisions and better manage their risk.
Position TrackerEnter your purchase price & the quantity.
It'll display a line at that value, with a label indicating the current gain/loss
[MiV] Trading SessionHello, everyone!
Today I want to present my new script, which I hope will help not only me!
I'm sure that many people, like me, went through such a stage as "building their strategy". This is when you sit and test on the history how you would enter or exit a trade.
Recently I was doing the same thing and realized that my "tests" involve night time, when in reality I would be asleep and not trading! So I decided to create an indicator that would display my "working hours" so that the backtest I conduct would be as realistic as possible.
Also this indicator is able to display sessions of major exchanges and forex working hours, so it will be useful not only for cryptocurrency lovers.
In addition, we don't always trade every day and, for example, I don't trade on Sunday. That's why we added a feature that "turns off" the day and does not highlight it in color if you're not planning to trade on that day.
And finally, I added a notification of the beginning and end of the trading session. A small thing, but it may also be a useful feature for those who like to sit at the chart!
I will be glad to receive any comments and suggestions!
-----
Всем привет!
Хочу сегодня представить свой новый скрипт, который, надеюсь, поможет не только мне!
Уверен, что многие, как и я, проходили такой этап как "постройка своей стратегии". Это когда ты сидишь и тестируешь на истории то как бы ты входил или выходил из сделки.
Вот недавно я ровно также занимался этим и осознал, что мои "тесты" затрагивают и ночное время, когда в реальности я бы спал и не торговал! Поэтому я решил создать индикатор, который будет отображать мои "рабочие часы", чтобы бектест, который я провожу, был максимально реалистичным.
Также данный индикатор умеет отображать сессии крупных бирж и время работы форекса, так что полезным он будет не только для любителей криптовалюты.
Кроме того, мы же не всегда торгуем каждый день и например я не торгую в воскресенье. Поэтому добавлен функционал, который "выключает" день и не подсвечивает его цветом, если ты в этот день не планируешь торговать.
Ну и в заключении, добавил уведомление о начале и завершении торговой сессии. Мелочь, а тоже может быть полезной фичей для тех кто любит засесть за графиком!
Буду рад любым замечаниям и предложениям!
Gaussian Fisher Transform Price Reversals - FTRHello Traders !
Looking for better trading results ?
"This indicator shows you how to identify price reversals in a timely manner." John F. Ehlers
Introduction :
The Gaussian Fisher Transform Price Reversals indicator, dubbed FTR for short, is a stat based price reversal detection indicator inspired by and based on the work of the electrical engineer now private trader John F. Ehlers.
The Fisher Transform :
It is a common assumption that prices have a gaussian / normal probability density function(PDF), i.e. a sample of n close prices would be normally distributed if the probability of observing a price value say at any given standard deviation range is equal to that probability in the case of the normal distribution, e.g. 68% off all samples fell within one standard deviation around the mean, which is what we would expect if the data was normal.
However Price Action is not normally distributed and thus can not be conventionally interpreted in this way, Formally the Fisher Transform, transforms the distribution of bounded ranging price action (were price action takes values in a range from -1 to 1) into that of a normal distribution, alternatively it may be said the Fisher Transform changes the PDF of any waveform so that the transformed output has n approximately Gaussian PDF, It does so through the following equations. taken directly from the work of John F. Ehlers - Using The Fisher Transform
By substituting price data in the above formulas, bounded ranging price actions (over a given user defined period lookback - this determines the range price ranges in, see the Intermediate formula above) distribution is transformed to that in the normal case. This means when the input, the Intermediate ,(the Midpoint - see formula above) approaches either limit within the range the outputs are greatly amplified, this amplification accentuates /puts more weight on the larger deviations or limits within the range, conversely when price action is varying round the mean of the range the output is approximately equal to unity (the input is approximately equal to the input, the intermediate)
The inputs (Intermediates) are converted to normal outputs and the nonlinear Transfer of the Fisher Transform with varying senesitivity's (gammas) can be seen in the graph / image above. Although sensitivity adjustments are not currently available in this script (I forgot to add it) the outputs may be greatly amplified as gamma (the coefficient of the Fisher Transformation - see Fish equation) approaches 1. the purple line show this graphically, as a higher gamma leads to a greater amplification than in the standard case (the red line which is the standard fisher transformation, the black plot is the Fish with a gamma of 1, which is unity sensativity)
Reversal plots and Breakouts :
- Support lines are plotted with their corresponding Fish value when there is a crossover of the Fish and Fish SMA <= a given standard deviation of Fish
- Resistance lines are plotted with their corresponding Fish value when there is a crossunder of the Fish and Fish SMA >= a given standard deviation of Fish
- Reversals are these support and resistance line plots
Breakouts and Volume bars :
Breakouts cause the reversal lines to break (when the high/low is above the resistance/support), Breakouts are more "high quality" when they occur conditional on high volume, the highlighted bars represent volume standard deviations ranging from -3 to 3. When breakouts occure on high volume this may be a sign of the continutaion of the trend (reversals would signify the start of a new trend).
Hope you enjoy, Happy Trading !
(be sure to rocket the script if you liked it, this helps me know which of my scripts are the most useful)
BenfordsLawLibrary "BenfordsLaw"
Methods to deal with Benford's law which states that a distribution of first and higher order digits
of numerical strings has a characteristic pattern.
"Benford's law is an observation about the leading digits of the numbers found in real-world data sets.
Intuitively, one might expect that the leading digits of these numbers would be uniformly distributed so that
each of the digits from 1 to 9 is equally likely to appear. In fact, it is often the case that 1 occurs more
frequently than 2, 2 more frequently than 3, and so on. This observation is a simplified version of Benford's law.
More precisely, the law gives a prediction of the frequency of leading digits using base-10 logarithms that
predicts specific frequencies which decrease as the digits increase from 1 to 9." ~(2)
---
reference:
- 1: en.wikipedia.org
- 2: brilliant.org
- 4: github.com
cumsum_difference(a, b)
Calculate the cumulative sum difference of two arrays of same size.
Parameters:
a (float ) : `array` List of values.
b (float ) : `array` List of values.
Returns: List with CumSum Difference between arrays.
fractional_int(number)
Transform a floating number including its fractional part to integer form ex:. `1.2345 -> 12345`.
Parameters:
number (float) : `float` The number to transform.
Returns: Transformed number.
split_to_digits(number, reverse)
Transforms a integer number into a list of its digits.
Parameters:
number (int) : `int` Number to transform.
reverse (bool) : `bool` `default=true`, Reverse the order of the digits, if true, last will be first.
Returns: Transformed number digits list.
digit_in(number, digit)
Digit at index.
Parameters:
number (int) : `int` Number to parse.
digit (int) : `int` `default=0`, Index of digit.
Returns: Digit found at the index.
digits_from(data, dindex)
Process a list of `int` values and get the list of digits.
Parameters:
data (int ) : `array` List of numbers.
dindex (int) : `int` `default=0`, Index of digit.
Returns: List of digits at the index.
digit_counters(digits)
Score digits.
Parameters:
digits (int ) : `array` List of digits.
Returns: List of counters per digit (1-9).
digit_distribution(counters)
Calculates the frequency distribution based on counters provided.
Parameters:
counters (int ) : `array` List of counters, must have size(9).
Returns: Distribution of the frequency of the digits.
digit_p(digit)
Expected probability for digit according to Benford.
Parameters:
digit (int) : `int` Digit number reference in range `1 -> 9`.
Returns: Probability of digit according to Benford's law.
benfords_distribution()
Calculated Expected distribution per digit according to Benford's Law.
Returns: List with the expected distribution.
benfords_distribution_aprox()
Aproximate Expected distribution per digit according to Benford's Law.
Returns: List with the expected distribution.
test_benfords(digits, calculate_benfords)
Tests Benford's Law on provided list of digits.
Parameters:
digits (int ) : `array` List of digits.
calculate_benfords (bool)
Returns: Tuple with:
- Counters: Score of each digit.
- Sample distribution: Frequency for each digit.
- Expected distribution: Expected frequency according to Benford's.
- Cumulative Sum of difference:
to_table(digits, _text_color, _border_color, _frame_color)
Parameters:
digits (int )
_text_color (color)
_border_color (color)
_frame_color (color)
Recessions & crises shading (custom dates & stats)Shades your chart background to flag events such as crises or recessions, in similar fashion to what you see on FRED charts. The advantage of this indicator over others is that you can quickly input custom event dates as text in the menu to analyse their impact for your specific symbol. The script automatically labels, calculates and displays the peak to through percentage corrections on your current chart.
By default the indicator is configured to show the last 6 US recessions. If you have custom events which will benefit others, just paste the input string in the comments below so one can simply copy/paste in their indicator.
Example event input (No spaces allowed except for the label name. Enter dates as YYYY-MM-DD.)
2020-02-01,2020-03-31,COVID-19
2007-12-01,2009-05-31,Subprime mortgages
2001-03-01,2001-10-30,Dot-com bubble
1990-07-01,1991-03-01,Oil shock
1981-07-01,1982-11-01,US unemployment
1980-01-01,1980-07-01,Volker
1973-11-01,1975-03-01,OPEC
Trend Reversal Probability CalculatorThe "Trend Reversal Probability Calculator" is a TradingView indicator that calculates the probability of a trend reversal based on the crossover of multiple moving averages and the rate of change (ROC) of their slopes. This indicator is designed to help traders identify potential trend reversals by providing signals when the short-term moving averages start to slope in the opposite direction of the long-term moving average.
To use the indicator, simply add it to your TradingView chart and adjust the input parameters according to your preferences. The input parameters include the length of the moving averages, the ROC length (trend sensitivity), and the reversal sensitivity (signal percentage).
The indicator calculates the ROC of the moving averages and determines if the short-term moving averages are sloping in the opposite direction of the long-term moving average. The number of short-term moving averages that meet this condition is then counted, and the probability of a trend reversal is calculated based on the percentage of short-term moving averages that meet this condition.
When the probability of a trend reversal is high, a bullish or bearish signal is generated, depending on the direction of the reversal. The bullish signal is generated when the short-term moving averages start to slope upward, and the bearish signal is generated when the short-term moving averages start to slope downward.
Traders can use the "Trend Reversal Probability Calculator" to identify potential trend reversals and adjust their trading strategies accordingly. It is important to note that this indicator is not a guarantee of a trend reversal and should be used in conjunction with other technical analysis tools to make informed trading decisions.
relative performanceThis indicator is built to mesure the performance of a stock vs the index of choice. it is best use for the intraday session because it doesn't take gap into account when doing the calculation. This is how i made my math (using AAPL compared to SPY for simplicity)
(change AAPL / ATR AAPL) - (change SPY / ATR SPY) * beta factor * volume factor
change is calculated open to close for each candle instead of close to close. this is why gap does not affect the calculation
blue columns is an instant snap shot of the RP
red and green columns is the moving average of the blue columns
limit is the max value for the blue line when ploting them on the chart but doesn't affect the calculation
option:
indice: default with SPY but could use any stock
moving average choice: let you choose between EMA or SMA green and red columns
rolling average length : number of bar for the moving average
I made an auto adjust for the 5 min chart and the 2 min chart so you can swithc between both chart and have the same average (default value set to 6x 5min and 15x 2 min, giving you the average of the last 30min)
volume weighing let you choose if you want a volume factor or not. volume factor is only going to multiplie the result of the price move. it cannot move it from positive to negative.
this is the calculation
(volume AAPL / volume SMA AAPL) / (volume SPY / volume sma SPY)
meaning that a higher volume on the thicker compared to it's sma while having a lower volume on SPY will give you a big relative performance.
you can choose the number of bar in the average for the volume.
BETA factor work the same way that the volume factor does. you got to manualy enter your beta. default is set to 1.5
table
top line : blue square is you RP value (same has the blue columns bar) and your reference thicker
middle line : pourcentage move from the open (9:30 open) for your stock on the left and the reference on the right
bottom line : beta on the left and volume factor on the right
feel free to ask question or give modification idea!
Uptrend Downtrend Loopback Candle Identification LibThis library is for identifying uptrends and downtrends using a loopback candle analysis method. Which contains two functions:
uptrendLoopbackCandleIdentification() and downtrendLoopbackCandleIdentification() . These functions check if the current candle is part of an uptrend or downtrend, respectively, based on the specified lookback period.
The uptrendLoopbackCandleIdentification() takes two arguments: index , which is the index of the current bar, and lookbackPeriod , which is the number of previous candles to check for an uptrend. The function returns false if the index is less than the lookback period. Otherwise, it initializes a boolean variable isHigherHigh as true and loops through the previous candles. If any of the previous candles have a higher high than the current candle, isHigherHigh is set to false , and the loop breaks. Finally, the function returns the value of isHigherHigh .
The downtrendLoopbackCandleIdentification() takes the same arguments and returns false if the index is less than the lookback period. The function initializes a boolean variable isHigherLow as true and loops through the previous candles. If any of the previous candles have a higher low than the current candle, isHigherLow is set to false , and the loop breaks. The function returns the value of isHigherLow .
Endpointed SSA of Price [Loxx]The Endpointed SSA of Price: A Comprehensive Tool for Market Analysis and Decision-Making
The financial markets present sophisticated challenges for traders and investors as they navigate the complexities of market behavior. To effectively interpret and capitalize on these complexities, it is crucial to employ powerful analytical tools that can reveal hidden patterns and trends. One such tool is the Endpointed SSA of Price, which combines the strengths of Caterpillar Singular Spectrum Analysis, a sophisticated time series decomposition method, with insights from the fields of economics, artificial intelligence, and machine learning.
The Endpointed SSA of Price has its roots in the interdisciplinary fusion of mathematical techniques, economic understanding, and advancements in artificial intelligence. This unique combination allows for a versatile and reliable tool that can aid traders and investors in making informed decisions based on comprehensive market analysis.
The Endpointed SSA of Price is not only valuable for experienced traders but also serves as a useful resource for those new to the financial markets. By providing a deeper understanding of market forces, this innovative indicator equips users with the knowledge and confidence to better assess risks and opportunities in their financial pursuits.
█ Exploring Caterpillar SSA: Applications in AI, Machine Learning, and Finance
Caterpillar SSA (Singular Spectrum Analysis) is a non-parametric method for time series analysis and signal processing. It is based on a combination of principles from classical time series analysis, multivariate statistics, and the theory of random processes. The method was initially developed in the early 1990s by a group of Russian mathematicians, including Golyandina, Nekrutkin, and Zhigljavsky.
Background Information:
SSA is an advanced technique for decomposing time series data into a sum of interpretable components, such as trend, seasonality, and noise. This decomposition allows for a better understanding of the underlying structure of the data and facilitates forecasting, smoothing, and anomaly detection. Caterpillar SSA is a particular implementation of SSA that has proven to be computationally efficient and effective for handling large datasets.
Uses in AI and Machine Learning:
In recent years, Caterpillar SSA has found applications in various fields of artificial intelligence (AI) and machine learning. Some of these applications include:
1. Feature extraction: Caterpillar SSA can be used to extract meaningful features from time series data, which can then serve as inputs for machine learning models. These features can help improve the performance of various models, such as regression, classification, and clustering algorithms.
2. Dimensionality reduction: Caterpillar SSA can be employed as a dimensionality reduction technique, similar to Principal Component Analysis (PCA). It helps identify the most significant components of a high-dimensional dataset, reducing the computational complexity and mitigating the "curse of dimensionality" in machine learning tasks.
3. Anomaly detection: The decomposition of a time series into interpretable components through Caterpillar SSA can help in identifying unusual patterns or outliers in the data. Machine learning models trained on these decomposed components can detect anomalies more effectively, as the noise component is separated from the signal.
4. Forecasting: Caterpillar SSA has been used in combination with machine learning techniques, such as neural networks, to improve forecasting accuracy. By decomposing a time series into its underlying components, machine learning models can better capture the trends and seasonality in the data, resulting in more accurate predictions.
Application in Financial Markets and Economics:
Caterpillar SSA has been employed in various domains within financial markets and economics. Some notable applications include:
1. Stock price analysis: Caterpillar SSA can be used to analyze and forecast stock prices by decomposing them into trend, seasonal, and noise components. This decomposition can help traders and investors better understand market dynamics, detect potential turning points, and make more informed decisions.
2. Economic indicators: Caterpillar SSA has been used to analyze and forecast economic indicators, such as GDP, inflation, and unemployment rates. By decomposing these time series, researchers can better understand the underlying factors driving economic fluctuations and develop more accurate forecasting models.
3. Portfolio optimization: By applying Caterpillar SSA to financial time series data, portfolio managers can better understand the relationships between different assets and make more informed decisions regarding asset allocation and risk management.
Application in the Indicator:
In the given indicator, Caterpillar SSA is applied to a financial time series (price data) to smooth the series and detect significant trends or turning points. The method is used to decompose the price data into a set number of components, which are then combined to generate a smoothed signal. This signal can help traders and investors identify potential entry and exit points for their trades.
The indicator applies the Caterpillar SSA method by first constructing the trajectory matrix using the price data, then computing the singular value decomposition (SVD) of the matrix, and finally reconstructing the time series using a selected number of components. The reconstructed series serves as a smoothed version of the original price data, highlighting significant trends and turning points. The indicator can be customized by adjusting the lag, number of computations, and number of components used in the reconstruction process. By fine-tuning these parameters, traders and investors can optimize the indicator to better match their specific trading style and risk tolerance.
Caterpillar SSA is versatile and can be applied to various types of financial instruments, such as stocks, bonds, commodities, and currencies. It can also be combined with other technical analysis tools or indicators to create a comprehensive trading system. For example, a trader might use Caterpillar SSA to identify the primary trend in a market and then employ additional indicators, such as moving averages or RSI, to confirm the trend and generate trading signals.
In summary, Caterpillar SSA is a powerful time series analysis technique that has found applications in AI and machine learning, as well as financial markets and economics. By decomposing a time series into interpretable components, Caterpillar SSA enables better understanding of the underlying structure of the data, facilitating forecasting, smoothing, and anomaly detection. In the context of financial trading, the technique is used to analyze price data, detect significant trends or turning points, and inform trading decisions.
█ Input Parameters
This indicator takes several inputs that affect its signal output. These inputs can be classified into three categories: Basic Settings, UI Options, and Computation Parameters.
Source: This input represents the source of price data, which is typically the closing price of an asset. The user can select other price data, such as opening price, high price, or low price. The selected price data is then utilized in the Caterpillar SSA calculation process.
Lag: The lag input determines the window size used for the time series decomposition. A higher lag value implies that the SSA algorithm will consider a longer range of historical data when extracting the underlying trend and components. This parameter is crucial, as it directly impacts the resulting smoothed series and the quality of extracted components.
Number of Computations: This input, denoted as 'ncomp,' specifies the number of eigencomponents to be considered in the reconstruction of the time series. A smaller value results in a smoother output signal, while a higher value retains more details in the series, potentially capturing short-term fluctuations.
SSA Period Normalization: This input is used to normalize the SSA period, which adjusts the significance of each eigencomponent to the overall signal. It helps in making the algorithm adaptive to different timeframes and market conditions.
Number of Bars: This input specifies the number of bars to be processed by the algorithm. It controls the range of data used for calculations and directly affects the computation time and the output signal.
Number of Bars to Render: This input sets the number of bars to be plotted on the chart. A higher value slows down the computation but provides a more comprehensive view of the indicator's performance over a longer period. This value controls how far back the indicator is rendered.
Color bars: This boolean input determines whether the bars should be colored according to the signal's direction. If set to true, the bars are colored using the defined colors, which visually indicate the trend direction.
Show signals: This boolean input controls the display of buy and sell signals on the chart. If set to true, the indicator plots shapes (triangles) to represent long and short trade signals.
Static Computation Parameters:
The indicator also includes several internal parameters that affect the Caterpillar SSA algorithm, such as Maxncomp, MaxLag, and MaxArrayLength. These parameters set the maximum allowed values for the number of computations, the lag, and the array length, ensuring that the calculations remain within reasonable limits and do not consume excessive computational resources.
█ A Note on Endpionted, Non-repainting Indicators
An endpointed indicator is one that does not recalculate or repaint its past values based on new incoming data. In other words, the indicator's previous signals remain the same even as new price data is added. This is an important feature because it ensures that the signals generated by the indicator are reliable and accurate, even after the fact.
When an indicator is non-repainting or endpointed, it means that the trader can have confidence in the signals being generated, knowing that they will not change as new data comes in. This allows traders to make informed decisions based on historical signals, without the fear of the signals being invalidated in the future.
In the case of the Endpointed SSA of Price, this non-repainting property is particularly valuable because it allows traders to identify trend changes and reversals with a high degree of accuracy, which can be used to inform trading decisions. This can be especially important in volatile markets where quick decisions need to be made.