Vector2FunctionClipLibrary "Vector2FunctionClip"
Sutherland-Hodgman polygon clipping algorithm.
reference:
.
rosettacode.org
.
clip(source, reference)
Perform Clip operation on a vector with another.
Parameters:
source : array . Source polygon to be clipped.
reference : array . Reference polygon to clip source.
Returns: array.
在脚本中搜索"algo"
A New Adaptive Moving Average [CC]The New Adaptive Moving Average was created by Scott Cong (Stocks and Commodities Mar 2023) and his idea was to focus on the Adaptive Moving Average created by Perry Kaufman and to try to improve it by introducing a concept of effort vs results. In this case the effort would be the total range of the underlying price action since each bar is essentially a war of the bulls vs the bears. The result would be the total range of the close so we are looking for the highest close and lowest close in that same time period. This gives us an alpha that we can use to plug into the Kaufman Adaptive Moving Average algorithm which gives us a brand new indicator that can hug the price just enough to allow us to ride the stock up or down. I have color coded it to be darker colors when it is a strong signal and lighter colors when it is a normal signal. Buy when the line turns green and sell when it turns red.
Let me know if there are any other indicators you would like to see me publish!
Recursive Zigzag [Trendoscope]Here is an another outcome of Object Oriented Zigzag and Pattern Ecosystem of Libraries.
We already have another implementation of recursive zigzag which makes use of earlier library rzigzag . Here in this example, we make use of similar logic but leverage the new type and method based Zigzag system libraries to derive the indicator.
🎲 Design Overview
Similar to Recursive Auto Pitchfork, here too the indicator code is around 50 lines. Whereas most of the heavy lifting is done by the libraries.
🎲 Base Libraries
Base libraries are those which does not have any dependency. They form basic structures which are later used in other libraries. These libraries need to be crafted carefully so that minimal updates are done later on. Any updates on these libraries will impact all the dependent libraries and scripts.
🎯 Drawing
DrawingTypes - Defines basic drawing types Point, Line, Label, Box, Linefill and related property types.
DrawingMethods - All the methods or functionality surrounding Basic types are defined here.
🎲 Layer 1 Libraries
These are the libraries which has direct dependency on base libraries.
🎯 Zigzag
ZigzagTypes - Types required for defining Zigzag and Divergence
ZigzagMethods - Methods associated with Zigzag Type definitions.
🎲Indicator
Indicator draws zigzags based on given length. And then recursively derives next level zigzags based on previous levels. As per the utility, indicator is useful in several ways
Visualising price structure based on zigzag pivots - which in turn can help visualise patterns.
Ability to add any oscillator makes it easy to spot divergences with choice of indicators.
Programmers can use the derived values to build complex algorithms such as automatic pattern recognition.
🎯 Settings
Settings are explained via tooltips. These are very much straight forward and directly related to zigzag, oscillators and divergence.
BE - Golden Cross Crude KeyTraders, i have been observing crude oil for about 3 months now and somehow I can see that crude is respecting 42 days Moving average and crosses have created massive spikes most of the time.
However you need to be mindful of the time to trade and timeframe since not all crosses creates spikes.
Note: I have been testing on a 15min timeframe.
Keeping this in mind, this indicator is a automated solution which takes trade entries on crosses plus buffer and exits based on the specified Sl type.
Enjoy!
DISCLAIMER: No sharing, copying, reselling, modifying, or any other forms of use are authorized for our documents, script / strategy, and the information published with them. This informational planning script / strategy is strictly for individual use and educational purposes only. This is not financial or investment advice. Investments are always made at your own risk and are based on your personal judgement. I am not responsible for any losses you may incur. Please invest wisely.
Happy to receive suggestions and feedback in order to improve the performance of the indicator better.
ICT MacrosThis script allows traders to visualize the range of time when a macro (an automated series of instructions/trades from large fund traders, executed by an algorithm) will likely occur in the market. It does this by drawing vertical lines and labels on the chart at these specific times:
(Macro Open) - 9:50 AM EST
(Macro Close) - 10:10 AM EST
(Macro Open) - 10:50 AM EST
(Macro Close) - 11:10 AM EST
(Macro Open) - 1:10 PM EST
(Macro Close) - 1:40 PM EST
(Macro Open) - 3:15 PM EST
(Macro Close) - 3:45 PM EST
The theory behind the use of these macros - is that the market will either seek buy side or sell side liquidity, or seek to rebalance price at a point of interest in between the open and close of the macro. Traders who follow this theory can use that information to anticipate how price might behave.
When a macro occurs, the script draws a vertical line on the chart using a dotted line style with a user-defined color. Additionally, a label is placed above the line to indicate whether it is a Macro Open or Macro Close event.
To preserve space, the labels are abbreviated on chart - "Macro Open" (M.O.) and "Macro Close" (M.C.) for both the morning and afternoon trading sessions. The labels may be turned on/off by the user.
The script also includes alerts that can notify traders when a macro occurs. These alerts can be set to go off once per bar close, and the alert message indicates the specific macro type and time.
This script is entirely open-source, meaning that traders can read the code and modify it as needed. Credit to the foundation of this script goes to TradingView user @rickyzcarroll for his open source Strat Assistant Hour Flip script. Important changes include the specific time changes and alert function.
Investments/swing trading strategy for different assetsStop worrying about catching the lowest price, it's almost impossible!: with this trend-following strategy and protection from bearish phases, you will know how to enter the market properly to obtain benefits in the long term.
Backtesting context: 1899-11-01 to 2023-02-16 of SPX by Tvc. Commissions: 0.05% for each entry, 0.05% for each exit. Risk per trade: 2.5% of the total account
For this strategy, 5 indicators are used:
One Ema of 200 periods
Atr Stop loss indicator from Gatherio
Squeeze momentum indicator from LazyBear
Moving average convergence/divergence or Macd
Relative strength index or Rsi
Trade conditions:
There are three type of entries, one of them depends if we want to trade against a bearish trend or not.
---If we keep Against trend option deactivated, the rules for two type of entries are:---
First type of entry:
With the next rules, we will be able to entry in a pull back situation:
Squeeze momentum is under 0 line (red)
Close is above 200 Ema and close is higher than the past close
Histogram from macd is under 0 line and is higher than the past one
Once these rules are met, we enter into a buy position. Stop loss will be determined by atr stop loss (white point) and break even(blue point) by a risk/reward ratio of 1:1.
For closing this position: Squeeze momentum crosses over 0 and, until squeeze momentum crosses under 0, we close the position. Otherwise, we would have closed the position due to break even or stop loss.
Second type of entry:
With the next rules, we will not lose a possible bullish movement:
Close is above 200 Ema
Squeeze momentum crosses under 0 line
Once these rules are met, we enter into a buy position. Stop loss will be determined by atr stop loss (white point) and break even(blue point) by a risk/reward ratio of 1:1.
Like in the past type of entry, for closing this position: Squeeze momentum crosses over 0 and, until squeeze momentum crosses under 0, we close the position. Otherwise, we would have closed the position due to break even or stop loss.
---If we keep Against trend option activated, the rules are the same as the ones above, but with one more type of entry. This is more useful in weekly timeframes, but could also be used in daily time frame:---
Third type of entry:
Close is under 200 Ema
Squeeze momentum crosses under 0 line
Once these rules are met, we enter into a buy position. Stop loss will be determined by atr stop loss (white point) and break even(blue point) by a risk/reward ratio of 1:1.
Like in the past type of entries, for closing this position: Squeeze momentum crosses over 0 and, until squeeze momentum crosses under 0, we close the position. Otherwise, we would have closed the position due to break even or stop loss.
Risk management
For calculating the amount of the position you will use just a small percent of your initial capital for the strategy and you will use the atr stop loss for this.
Example: You have 1000 usd and you just want to risk 2,5% of your account, there is a buy signal at price of 4,000 usd. The stop loss price from atr stop loss is 3,900. You calculate the distance in percent between 4,000 and 3,900. In this case, that distance would be of 2.50%. Then, you calculate your position by this way: (initial or current capital * risk per trade of your account) / (stop loss distance).
Using these values on the formula: (1000*2,5%)/(2,5%) = 1000usd. It means, you have to use 1000 usd for risking 2.5% of your account.
We will use this risk management for applying compound interest.
In settings, with position amount calculator, you can enter the amount in usd of your account and the amount in percentage for risking per trade of the account. You will see this value in green color in the upper left corner that shows the amount in usd to use for risking the specific percentage of your account.
Script functions
Inside of settings, you will find some utilities for display atr stop loss, break evens, positions, signals, indicators, etc.
You will find the settings for risk management at the end of the script if you want to change something. But rebember, do not change values from indicators, the idea is to not over optimize the strategy.
If you want to change the initial capital for backtest the strategy, go to properties, and also enter the commisions of your exchange and slippage for more realistic results.
If you activate break even using rsi, when rsi crosses under overbought zone break even will be activated. This can work in some assets.
---Important: In risk managment you can find an option called "Use leverage ?", activate this if you want to backtest using leverage, which means that in case of not having enough money for risking the % determined by you of your account using your initial capital, you will use leverage for using the enough amount for risking that % of your acount in a buy position. Otherwise, the amount will be limited by your initial/current capital---
Some things to consider
USE UNDER YOUR OWN RISK. PAST RESULTS DO NOT REPRESENT THE FUTURE.
DEPENDING OF % ACCOUNT RISK PER TRADE, YOU COULD REQUIRE LEVERAGE FOR OPEN SOME POSITIONS, SO PLEASE, BE CAREFULL AND USE CORRECTLY THE RISK MANAGEMENT
Do not forget to change commissions and other parameters related with back testing results!
Some assets and timeframes where the strategy has also worked:
BTCUSD : 4H, 1D, W
SPX (US500) : 4H, 1D, W
GOLD : 1D, W
SILVER : 1D, W
ETHUSD : 4H, 1D
DXY : 1D
AAPL : 4H, 1D, W
AMZN : 4H, 1D, W
META : 4H, 1D, W
(and others stocks)
BANKNIFTY : 4H, 1D, W
DAX : 1D, W
RUT : 1D, W
HSI : 1D, W
NI225 : 1D, W
USDCOP : 1D, W
Recursive Auto-Pitchfork [Trendoscope]"Say Hi" to object oriented programming with Pinescript using types and methods. This is the beginning of new era of Pinescript where we are moving from isolated scripts containing indicator and strategies to whole ecosystem of Object Oriented Programming with libraries of highly reusable components. Those who are familiar with programming would have already realised how big these improvements are and what it brings to the table.
With this script, I am not just providing an indicator for traders but also an introduction for programmers on how to design and build object oriented components in Pinescript using types and methods. Big thanks to Tradingview and Pine development team for making this happen. We look forward for many such gifts in the future :)
🎲 Architecture
As mentioned before, we are not just building an indicator here. But, an ecosystem of components. Using Types and Methods we can visualise libraries as Classes. Thus, we can build an ecosystem of libraries in layered approach to enhance effective code reusability.
Generic architecture can be visualised as below
Coming to the specific case of Auto Pitchfork indicator, the indicator code is less than 50 lines for logic and around 100 lines of inputs. But, most of the heavy-lifting is done by the libraries underneath. Here is a snapshot of related libraries and how they are connected.
All libraries are divided into two portions.
Types - Contains only type definitions
Methods - Contains only method definitions related to the types defined in the Types library
Together, these libraries can be visualised as Class. Methods are defined in such a way all exported methods are related to Types and no other functions or features are defined. If we need further functionality which does not depend on the types, we need to do this via some other library and use them here. Similarly, we should not define any methods related to these types in other libraries.
Reason for splitting the libraries to types and methods is to enable updating methods without disturbing types. Since libraries create interdependencies due to versioning, it is best if we do less updates on the type definitions. Splitting the two enables adding more features while keeping the type definition version intact.
🎲 Base Libraries
Base libraries are those which does not have any dependency. They form basic structures which are later used in other libraries. These libraries need to be crafted carefully so that minimal updates are done later on. Any updates on these libraries will impact all the dependent libraries and scripts.
🎯 Drawing
DrawingTypes - Defines basic drawing types Point, Line, Label, Box, Linefill and related property types.
DrawingMethods - All the methods or functionality surrounding Basic types are defined here.
🎲 Layer 1 Libraries
These are the libraries which has direct dependency on base libraries.
🎯 Zigzag
ZigzagTypes - Types required for defining Zigzag and Divergence
ZigzagMethods - Methods associated with Zigzag Type definitions.
🎯Pitchfork
PitchforkTypes - Basic and Drawing Types for Pitchfork objects
PitchforkMethods - Methods associated with Pitchfork type definitions
🎲 Indicator and Settings
Indicator draws pitchfork based on recursive zigzag configurations. Recursive zigzag is derived with following logic:
Base level zigzag is calculated with regular zigzag algorithm with given length and depth
Next level zigzag is calculated based on base zigzag. And we recursively calculate higher level zigzags until we are left with 4 or less pivots or when no further reduction is possible
On every level of zigzag, we then check the last 3 pivots and draw pitchfork based on the retracement ratio.
Indicator settings are summarised in the tooltips and are as below.
Finally, big thanks to my partner @CryptoArch_ for bringing up the topic of pitchfork for our next development.
Dark Energy Divergence OscillatorThe Dark Energy Divergence Oscillator (DEDO)
What makes The Universe grow at an accelerating pace?
Dark Energy.
What makes The Economy grow at an accelerating pace?
Debt.
Debt is the Dark Energy of The Economy.
I pronounce DEDO "Deed-oh", but variations are fine with me.
Note: The Pine Script version of DEDO is improved from the original formula, which used a constant all-time high calculation in the normalization factor. This was technically not as accurate for calculating liquidity pressure in historical data because it meant that historical prices were being tested against future liquidity factors. Now using Pine, the functions can be normalized for the bar at the time of calculation, so the liquidity factors are normalized per candle, not across the entire series, which feels like an improvement to me.
Thought Process:
It's all about the liquidity. What I started with is a correlation between major stock indices such as SPX and WRESBAL , a balance sheet metric on FRED
After September 2008, when QE was initiated, many asset valuations started to follow more closely with liquidity factors. This led me to create a function that could combine asset prices and liquidity in WRESBAL , in order to calculate their divergence and chart the signal in TradingView.
The original formula:
First, we don't want "non-QE" data. we only want data for the market affected by QE .
So, find SPX on the day of pre-QE: 1255.08 and subtract that from the 2022 top 4818.62 = 3563.54
With this post-QE SPX range, now you can normalize the price level simply by dividing by the range = ( SPX -1255.08)/3563.54)
Normalization produces values from 0 to 1 so that they can be compared with other normalized figures.
In order to test the 0 to 1 normalized SPX range measure against the liquidity number, WRESBAL , it's the same idea: normalize it using the max as the denominator and you get a 0 to 1 liquidity index:
( WRESBAL /4276000000000)
Subtract one from the other to get the divergence:
(( WRESBAL /4276000000000)-(( SPX -1255.08)/3563.54))*10
x10 to reduce decimal places, but this option is configurable in DEDO's input settings tab.
Positive values indicate there's ample liquidity to hold up price or even create bullish momentum in some cases. Negative values mean price levels are potentially extended beyond what liquidity levels can support.
Note: many viewers of the charts on social media wanted the values to go down in alignment with price moving down, so inverting the chart is what I do with Option + I. I like the fact that negative values represent a deficit in liquidity to hold up price but that's just me.
Now with Pine Script and some help from other liquidity focused accounts on TradingView , I was able to derive a script that includes central bank liquidity and Reverse Repo liquidity drain, all in one algorithm, with adjustable settings.
Central bank assets included in this version:
-JPY (Japan)
-CNY (China)
-UK (British Pound)
-SNB (Swiss National Bank)
-ECB (European Central Bank )
Central Bank assets can be adjusted to an allocation % so that the formula is adjusted for the market cap of the asset.
A handy table in the lower right corner displays useful information about the asset market cap, and percentage it represents in the liquidity pool.
Reverse repo soak is also an optional addition in the Input settings using the RRPONTSYD value from FRED. This value is subtracted from global liquidity used to determine divergence since it is swept away from markets when residing in the Fed's reverse repo facility.
There is an option to draw a line at the Zero bound. This provides a convenience so that the line doesn't keep having to be redrawn on every chart. The normalized equation produces a value that should oscillate around zero, as price/valuation grows past liquidity support, falls under it, and repeats in cycles.
Spoofing Detector with VPOC [CHE]"We're keeping an eye on the market makers, zooming in for a closer look."
Spoofing and Volume Point of Control (VPOC) are terms used in the context of market manipulation and market analysis in financial markets.
A spoofing detector is a tool developed to detect the spoofing of orders. Spoofing refers to a practice where a market participant places large orders to deceive other market participants and influence the price of a stock. These large orders, however, are not executed but cancelled shortly after, creating a false demand for a specific stock and influencing the price. A spoofing detector can use algorithms to detect and report these practices to maintain the integrity of the market.
The Volume Point of Control (VPOC) is a concept in technical analysis aimed at identifying the key price level at which a stock was bought and sold. VPOC is calculated by analyzing the volume data of a stock and determining the price level at which the largest volume was traded for a specific period. This price level can serve as an indicator of the current market trend and market interest in a specific stock.
There is a substantive connection between a spoofing detector and VPOC because both tools can be used to gain a better understanding of the stock markets and detect potential forms of market manipulation. For example, VPOC can be used as an indicator of potential market manipulation when an abnormal distribution of trading volume is observed at a specific price level. A spoofing detector can then be used to detect and report these activities.
Pine Script Indicator Analysis:
This is a Pine Script code for a spoofing detector and volume point of control (VPOC) indicator. The purpose of the indicator is to detect and highlight potential spoofing activities in the market, as well as to plot the volume point of control on the chart.
Inputs:
Median Lookback: This input defines the length of the median calculation, with a default value of 25.
Range To Edges Threshold: This input sets a threshold value for the range to edges calculation, with a default value of 200.
Multiplier 1: This input sets a multiplier value to be used in the average true range calculation, with a default value of 0.8.
Multipler 2: This input sets a multiplier value to be used in the average true range calculation, with a default value of 2.0.
Multipler 3: This input sets a multiplier value to be used in the average true range calculation, with a default value of 3.0.
Variables:
y, x, ds, os: These are arrays and a variable used for the first part of the spoofing detection process.
y1, x1, ds1, os1: These are arrays and a variable used for the second part of the spoofing detection process.
y2, x2, ds2, os2: These are arrays and a variable used for the third part of the spoofing detection process.
Calculation:
The code starts by defining some variables, such as the bar index (n), the close price (src), and the average true range (atr) with different multipliers.
Next, the median of the close price is calculated over the lookback period specified by the "Median Lookback" input.
Then, the difference between the current median and the previous median is calculated, and the value is compared with the average true range with different multipliers to determine the state of the market (up, down, or unchanged).
The code then checks if the state has changed from the previous bar, and if so, the code performs a spoofing detection calculation.
The spoofing detection calculation involves determining the range between the first and last bar in the median calculation, and dividing it by the sum of the absolute differences calculated earlier. If the result is below the "Range To Edges Threshold" input, the code plots a line and a label on the chart indicating a potential spoofing activity.
The process is repeated for each of the three parts of the spoofing detection process.
VPOC:
The VPOC code is used to calculate the Volume Point of Control (VPOC) on a chart. The VPOC is the price level with the highest volume over a specified lookback period. The script contains several functions and inputs that allow the user to customize the calculation.
Inputs:
i_source: This input allows the user to specify the source for the VPOC price calculation. The options are the close price of the bar.
i_vpocThreshold: This input allows the user to set the threshold percentage for the VPOC highlight.
Functions:
timeStep_translate(): This function returns a string representing the time step of the lower time frame based on the current time frame of the chart.
ltfStats(): This function returns an array of the source and volume of the lower time frame.
ltfSrc, ltfVolume: This line requests the lower time frame data using the request.security_lower_tf function, with the lower time frame step calculated by the timeStep_translate() function.
maxVolume and indexOfMaxVolume: These variables store the maximum volume value and its corresponding index in the ltfVolume array.
maxVol: This variable stores the source value corresponding to the maximum volume.
vpocThresholdMet: This variable is a boolean that is true when the volume at the maximum volume price level is greater than or equal to the threshold percentage of the total volume.
vpocColor: This variable stores the color for the VPOC plot.
vh: This variable stores the highest volume in the lookback period.
plotshape(): This function plots the VPOC on the chart. The shape will be plotted only if the volume is greater than the specified threshold percentage of the highest volume in the lookback period. The shape will be labeled with the text "VC".
Overall, this script calculates the VPOC for a chart by aggregating volume data from a lower time frame and plotting a shape at the price level with the highest volume. The user can specify the source for the VPOC calculation and the threshold percentage for the VPOC highlight.
Important: VPOC shows everything in real time as a leading indicator, the triple spoofing detector is trailing
Best regards
Chervolino
[blackcat] L1 Chop ZonesLevel: 1
Background
I was inspired by NILX's "Tool: Chop & Trade Zones". This can used as an element for trading system control.
Function
I use my own customized algorithm to replace that core of NILX one, which is targetting to provide smoother and trend for chop and trend judgement.
Since it is quite differnt now but an oscillator within range of 0~100. The pro is it can use the contstant threshold values for all time frames and all trading pairs now.
Remarks
Feedbacks are appreciated.
Any Oscillator Underlay [TTF]We are proud to release a new indicator that has been a while in the making - the Any Oscillator Underlay (AOU) !
Note: There is a lot to discuss regarding this indicator, including its intent and some of how it operates, so please be sure to read this entire description before using this indicator to help ensure you understand both the intent and some limitations with this tool.
Our intent for building this indicator was to accomplish the following:
Combine all of the oscillators that we like to use into a single indicator
Take up a bit less screen space for the underlay indicators for strategies that utilize multiple oscillators
Provide a tool for newer traders to be able to leverage multiple oscillators in a single indicator
Features:
Includes 8 separate, fully-functional indicators combined into one
Ability to easily enable/disable and configure each included indicator independently
Clearly named plots to support user customization of color and styling, as well as manual creation of alerts
Ability to customize sub-indicator title position and color
Ability to customize sub-indicator divider lines style and color
Indicators that are included in this initial release:
TSI
2x RSIs (dubbed the Twin RSI )
Stochastic RSI
Stochastic
Ultimate Oscillator
Awesome Oscillator
MACD
Outback RSI (Color-coding only)
Quick note on OB/OS:
Before we get into covering each included indicator, we first need to cover a core concept for how we're defining OB and OS levels. To help illustrate this, we will use the TSI as an example.
The TSI by default has a mid-point of 0 and a range of -100 to 100. As a result, a common practice is to place lines on the -30 and +30 levels to represent OS and OB zones, respectively. Most people tend to view these levels as distance from the edges/outer bounds or as absolute levels, but we feel a more way to frame the OB/OS concept is to instead define it as distance ("offset") from the mid-line. In keeping with the -30 and +30 levels in our example, the offset in this case would be "30".
Taking this a step further, let's say we decided we wanted an offset of 25. Since the mid-point is 0, we'd then calculate the OB level as 0 + 25 (+25), and the OS level as 0 - 25 (-25).
Now that we've covered the concept of how we approach defining OB and OS levels (based on offset/distance from the mid-line), and since we did apply some transformations, rescaling, and/or repositioning to all of the indicators noted above, we are going to discuss each component indicator to detail both how it was modified from the original to fit the stacked-indicator model, as well as the various major components that the indicator contains.
TSI:
This indicator contains the following major elements:
TSI and TSI Signal Line
Color-coded fill for the TSI/TSI Signal lines
Moving Average for the TSI
TSI Histogram
Mid-line and OB/OS lines
Default TSI fill color coding:
Green : TSI is above the signal line
Red : TSI is below the signal line
Note: The TSI traditionally has a range of -100 to +100 with a mid-point of 0 (range of 200). To fit into our stacking model, we first shrunk the range to 100 (-50 to +50 - cut it in half), then repositioned it to have a mid-point of 50. Since this is the "bottom" of our indicator-stack, no additional repositioning is necessary.
Twin RSI:
This indicator contains the following major elements:
Fast RSI (useful if you want to leverage 2x RSIs as it makes it easier to see the overlaps and crosses - can be disabled if desired)
Slow RSI (primary RSI)
Color-coded fill for the Fast/Slow RSI lines (if Fast RSI is enabled and configured)
Moving Average for the Slow RSI
Mid-line and OB/OS lines
Default Twin RSI fill color coding:
Dark Red : Fast RSI below Slow RSI and Slow RSI below Slow RSI MA
Light Red : Fast RSI below Slow RSI and Slow RSI above Slow RSI MA
Dark Green : Fast RSI above Slow RSI and Slow RSI below Slow RSI MA
Light Green : Fast RSI above Slow RSI and Slow RSI above Slow RSI MA
Note: The RSI naturally has a range of 0 to 100 with a mid-point of 50, so no rescaling or transformation is done on this indicator. The only manipulation done is to properly position it in the indicator-stack based on which other indicators are also enabled.
Stochastic and Stochastic RSI:
These indicators contain the following major elements:
Configurable lengths for the RSI (for the Stochastic RSI only), K, and D values
Configurable base price source
Mid-line and OB/OS lines
Note: The Stochastic and Stochastic RSI both have a normal range of 0 to 100 with a mid-point of 50, so no rescaling or transformations are done on either of these indicators. The only manipulation done is to properly position it in the indicator-stack based on which other indicators are also enabled.
Ultimate Oscillator (UO):
This indicator contains the following major elements:
Configurable lengths for the Fast, Middle, and Slow BP/TR components
Mid-line and OB/OS lines
Moving Average for the UO
Color-coded fill for the UO/UO MA lines (if UO MA is enabled and configured)
Default UO fill color coding:
Green : UO is above the moving average line
Red : UO is below the moving average line
Note: The UO naturally has a range of 0 to 100 with a mid-point of 50, so no rescaling or transformation is done on this indicator. The only manipulation done is to properly position it in the indicator-stack based on which other indicators are also enabled.
Awesome Oscillator (AO):
This indicator contains the following major elements:
Configurable lengths for the Fast and Slow moving averages used in the AO calculation
Configurable price source for the moving averages used in the AO calculation
Mid-line
Option to display the AO as a line or pseudo-histogram
Moving Average for the AO
Color-coded fill for the AO/AO MA lines (if AO MA is enabled and configured)
Default AO fill color coding (Note: Fill was disabled in the image above to improve clarity):
Green : AO is above the moving average line
Red : AO is below the moving average line
Note: The AO is technically has an infinite (unbound) range - -∞ to ∞ - and the effective range is bound to the underlying security price (e.g. BTC will have a wider range than SP500, and SP500 will have a wider range than EUR/USD). We employed some special techniques to rescale this indicator into our desired range of 100 (-50 to 50), and then repositioned it to have a midpoint of 50 (range of 0 to 100) to meet the constraints of our stacking model. We then do one final repositioning to place it in the correct position the indicator-stack based on which other indicators are also enabled. For more details on how we accomplished this, read our section "Binding Infinity" below.
MACD:
This indicator contains the following major elements:
Configurable lengths for the Fast and Slow moving averages used in the MACD calculation
Configurable price source for the moving averages used in the MACD calculation
Configurable length and calculation method for the MACD Signal Line calculation
Mid-line
Note: Like the AO, the MACD also technically has an infinite (unbound) range. We employed the same principles here as we did with the AO to rescale and reposition this indicator as well. For more details on how we accomplished this, read our section "Binding Infinity" below.
Outback RSI (ORSI):
This is a stripped-down version of the Outback RSI indicator (linked above) that only includes the color-coding background (suffice it to say that it was not technically feasible to attempt to rescale the other components in a way that could consistently be clearly seen on-chart). As this component is a bit of a niche/special-purpose sub-indicator, it is disabled by default, and we suggest it remain disabled unless you have some pre-defined strategy that leverages the color-coding element of the Outback RSI that you wish to use.
Binding Infinity - How We Incorporated the AO and MACD (Warning - Math Talk Ahead!)
Note: This applies only to the AO and MACD at time of original publication. If any other indicators are added in the future that also fall into the category of "binding an infinite-range oscillator", we will make that clear in the release notes when that new addition is published.
To help set the stage for this discussion, it's important to note that the broader challenge of "equalizing inputs" is nothing new. In fact, it's a key element in many of the most popular fields of data science, such as AI and Machine Learning. They need to take a diverse set of inputs with a wide variety of ranges and seemingly-random inputs (referred to as "features"), and build a mathematical or computational model in order to work. But, when the raw inputs can vary significantly from one another, there is an inherent need to do some pre-processing to those inputs so that one doesn't overwhelm another simply due to the difference in raw values between them. This is where feature scaling comes into play.
With this in mind, we implemented 2 of the most common methods of Feature Scaling - Min-Max Normalization (which we call "Normalization" in our settings), and Z-Score Normalization (which we call "Standardization" in our settings). Let's take a look at each of those methods as they have been implemented in this script.
Min-Max Normalization (Normalization)
This is one of the most common - and most basic - methods of feature scaling. The basic formula is: y = (x - min)/(max - min) - where x is the current data sample, min is the lowest value in the dataset, and max is the highest value in the dataset. In this transformation, the max would evaluate to 1, and the min would evaluate to 0, and any value in between the min and the max would evaluate somewhere between 0 and 1.
The key benefits of this method are:
It can be used to transform datasets of any range into a new dataset with a consistent and known range (0 to 1).
It has no dependency on the "shape" of the raw input dataset (i.e. does not assume the input dataset can be approximated to a normal distribution).
But there are a couple of "gotchas" with this technique...
First, it assumes the input dataset is complete, or an accurate representation of the population via random sampling. While in most situations this is a valid assumption, in trading indicators we don't really have that luxury as we're often limited in what sample data we can access (i.e. number of historical bars available).
Second, this method is highly sensitive to outliers. Since the crux of this transformation is based on the max-min to define the initial range, a single significant outlier can result in skewing the post-transformation dataset (i.e. major price movement as a reaction to a significant news event).
You can potentially mitigate those 2 "gotchas" by using a mechanism or technique to find and discard outliers (e.g. calculate the mean and standard deviation of the input dataset and discard any raw values more than 5 standard deviations from the mean), but if your most recent datapoint is an "outlier" as defined by that algorithm, processing it using the "scrubbed" dataset would result in that new datapoint being outside the intended range of 0 to 1 (e.g. if the new datapoint is greater than the "scrubbed" max, it's post-transformation value would be greater than 1). Even though this is a bit of an edge-case scenario, it is still sure to happen in live markets processing live data, so it's not an ideal solution in our opinion (which is why we chose not to attempt to discard outliers in this manner).
Z-Score Normalization (Standardization)
This method of rescaling is a bit more complex than the Min-Max Normalization method noted above, but it is also a widely used process. The basic formula is: y = (x – μ) / σ - where x is the current data sample, μ is the mean (average) of the input dataset, and σ is the standard deviation of the input dataset. While this transformation still results in a technically-infinite possible range, the output of this transformation has a 2 very significant properties - the mean (average) of the output dataset has a mean (μ) of 0 and a standard deviation (σ) of 1.
The key benefits of this method are:
As it's based on normalizing the mean and standard deviation of the input dataset instead of a linear range conversion, it is far less susceptible to outliers significantly affecting the result (and in fact has the effect of "squishing" outliers).
It can be used to accurately transform disparate sets of data into a similar range regardless of the original dataset's raw/actual range.
But there are a couple of "gotchas" with this technique as well...
First, it still technically does not do any form of range-binding, so it is still technically unbounded (range -∞ to ∞ with a mid-point of 0).
Second, it implicitly assumes that the raw input dataset to be transformed is normally distributed, which won't always be the case in financial markets.
The first "gotcha" is a bit of an annoyance, but isn't a huge issue as we can apply principles of normal distribution to conceptually limit the range by defining a fixed number of standard deviations from the mean. While this doesn't totally solve the "infinite range" problem (a strong enough sudden move can still break out of our "conceptual range" boundaries), the amount of movement needed to achieve that kind of impact will generally be pretty rare.
The bigger challenge is how to deal with the assumption of the input dataset being normally distributed. While most financial markets (and indicators) do tend towards a normal distribution, they are almost never going to match that distribution exactly. So let's dig a bit deeper into distributions are defined and how things like trending markets can affect them.
Skew (skewness): This is a measure of asymmetry of the bell curve, or put another way, how and in what way the bell curve is disfigured when comparing the 2 halves. The easiest way to visualize this is to draw an imaginary vertical line through the apex of the bell curve, then fold the curve in half along that line. If both halves are exactly the same, the skew is 0 (no skew/perfectly symmetrical) - which is what a normal distribution has (skew = 0). Most financial markets tend to have short, medium, and long-term trends, and these trends will cause the distribution curve to skew in one direction or another. Bullish markets tend to skew to the right (positive), and bearish markets to the left (negative).
Kurtosis: This is a measure of the "tail size" of the bell curve. Another way to state this could be how "flat" or "steep" the bell-shape is. If the bell is steep with a strong drop from the apex (like a steep cliff), it has low kurtosis. If the bell has a shallow, more sweeping drop from the apex (like a tall hill), is has high kurtosis. Translating this to financial markets, kurtosis is generally a metric of volatility as the bell shape is largely defined by the strength and frequency of outliers. This is effectively a measure of volatility - volatile markets tend to have a high level of kurtosis (>3), and stable/consolidating markets tend to have a low level of kurtosis (<3). A normal distribution (our reference), has a kurtosis value of 3.
So to try and bring all that back together, here's a quick recap of the Standardization rescaling method:
The Standardization method has an assumption of a normal distribution of input data by using the mean (average) and standard deviation to handle the transformation
Most financial markets do NOT have a normal distribution (as discussed above), and will have varying degrees of skew and kurtosis
Q: Why are we still favoring the Standardization method over the Normalization method, and how are we accounting for the innate skew and/or kurtosis inherent in most financial markets?
A: Well, since we're only trying to rescale oscillators that by-definition have a midpoint of 0, kurtosis isn't a major concern beyond the affect it has on the post-transformation scaling (specifically, the number of standard deviations from the mean we need to include in our "artificially-bound" range definition).
Q: So that answers the question about kurtosis, but what about skew?
A: So - for skew, the answer is in the formula - specifically the mean (average) element. The standard mean calculation assumes a complete dataset and therefore uses a standard (i.e. simple) average, but we're limited by the data history available to us. So we adapted the transformation formula to leverage a moving average that included a weighting element to it so that it favored recent datapoints more heavily than older ones. By making the average component more adaptive, we gained the effect of reducing the skew element by having the average itself be more responsive to recent movements, which significantly reduces the effect historical outliers have on the dataset as a whole. While this is certainly not a perfect solution, we've found that it serves the purpose of rescaling the MACD and AO to a far more well-defined range while still preserving the oscillator behavior and mid-line exceptionally well.
The most difficult parts to compensate for are periods where markets have low volatility for an extended period of time - to the point where the oscillators are hovering around the 0/midline (in the case of the AO), or when the oscillator and signal lines converge and remain close to each other (in the case of the MACD). It's during these periods where even our best attempt at ensuring accurate mirrored-behavior when compared to the original can still occasionally lead or lag by a candle.
Note: If this is a make-or-break situation for you or your strategy, then we recommend you do not use any of the included indicators that leverage this kind of bounding technique (the AO and MACD at time of publication) and instead use the Trandingview built-in versions!
We know this is a lot to read and digest, so please take your time and feel free to ask questions - we will do our best to answer! And as always, constructive feedback is always welcome!
Bar MagnifierMany times while developing algos based on patterns and reversals, I come across issues which needs lower timeframe inspection. Loading multiple charts and comparing equivalent lower timeframe is slightly cumbersome at times. Hence, I thought of building this simple tool - which will instantly provide me lower timeframe candles for given candle. Since the candle selection happen via confirmed time input, we can use this as slider to move from one candle to other for inspection.
🎲 Usage
🎯Loading the script
When you load the script, a prompt appears which asks you to select a time by clicking on the chart.
Select the bar you want to magnify and study
🎯Components
Once loaded, you can see the marker which tells which bar is magnified. And you can also see all the lower timeframe candles before that point. Please note that due to pine restrictions, we can only show last 250 lower timeframe bars. You can change the lower timeframe via settings to cover if the chart timeframe is very high.
🎯Moving to different bars
Click on the middle of the marker, you will see slider which you can slide to move from one bar to other.
Example, after sliding, you will see the lower timeframe data of new candle.
🎯Settings
Settings has only two inputs.
Bar time - selects the bar which needs to be inspected.
Lower timeframe - Default is 1 min. And select a timeframe according to your chart timeframe. Less than 1 min is not supported by security.lower_tf function. Hence, will not work.
Position Sizer for UltraCap Trading Accreditation PlansWhen you enter a typical trading challenge, you are told that your accreditation assessment demo account is funded up to a certain amount. You are then told that you can only lose a small percentage of that account before you fail the accreditation/challenge. For example, if you are given a $100,000 dollar challenge demo account and are told that you can only lose up to 8% of that account ($8,000), then in reality, you really only have $8,000 to "trade" with before the game is over. That suggests that we need a risk management system that is initially based on the "true" amount of capital that we actually have to work with at the beginning of the assessment rather than an imaginary demo balance the prop firm gives us. Traditional forex risk management principles mandate that you never risk more than 2% of your trading capital on any one trade, the idea being that as long as your win rate is above some abysmally low level, it will take you a (hopefully) long time to run out of trading capital. That’s why the rules for passing an accreditation at the prop firm Ultra Cap mandate that you never risk more than 2% of your balance, or you will fail the assessment. With that in mind, I created this indicator/tool mostly for UltraCap accreditation candidates. In addition to using it to pass a prop firm assessment, you can also use it to increase your chances of surviving in an undercapitalized trading situation with your own money. For example, you could trade an actual $8,000 dollars (money that you really have) as if it were $100,000 (which is basically what any prop firm is asking you to do when they "give" you "$100,000" to trade with but only allow you lose a maximum of $8000). In that particular situation, the algorithm in this pricing model will base your initial risk exposure on an assumed account balance of $8000, and as you increase your balance, it proportionally increases risk exposure in the background until you reach a profit level of 6%, which just so happens to be the profit goal at Ultra Cap that gets you funded! This indicator uses a simple linear equation to progressively increase the risk exposure in the background based on your current stated account balance. Initially, your trade size will seem ridiculously small, but if your win rate holds up, the trade sizes will increase substantially as you get closer to the finish line.
Reinforced RSI - The Quant Science This strategy was designed and written with the goal of showing and motivating the community how to integrate our 'Probabilities' module with their own script.
We have recreated one of the simplest strategies used by many traders. The strategy only trades long and uses the overbought and oversold levels on the RSI indicator.
We added stop losses and take profits to offer more dynamism to the strategy. Then the 'Probabilities' module was integrated to create a probabilistic reinforcement on each trade.
Specifically, each trade is executed, only if the past probabilities of making a profitable trade is greater than or equal to 51%. This greatly increased the performance of the strategy by avoiding possible bad trades.
The backtesting was calculated on the NASDAQ:TSLA , on 15 minutes timeframe.
The strategy works on Tesla using the following parameters:
1. Lenght: 13
2. Oversold: 40
3. Overbought: 70
4. Lookback: 50
5. Take profit: 3%
6. Stop loss: 3%
Time period: January 2021 to date.
Our Probabilities Module, used in the strategy example:
Exponential Bollinger Bands (EBB)This script is a variation of the popular Bollinger Bands indicator, which uses exponential moving averages (EMA) instead of simple moving averages (SMA) as its core calculation. The indicator is designed to provide a visual representation of volatility, with the distance between the upper and lower bands being determined by the standard deviation of the underlying data.
The script starts by defining a number of helper functions that are used to calculate the moving averages and standard deviations required for the indicator. The first helper function is sma(), which calculates the simple moving average of the input data over a specified length. This function uses linear interpolation to smooth the data when the length is not an integer. The stdev() function calculates the standard deviation of the input data using the simple moving average calculated by the sma() function.
The bes() function calculates the exponential moving average of the input data over a specified length. The estdev() function calculates the standard deviation of the input data using the exponential moving average calculated by the bes() function.
The estdev function calculates the standard deviation using an exponential moving average method, rather than the traditional simple moving average method used by the stdev function. The exponential moving average method gives more weight to recent data, which can make the estdev more responsive to recent changes in volatility. This can make it more useful in certain types of analysis, such as identifying trends in volatility. Additionally, it also uses the same EMA algorithm to calculate the average value of the data set, which can help to keep the output of the estdev and average functions consistent.
The script also defines two more helper functions, average() and standard_deviation(), which allow the user to switch between using simple moving averages (SMA) and exponential moving averages (EMA) as the basis for the indicator. These functions take three arguments, the input data, the length of the moving average, and a string that specifies whether to use SMA or EMA.
The script then defines the input parameters for the indicator. The user can choose whether to use SMA or EMA as the basis for the indicator using the select parameter. The user can also specify the length of the moving average and the multiplier for the standard deviation using the length and multiplier parameters, respectively.
Finally, the script calculates the average and standard deviation of the input data using the selected method (SMA or EMA), and plots the upper and lower bands of the indicator. The upper band is calculated as the average plus the standard deviation multiplied by the specified multiplier, while the lower band is calculated as the average minus the standard deviation multiplied by the specified multiplier.
Library_SmoothersLibrary "Library_Smoothers"
CorrectedMA(Src, Len)
CorrectedMA The strengths of the corrected Average (CA) is that the current value of the time series must exceed a the current volatility-dependent threshold, so that the filter increases or falls, avoiding false signals when the trend is in a weak phase.
Parameters:
Src
Len
Returns: The Corrected source.
EHMA(src, len)
EMA Exponential Moving Average.
Parameters:
src : Source to act upon
len
Returns: EMA of source
FRAMA(src, len, FC, SC)
FRAMA Fractal Adaptive Moving Average
Parameters:
src : Source to act upon
len : Length of moving average
FC : Fast moving average
SC : Slow moving average
Returns: FRAMA of source
Jurik(src, length, phase, power)
Jurik A low lag filter
Parameters:
src : Source
length : Length for smoothing
phase : Phase range is ±100
power : Mathematical power to use. Doesn't need to be whole numbers
Returns: Jurik of source
SMMA(src, len)
SMMA Smoothed moving average. Think of the SMMA as a hybrid of its better-known siblings — the simple moving average (SMA) and the exponential moving average (EMA).
Parameters:
src : Source
len
Returns: SMMA of source
SuperSmoother(src, len)
SuperSmoother
Parameters:
src : Source to smooth
len
Returns: SuperSmoother of the source
TMA(src, len)
TMA Triangular Moving Average
Parameters:
src : Source
len
Returns: TMA of source
TSF(src, len)
TSF Time Series Forecast. Uses linear regression.
Parameters:
src : Source
len
Returns: TSF of source
VIDYA(src, len)
VIDYA Chande's Variable Index Dynamic Average. See www.fxcorporate.com
Parameters:
src : Source
len
Returns: VIDYA of source
VAWMA(src, len, startingWeight, volumeDefault)
VAWMA = VWMA and WMA combined. Simply put, this attempts to determine the average price per share over time weighted heavier for recent values. Uses a triangular algorithm to taper off values in the past (same as WMA does).
Parameters:
src : Source
len : Length
startingWeight
volumeDefault : The default value to use when a chart has no volume.
Returns: The VAWMA of the source.
WWMA(src, len)
WWMA Welles Wilder Moving Average
Parameters:
src : Source
len
Returns: The WWMA of the source
ZLEMA(src, len)
ZLEMA Zero Lag Expotential Moving Average
Parameters:
src : Source
len
Returns: The ZLEMA of the source
SmootherType(mode, src, len, fastMA, slowMA, offset, phase, power, startingWeight, volumeDefault, Corrected)
Performs the specified moving average
Parameters:
mode : Name of moving average
src : the source to apply the MA type
len
fastMA : FRAMA fast moving average
slowMA : FRAMA slow moving average
offset : Linear regression offset
phase : Jurik phase
power : Jurik power
startingWeight : VAWMA starting weight
volumeDefault : VAWMA default volume
Corrected
Returns: The MA smoothed source
Super 8 - 30M BTCWelcome to Super 8, the ultimate automatic trading script for Pine!
This bad boy is designed to go both long and short, and it's equipped with all the tools you need to maximize your profits. Whether you're looking to take profit, set a trailing stop, or protect yourself with a stop loss, Super 8 has you covered.
But that's not all! Super 8 is also loaded with 8 powerful indicators to help you make informed decisions. We've got the EMA, ADX, SAR, MACD, VOLUME, BOLLINGER BANDS, DONCHIAN, and ATR all working together to give you the best possible trading experience.
And if you want to take it to the next level, Super 8 also has a feature that lets you use stepped entries in normal mode or incremental 1,2,3,... to improve your average price. Plus, if you're using trailing stop, you can activate the Backtest precision to use lower timeframes.
But what's in a name? Super 8 is called that because it's just that... super! It's tailored specifically for the OKX:BTCUSDT.P pair, so you know you're getting the best possible results. it's highly adjustable and can be used with any other pair. So no matter what market you're trading in, Super 8 has got you covered.
So if you want to level up your trading game, give Super 8 a try. You won't be disappointed.
Certain Risks of Live Algorithmic Trading:
Backtesting Cannot Assure Actual Results.
The relevant market might fail or behave unexpectedly.
Your broker may experience failures in its infrastructure, fail to execute your orders in a correct or timely fashion or reject your orders.
The system you use for generating trading orders, communicating those orders to your broker, and receiving queries and trading results from your broker may fail.
Time lag at various point in live trading might cause unexpected behavior.
The systems of third parties in addition to those of the provider from which we obtain various services, your broker, and the applicable securities market may fail or malfunction.
RSI Candle Advanced V2RSI Advanced
As the period value is longer than 14, the RSI value sticks to the value of 50 and becomes useless.
Also, when the period value is less than 14, it moves excessively, so it is difficult for us to see the movement of the RSI .
So, using the period value and the RSI value as variables, I tried to make it easier to identify the RSI value through a new function expression.
This is how RSI Advanced was developed.
Period below 14 reduce the volatility of RSI , and period above 14 increase the volatility of RSI, allowing overbought and oversold zones to work properly and give you a better view of the trend.
By applying the custom algorithm so that the 'RSI Advanced' with period on a 5-minute timeframe has the same value as the 'original RSI' with period on a 60-minute timeframe.
As another example, an 'RSI Advanced' with a period in a 60-minute time frame has the same value as an 'original RSI' with a period in a 240-minute time frame.
Compare the difference in the RSI with a period value of 200 in the snapshot.
------------------------------------------------------------------------------------------
RSI Candlestick
RSI derives its value using only the closing price as a variable.
I solved the RSI equation in reverse and tried to include the high and low prices of candlesticks in the equation.
As a result, 'if the high or low was the closing price, the value of RSI would be like this' was implemented.
Just like when a candle comes down after setting a high price, an upper tail is formed when RSI Candle goes down after setting a high price!!
In divergence, we had to look only at the relationship between closing prices, but if we use RSI candles, we can find divergences in highs and highs, and lows and lows.
Existing indicators could not express "gap", but Version 2 made it possible to express "gap"!!!!!!
RSI can be displayed as candlesticks, bars and lines
Then enjoy my RSI!
----------------------------------------------------------------------------------------
RSI Advanced
기간값이 14보다 길어질수록 RSI값은 50값에 달라붙게 되어서 쓸모가 없어집니다.
또 기간값이 14보다 줄어들수록 과도하게 움직여서 우리는 RSI의 움직임을 보기가 힘듭니다.
그래서 기간 값과 RSI 값을 변수로 사용하여 새로운 함수 식을 통해 RSI 값을 식별하기 편하도록 해보았습니다.
이렇게 RSI Advanced가 개발되었습니다.
기간값이 14보다 낮으면 rsi의 변동폭이 줄어들고, 기간값이 14보다 크면 변동폭이 넓어져 과매수 및 과매도 영역이 제대로 작동하여 추세를 더 잘 볼 수 있습니다.
또한 저는 5분 타임프레임의 기간값이 168(=14*12)인 RSI가 주기 값이 14인 60분 타임프레임의 RSI와 동일한 값을 갖도록 적절한 함수 표현식을 적용하여 RSI를 변경했습니다.
다른 예로, 15분 시간 프레임에서 기간값이 56(=14*4)인 RSI는 60분 시간 프레임의 기간값이 14인 RSI와 동일한 값을 갖습니다.
기간값이 200인 RSI의 차이를 스냅샷에서 비교해보십시오.
-----------------------------
RSI Candlestick
RSI는 종가만을 변수로 사용하여 값을 도출해냅니다.
저는 RSI 식을 역으로 풀어내어서 캔들스틱의 고가와 저가, 시가를 식에 포함시켜보았습니다.
결과적으로, '만약 고가나 저가가 종가였다면 RSI의 값이 이럴것이다'를 구현해내었습니다.
캔들이 고가를 찍고 내려오면 윗꼬리가 생기듯 RSI Candle에서도 고가를 찍고 내려오면 윗꼬리가 생기는겁니다!!
다이버전스 또한 원래는 종가끼리의 관계만 봐야했지만 RSI 캔들을 이용한다면 고가와 고가, 저가와 저가에서도 다이버전스를 발견할 수 있습니다.
기존의 지표는 "갭"을 표현하지 못했지만 Version 2 에서는 "갭"을 표현할 수 있게 만들었습니다!!!!!!
그럼 잘 사용해주십시오!!!
Wolfe Strategy [Trendoscope]Hello Everyone,
Wish you all Merry X-Mas and happy new year. Lets start 2023 with fresh new strategy built on Wolfe Indicator. Details of the indicator can be found here
🎲 Wolfe Concept
Wolfe concept is simple. Whenever a wedge is formed, draw a line joining pivot 1 and 4 as shown in the chart below:
For simplicity, we will only consider static value for Target and Stop. But, entry is done based on breaking the triangle. Revised strategy looks something like this:
🎲 Settings
Settings are simple and details of each are provided via tooltips.
Out of these, the most important one is minimum risk reward ratio. If you set lower risk reward threshold then losing few trades may generate more losses than more winning trades. Similarly higher value will filter out most of the trades and may not work efficiently. Default value set to 1 to make sure optimal risk reward is present before placing trade. Also make note that since the entry bar is always moving towards stop, as and when pattern progress, the RR will also increase. Hence, a pattern which is below RR threshold may become good to trade at certain point of time in future.
🎲 Strategy Parameters
Default strategy parameters are initialised via definition. Margins are set to 100 to disable leveraged trades. Appropriate values are chosen for other parameters. These can be altered based on individual strategy and trading plan.
As the strategy concentrates on the single pattern, number of trades generated are comparatively less. But, there is chance to increase the algorithm further to catch more such patterns on larger scale. Will try to work on them in next versions.
🎲 Pine Strategy limitations
Backtest can only be done on one direction as pine strategy cannot have both long and short open trades together. Hence, it is mandatory to chose either long/short trades in settings.
Since pyramiding is limited to 1, there is possibility of a pattern not generating trade even though the entry conditions are met. They are just based on pine limitations and not necessarily mean patterns are not good for placing trades.
Price Filter [AstrideUnicorn]The indicator calculates a fast price filter based on the closing price of the underlying asset. Overall, it is intended to provide a fast, reliable way to detect trend direction and confirm trend strength, using statistical measures of price movements.
The algorithm was adapted from Marcus Schmidberger's (2018) article "High Frequency Trading with the MSCI World ETF". It demeans the price time series using the long-term average and then normalizes it with the long-term standard deviation. The resulting time series is then compared to specified thresholds to determine the trend direction.
HOW TO USE
The indicator surface is colored green if the price is trending upwards and red if the price is trending downwards. If the indicator outline is the opposite color of the indicator surface, it indicates that the price is moving against the trend and the current trend may be losing strength.
If the 'Use threshold' setting is enabled, the indicator will be colored blue if its value is within the range defined by the upper and lower thresholds. This indicates that the price is trending sideways, or that the current trend is losing strength.
SETTNGS
Length - the length of the long-term average used to calculate the price filter. Recommended range 20 - 200. The sensitivity of the indicator increases as the value becomes smaller, allowing it to detect smaller price moves and swings earlier.
Threshold - the threshold value used to detect trend direction.
Use threshold - a boolean (true/false) input that determines whether to use the threshold value for confirmation.
The Forbidden RSI [CHE]My main goal of programming and publishing an indicator is that everyone should have the opportunity to use indicators that do not show false signals or where there is maximum practical use, so I publish this indicator:
This script is an advanced variant of the Onset Trend Detector, a technical indicator for trend analysis developed by John F. Ehlers.
It is based on a non-linear quotient transformation and expands upon Mr. Ehlers' previous studies, the Super Smoother Filter and the Roofing Filter,
to address the lag issue common to moving average type indicators.
The algorithm in this script registers the most recent peak value and normalizes it. The normalized value then decays slowly until the next
peak swing. The ratio of the previously filtered value to the corresponding peak value is then transformed using a quotient transformation to
provide the resulting oscillator.
This script implements an indicator called "The forbidden RSI" (TFRSI). This indicator was developed by chervolino as an improvement on the
standard Relative Strength Index (RSI), which is a technical indicator used to measure the strength of a trend and identify potential buy and sell signals.
The TFRSI is calculated based on the close price and is typically plotted on a scale from -20 to 120, with values above 100 indicating that
the asset is overbought (likely to decline in value) and values below 1 indicating that it is oversold (likely to increase in value). The script
allows the user to customize the length of the RSI and the length of the trigger used to smooth the signal.
In order to calculate the TFRSI, the script first initializes some constants and then performs a series of calculations to determine the value of
"HP", "ag", and "Sp". The RSI value is then calculated based on the values of "X", which is based on "ag" and "Sp", and "q1", which is based on "X"
and the trigger length. The RSI value is plotted in a chart along with upper and lower bounds and a filled region representing the background.
Please check it out, it works perfectly to find good analysis and entries for both, longs and shorts.
Best regards
Chervolino
Note: I hope that the moderators like my script and the explanation and don't delete it this time
Welford Bollinger Bands (WBB)The Welford method is an algorithm for calculating the running average and variance of a series of numbers in a single pass, without the need to store all the previous values. It works by maintaining an ongoing running average and variance, updating them with each new value in the series. The running average is updated using a simple formula that adds the new value to the previous average, weighed by the number of values that have been processed so far. The variance is updated using a similar formula that takes into account the deviation of the new value from the running average.
The Welford method has several advantages that make it a good fit for use in calculating Bollinger Bands. First, it is more numerically stable than other methods, as it avoids accumulating round-off errors and can handle large numbers of data points without overflow or underflow. This is important when working with financial data, which can contain large price movements and wide ranges of values.
Second, the Welford method is well-suited for use in real-time or streaming data scenarios where all the data may not be available upfront. This is useful in the context of Bollinger Bands, which are often used to identify trend changes and trading opportunities in real-time, as the bands are updated with each new data point.
Finally, the Welford method is simple and efficient, making it easy to implement and fast to compute. This is important when creating technical indicators and trading strategies, as performance is often a critical factor.
Overall, the Welford method is a reliable and efficient way to calculate the running average and variance of a series of numbers, making it a good fit for use in calculating Bollinger Bands and other technical indicators.
Midnight Open NY TimeMidnight Open shows opening price of the first candle after New York Midnight.
According to ICT, this is what IBPDA - Inter Bank Price Delivery Algorithm - sees as a true market opening and we should aim for shorts above it (sell for premium) and longs below it (buy at discount).