Mechanical Trading StrategyThe "Mechanical Trading Strategy" is a simple and systematic approach to trading that aims to capture short-term price movements in the financial markets. This strategy focuses on executing trades based on specific conditions and predetermined profit targets and stop loss levels.
Key Features:
Profit Target: The strategy allows you to set a profit target as a percentage of the entry price. This target represents the desired level of profit for each trade.
Stop Loss: The strategy incorporates a stop loss level as a percentage of the entry price. This level represents the maximum acceptable loss for each trade, helping to manage risk.
Entry Condition: The strategy triggers trades at a specific time. In this case, the condition for entering a trade is based on the hour of the candle being 16 (4:00 PM). This time-based entry condition provides a systematic approach to executing trades.
Position Sizing: The strategy determines the position size based on a fixed percentage of the available equity. This approach ensures consistent risk management and allows for potential portfolio diversification.
Execution:
When the entry condition is met, signified by the hour being 16, the strategy initiates a long position using the strategy.entry function. It sets the exit conditions using the strategy.exit function, with a limit order for the take profit level and a stop order for the stop loss level.
Take Profit and Stop Loss:
The take profit level is calculated by adding a percentage of the entry price to the entry price itself. This represents the profit target for the trade. Conversely, the stop loss level is calculated by subtracting a percentage of the entry price from the entry price. This level represents the maximum acceptable loss for the trade.
By using this mechanical trading strategy, traders can establish a disciplined and systematic approach to their trading decisions. The predefined profit target and stop loss levels provide clear exit rules, helping to manage risk and potentially maximize returns. However, it is important to note that no trading strategy is guaranteed to be profitable, and careful analysis and monitoring of market conditions are always recommended.
Educational
120x ticker screener (composite tickers)In specific circumstances, it is possible to extract data, far above the 40 `request.*()` call limit for 1 single script .
The following technique uses composite tickers . Changing tickers needs to be done in the code itself as will be explained further.
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
🔶 PRINCIPLE
Standard example:
c1 = request.security('MTLUSDT' , 'D', close)
This will give the close value from 1 ticker (MTLUSDT); c1 for example is 1.153
Now let's add 2 tickers to MTLUSDT; XMRUSDT and ORNUSDT with, for example, values of 1.153 (I), 143.4 (II) and 0.8242 (III) respectively.
Just adding them up 'MTLUSDT+XMRUSDT+ORNUSDT' would give 145.3772 as a result, which is not something we can use...
Let's multiply ORNUSDT by 100 -> 14340
and multiply MTLUSDT by 1000000000 -> 1153000000 (from now, 10e8 will be used instead of 1000000000)
Then we make the sum.
When we put this in a security call (just the close value) we get:
c1 = request.security('MTLUSDT*10e8+XMRUSDT*100+ORNUSDT', 'D', close)
'MTLUSDT*10e8+XMRUSDT*100+ORNUSDT' -> 1153000000 + 14340 + 0.8242 = 1153014340.8242 (a)
This (a) will be split later on, for example:
1153014330.8242 / 10e8 = 1.1530143408242 -> round -> in this case to 1.153 (I), multiply again by 10e8 -> 1153000000.00 (b)
We subtract this from the initial number:
1153014340.8242 (a)
- 1153000000.0000 (b)
–––––––––––––––––
14340.8242 (c)
Then -> 14340.8242 / 100 = 143.408242 -> round -> 143.4 (II) -> multiply -> 14340.0000 (d)
-> subtract
14340.8242 (c)
- 14340.0000 (d)
––––––––––––
0.8242 (III)
Now we have split the number again into 3 tickers: 1.153 (I), 143.4 (II) and 0.8242 (III)
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
In this publication the function compose_3_() will make a composite ticker of 3 tickers, and the split_3_() function will split these 3 tickers again after passing 1 request.security() call.
In this example:
t46 = 'BINANCE:MTLUSDT', n46 = 10e8 , r46 = 3, t47 = 'BINANCE:XMRUSDT', n47 = 10e1, r47 = 1, t48 = 'BINANCE:ORNUSDT', r48 = 4 // T16
•••
T16= compose_3_(t48, t47, n47, t46, n46)
•••
= request.security(T16, res, )
•••
= split_3_(c16, n46, r46, n47, r47, r48)
🔶 CHANGING TICKERS
If you need to change tickers, you only have to change the first part of the script, USER DEFINED TICKERS
Back to our example, at line 26 in the code, you'll find:
t46 = 'BINANCE:MTLUSDT', n46 = 10e8 , r46 = 3, t47 = 'BINANCE:XMRUSDT', n47 = 10e1, r47 = 1, t48 = 'BINANCE:ORNUSDT', r48 = 4 // T16
( t46 , T16 ,... will be explained later)
You need to figure out how much you need to multiply each ticker, and the number for rounding, to get a good result.
In this case:
'BINANCE:MTLUSDT', multiply number = 10e8, round number is 3 (example value 1.153)
'BINANCE:XMRUSDT', multiply number = 10e1, round number is 1 (example value 143.4)
'BINANCE:ORNUSDT', NO multiply number, round number is 4 (example value 0.8242)
The value with most digits after the decimal point by preference is placed to the right side (ORNUSDT)
If you want to change these 3, how would you do so?
First pick your tickers and look for the round values, for example:
'MATICUSDT', example value = 0.5876 -> round -> 4
'LTCUSDT' , example value = 77.47 -> round -> 2
'ARBUSDT' , example value = 1.0231 -> round -> 4
Value with most digits after the decimal point -> MATIC or ARB, let's pick ARB to go on the right side, LTC at the left of ARB, and MATIC at the most left side.
-> 'MATICUSDT', LTCUSDT', ARBUSDT'
Then check with how much 'LTCUSDT' and 'MATICUSDT' needs to be multiplied to get this: 5876 0 7747 0 1.0231
'MATICUSDT' -> 10e10
'LTCUSDT' -> 10e3
Replace:
t46 = 'BINANCE:MTLUSDT', n46 = 10e8 , r46 = 3, t47 = 'BINANCE:XMRUSDT', n47 = 10e1, r47 = 1, t48 = 'BINANCE:ORNUSDT', r48 = 4 // T16
->
t46 = 'BINANCE:MATICUSDT', n46 = 10e10 , r46 = 4, t47 = 'BINANCE:LTCUSDT', n47 = 10e3, r47 = 2, t48 = 'BINANCE:ARBUSDT', r48 = 4 // T16
DO NOT change anything at t46, n46,... if you don't know what you're doing!
Only
• tickers ('BINANCE:MTLUSDT', 'BINANCE:XMRUSDT', 'BINANCE:ORNUSDT', ...),
• multiply numbers (10e8, 10e1, ...) and
• round numbers (3, 1, 4, ...)
should be changed.
There you go!
🔶 LIMITATIONS
🔹 The composite ticker fails when 1 of the 3 isn't in market in the weekend, while the other 2 are.
That is the reason all tickers are crypto. I think it is possible to combine stock,... tickers, but they have to share the same market hours.
🔹 The number cannot be as large as you want, the limit lays around 15-16 digits.
This means when you have for example 123, 45.67 and 0.000000000089, you'll get issues when composing to this:
-> 123045670.000000000089 (21 digits)
Make sure the numbers are close to each other as possible, with 1 zero (or 2) in between:
-> 1.230045670089 (13 digits by doing -> (123 * 10e-3) + (45.67 * 10e-7) + 0.000000000089)
🔹 This script contains examples of calculated values, % change, SMA, RMA and RSI.
These values need to be calculated from HTF close data at current TF (timeframe).
This gives challenges. For example the SMA / %change is not a problem (same values at 1h TF from Daily data).
RMA , RSI is not so easy though...
Daily values are rather similar on a 2-3h TF, but 1h TF and lower is quite different.
At the moment I haven't figured out why, if someone has an idea, don't hesitate to share.
The main goal of this publication is 'composite tickers ~ request.security()' though.
🔹 When a ticker value changes substantially (x10, x100), the multiply number needs to be adjusted accordingly.
🔶 SETTINGS
SHOW SETS
SET
• Length : length of SMA, RMA and RSI
• HTF : Higher TimeFrame (default Daily)
TABLE
• Size table : \ _ Self-explanatory
• Include exchange name : /
• Sort : If exchange names are shown, the exchanges will be sorted first
COLOURS
• CH%
• RSI
• SMA (RMA)
DEBUG
Remember t46 , T16 ,... ?
This can be used for debugging/checking
ALWAYS DISABLE " sort " when doing so.
Example:
Set string -> T1 (tickers FIL, CAKE, SOL)
(Numbers are slightly different due to time passing by between screen captures)
Placing your tickers at the side panel makes it easy to compare with the printed label below the table (right side, 332201415014.45 ),
together with the line T1 in the script:
t1 = 'BINANCE:FILUSDT' , n1 = 10e10, r1 = 4, t2 = 'BINANCE:CAKEUSDT' , n2 = 10e5 , r2 = 3, t3 = 'BINANCE:SOLUSDT' , r3 = 2 // T1
FIL : 3.322
CAKE: 1.415
SOL : 14.56
Now it is easy to check whether the tickers are placed close enough to each other, with 1-2 zero's in between.
If you want to check a specific ticker, use " Show Ticker" , see out initial example:
Set string -> T16
Show ticker -> 46 (in the code -> t46 = 'BINANCE:MTLUSDT')
(Set at 0 to disable " check string " and NONE to disable " Set string ")
-> Debug/check/set away! 😀
🔶 OTHER TECHNIQUES
• REGEX ( Regular expression ) and str.match() is used to delete the exchange name from the ticker, in other words, everything before ":" is deleted by following regex:
exch(t) => incl_exch ? t : str.match(t, "(?<=:) +")
• To sort, array.sort_indices() is used (line 675 in the code), just as in my first "sort" publication Sort array alphabetically - educational
aSort = arrT.copy()
sort_Indices = array.sort_indices(id= aSort, order= order.ascending)
• Numbers and text colour will adjust automatically when switching between light/dark mode by using chart.fg_color / chart.bg_color
🔹 DISCLAIMER
Please don't ask me for custom screeners, thank you.
Simple Ultimate Oscillator█ OVERVIEW
This indicator as an educational and showcase the usage of user-defined types (UDT) or objects for Ultimate Oscillator.
█ CREDITS
TradingView
█ FEATURES
1. Color of plot is based on contrast color of chart background.
2. Plot fill of overbought and oversold.
3. Support Multi Timeframe.
Simple Ichimoku Kinko Hyo Cloud█ OVERVIEW
This indicator as an educational and showcase the usage of user-defined types or objects (UDT) for Ichimoku Kinko Hyo or Ichimoku Cloud.
█ CREDITS
TradingView
DEVPRO TradingDEVPRO Trading system comprises of the following:
D - Double (EMA and VWAP)
E - EMA
V - VWAP (current and previous day ending VWAP level)
P - Standard Pivot Point
R - RSI (Multi-time frame table is added at the top and traders can add standard RSI 14 as an additional non-overlay indicator)
O - OI data (not available for options trading in TV but trader can always check in their broker terminal)
Double EMA have been color coded in red and green for bullish and bearish trends.
Candles are colored for bullish (green), sideways (grey) and bearish (red) phases.
Setup to be traded with monthly options for stocks and weekly options for indices.
Bullish Setup:
RSI greater than 50
Current candle close above VWAP and previous day closing VWAP
Current candle close above daily Pivot
For option buying (Call option OI should be falling below its moving average 20 meaning short covering)
For option selling (Put option OI should be rising above its moving average 20 meaning Put writers confidence is increasing)
Book partial qty profits at R1/R2/R3 and/or exit completely on Doji candle low break
Bearish Setup:
RSI less than 50
Current candle close below VWAP and previous day closing VWAP
Current candle close below daily Pivot
For option buying (Put option OI should be falling below its moving average 20 meaning short covering)
For option selling (Call option OI should be rising above its moving average 20 meaning Call writers confidence is increasing)
Book partial qty profits at S1/S2/S3 and/or exit completely on Doji candle high break
Open Interest Chart [LuxAlgo]The Open Interest Chart displays Commitments of Traders %change of futures open interest , with a unique circular plotting technique, inspired from this publication Periodic Ellipses .
🔶 USAGE
Open interest represents the total number of contracts that have been entered by market participants but have not yet been offset or delivered. This can be a direct indicator of market activity/liquidity, with higher open interest indicating a more active market.
Increasing open interest is highlighted in green on the circular plot, indicating money coming into the market, while decreasing open interests highlighted in red indicates money coming out of the market.
You can set up to 6 different Futures Open interest tickers for a quick follow up:
🔶 DETAILS
Circles are drawn, using plot() , with the functions createOuterCircle() (for the largest circle) and createInnerCircle() (for inner circles).
Following snippet will reload the chart, so the circles will remain at the right side of the chart:
if ta.change(chart.left_visible_bar_time ) or
ta.change(chart.right_visible_bar_time)
n := bar_index
Here is a snippet which will draw a 39-bars wide circle that will keep updating its position to the right.
//@version=5
indicator("")
n = bar_index
barsTillEnd = last_bar_index - n
if ta.change(chart.left_visible_bar_time ) or
ta.change(chart.right_visible_bar_time)
n := bar_index
createOuterCircle(radius) =>
var int end = na
var int start = na
var basis = 0.
barsFromNearestEdgeCircle = 0.
barsTillEndFromCircleStart = radius
startCylce = barsTillEnd % barsTillEndFromCircleStart == 0 // start circle
bars = ta.barssince(startCylce)
barsFromNearestEdgeCircle := barsTillEndFromCircleStart -1
basis := math.min(startCylce ? -1 : basis + 1 / barsFromNearestEdgeCircle * 2, 1) // 0 -> 1
shape = math.sqrt(1 - basis * basis)
rad = radius / 2
isOK = barsTillEnd <= barsTillEndFromCircleStart and barsTillEnd > 0
hi = isOK ? (rad + shape * radius) - rad : na
lo = isOK ? (rad - shape * radius) - rad : na
start := barsTillEnd == barsTillEndFromCircleStart ? n -1 : start
end := barsTillEnd == 0 ? start + radius : end
= createOuterCircle(40)
plot(h), plot(l)
🔶 LIMITATIONS
Due to the inability to draw between bars, from time to time, drawings can be slightly off.
Bar-replay can be demanding, since it has to reload on every bar progression. We don't recommend using this script on bar-replay. If you do, please choose the lowest speed and from time to time pause bar-replay for a second. You'll see the script gets reloaded.
🔶 SETTINGS
🔹 TICKERS
Toggle :
• Enabled -> uses the first column with a pre-filled list of Futures Open Interest tickers/symbols
• Disabled -> uses the empty field where you can enter your own ticker/symbol
Pre-filled list : the first column is filled with a list, so you can choose your open interest easily, otherwise you would see COT:088691_F_OI aka Gold Futures Open Interest for example.
If applicable, you will see 3 different COT data:
• COT: Legacy Commitments of Traders report data
• COT2: Disaggregated Commitments of Traders report data
• COT3: Traders in Financial Futures report data
Empty field : When needed, you can pick another ticker/symbol in the empty field at the right and disable the toggle.
Timeframe : Commitments of Traders (COT) data is tallied by the Commodity Futures Trading Commission (CFTC) and is published weekly. Therefore data won't change every day.
Default set TF is Daily
🔹 STYLE
From middle:
• Enabled (default): Drawings start from the middle circle -> towards outer circle is + %change , towards middle of the circle is - %change
• Disabled: Drawings start from the middle POINT of the circle, towards outer circle is + OR -
-> in both options, + %change will be coloured green , - %change will be coloured red .
-> 0 %change will be coloured blue , and when no data is available, this will be coloured gray .
Size circle : options tiny, small, normal, large, huge.
Angle : Only applicable if "From middle" is disabled!
-> sets the angle of the spike:
Show Ticker : Name of ticker, as seen in table, will be added to labels.
Text - fill
• Sets colour for +/- %change
Table
• Sets 2 text colours, size and position
Circles
• Sets the colour of circles, style can be changed in the Style section.
You can make it as crazy as you want:
Volume Spread Analysis Candle PatternsVolume Spread Analysis (VSA) is a methodology used in trading and investing to analyze the relationship between volume, price spread, and price movement in financial markets. It was developed by Richard Wyckoff, a prominent trader and market observer.
The core principle of VSA is that changes in volume can provide insights into the strength or weakness of price movements and indicate the intentions of market participants. By examining the interplay between volume and price, traders aim to identify the behavior of smart money (informed institutional investors) versus less-informed market participants.
Key concepts in Volume Spread Analysis include:
1. Volume: VSA places significant emphasis on volume as a leading indicator. It suggests that changes in volume precede price movements and can provide clues about the market's sentiment.
2. Spread: The spread refers to the price range between the high and low of a given trading period (e.g., a candlestick or bar). VSA considers the relationship between volume and spread to gauge the strength of price action.
3. Upthrust and Springs: These are VSA candle patterns that indicate potential market reversals. An upthrust occurs when prices briefly move above a resistance level but fail to sustain the upward momentum. Springs, on the other hand, happen when prices briefly dip below a support level but quickly rebound.
4. No Demand and No Supply: These patterns suggest a lack of interest or participation from buyers (no demand) or sellers (no supply) at a particular price level. These conditions may foreshadow a potential price reversal or consolidation.
5. Hidden Buying and Selling: Hidden buying occurs when prices close near the high of a bar, indicating the presence of buyers even though the market appears weak. Hidden selling is the opposite, where prices close near the low of a bar, suggesting the presence of sellers despite apparent strength.
By combining these VSA concepts with other technical analysis tools, traders seek to identify potential trading opportunities with favorable risk-reward ratios. VSA can be applied to various financial markets, including stocks, futures, forex, and cryptocurrencies.
It's important to note that while VSA provides a framework for analyzing volume and price, its interpretation and application require experience, skill, and subjective judgment. Traders often use VSA in conjunction with other technical indicators and chart patterns to make well-informed trading decisions.
Range Projections [TFO]The purpose of this indicator is to see how often price reached certain standard deviations from a selected time range. The inspiration for this was to study ICT (Inner Circle Trader) concepts regarding the Central Bank Dealer’s Range (CBDR), which is 2:00 pm - 8:00 pm New York local time according to ICT Core Content. However, the idea and data collection could certainly be applied to any range of time.
The main settings of this indicator are session time, range type, and the standard deviation filter. The session time is the window of price that will be utilized for range projections. The range type can be either body or wick (on the current timeframe). The standard deviation filter is used to eliminate sessions whose ranges (from high to low) are greater than the desired/input number of standard deviations from all available session ranges.
In this example, the time range is set to 16:00 - 20:00, or the time between the New York session close and the Asia session open. Our standard deviations are set to 1, 2, 2.5, and 4. Now, by taking this session’s price range and extrapolating these extensions from the initial range, we can use these levels to see if and how price interacts with them before the next 16:00 - 20:00 session.
Furthermore, we can enable the Data Table to analyze how often price trades to these levels for the sessions that are deemed valid (determined by the standard deviation filter). This time our standard deviations are set to 1, 2, 3, and 4.
This concept can theoretically be applied to any window of time. ICT has mentioned that, in instances where the CBDR is too large, the Asia range may be used instead. We can observe that the indicator behaves the same way when we change the session to the Asia range, 20:00 - 00:00.
bar viewBar view is a simple script to show other higher time frame windows while you are focusing on lower time for precise decision making.
For example you are currently operating at 1 minute time frame and you want to see other bars on higher time frames e.g. 5 minute, 15 minutes etc.
Feel free to add multiple bar view to see different time frames.
Interactive Motive Wave ChecklistHere is an interactive tool that can be used for learning a bit about Elliott Waves
🎲 How it works?
The script upon load asks users to enter 6 pivots in an order. Once all 6 pivots are selected on the interactive chart, the script will calculate if the structure is a valid motive wave.
When you load the script, you will see a prompt on the chart to select points on the chart to form 6 pivots.
When you select the 6 pivots, the checklists are populated on the chart to notify users which conditions for qualifying the selection has passed and which of them are failed.
🎲 Conditions for Motive Wave
Motive wave can be either Impulse or Diagonal Wave. Diagonal wave can be either expanding or contracting diagonals. To learn more about diagonal waves, please go through this idea.
Rules for generic motive waves are as below
Pivots in order - Checks wether the pivots selected are in progressive order.
Directions in order - Checks if the pivot directions are correct - either PH, PL, PH, PL, PH, PL or PL, PH, PL, PH, PL, PH
Wave 2 never moves beyond the start of wave 1 - Wave 2 retracement is less than 100% of wave1
Wave 3 always moves beyond the end of wave 1 - Wave 3 retracement is more than 100% of wave2
Wave 3 is never the shortest one - Checks if Wave 3 is bigger than either Wave 1 or wave 5 or both.
Now, these are the specific rules for Impulse Waves on top of Motive Wave conditions
Wave 4 never moves beyond the end of Wave 1 - meaning wave 1 and wave 4 never overlap on price scale.
Wave 1, 3, 5 are all not extended. We check for retracement ratios of more than 200% to be considered as extended wave.
Below are the conditions for Diagonal Waves on top of Motive Wave conditions
Wave4 never moves beyond the start of Wave 3 - Wave 4 retracement is less than 100%
Wave 4 always ends within the price territory of Wave 1 - Unlike impulse wave, wave 4 intersects with wave 1 in case of diagonal waves. This is the major difference between impulse and diagonal wave.
Waves are progressively expanding or contracting - Wave1 > Wave3 > Wave5 and Wave2 > Wave4 to be contracting diagonal. Wave1 < Wave3 < Wave5 and Wave2 < Wave4 to be expanding diagonal wave.
Here is an example of diagonal wave projection
Here is an example of impulse wave projection
Machine Learning : Cosine Similarity & Euclidean DistanceIntroduction:
This script implements a comprehensive trading strategy that adheres to the established rules and guidelines of housing trading. It leverages advanced machine learning techniques and incorporates customised moving averages, including the Conceptive Price Moving Average (CPMA), to provide accurate signals for informed trading decisions in the housing market. Additionally, signal processing techniques such as Lorentzian, Euclidean distance, Cosine similarity, Know sure thing, Rational Quadratic, and sigmoid transformation are utilised to enhance the signal quality and improve trading accuracy.
Features:
Market Analysis: The script utilizes advanced machine learning methods such as Lorentzian, Euclidean distance, and Cosine similarity to analyse market conditions. These techniques measure the similarity and distance between data points, enabling more precise signal identification and enhancing trading decisions.
Cosine similarity:
Cosine similarity is a measure used to determine the similarity between two vectors, typically in a high-dimensional space. It calculates the cosine of the angle between the vectors, indicating the degree of similarity or dissimilarity.
In the context of trading or signal processing, cosine similarity can be employed to compare the similarity between different data points or signals. The vectors in this case represent the numerical representations of the data points or signals.
Cosine similarity ranges from -1 to 1, with 1 indicating perfect similarity, 0 indicating no similarity, and -1 indicating perfect dissimilarity. A higher cosine similarity value suggests a closer match between the vectors, implying that the signals or data points share similar characteristics.
Lorentzian Classification:
Lorentzian classification is a machine learning algorithm used for classification tasks. It is based on the Lorentzian distance metric, which measures the similarity or dissimilarity between two data points. The Lorentzian distance takes into account the shape of the data distribution and can handle outliers better than other distance metrics.
Euclidean Distance:
Euclidean distance is a distance metric widely used in mathematics and machine learning. It calculates the straight-line distance between two points in Euclidean space. In two-dimensional space, the Euclidean distance between two points (x1, y1) and (x2, y2) is calculated using the formula sqrt((x2 - x1)^2 + (y2 - y1)^2).
Dynamic Time Windows: The script incorporates a dynamic time window function that allows users to define specific time ranges for trading. It checks if the current time falls within the specified window to execute the relevant trading signals.
Custom Moving Averages: The script includes the CPMA, a powerful moving average calculation. Unlike traditional moving averages, the CPMA provides improved support and resistance levels by considering multiple price types and employing a combination of Exponential Moving Averages (EMAs) and Simple Moving Averages (SMAs). Its adaptive nature ensures responsiveness to changes in price trends.
Signal Processing Techniques: The script applies signal processing techniques such as Know sure thing, Rational Quadratic, and sigmoid transformation to enhance the quality of the generated signals. These techniques improve the accuracy and reliability of the trading signals, aiding in making well-informed trading decisions.
Trade Statistics and Metrics: The script provides comprehensive trade statistics and metrics, including total wins, losses, win rate, win-loss ratio, and early signal flips. These metrics offer valuable insights into the performance and effectiveness of the trading strategy.
Usage:
Configuring Time Windows: Users can customize the time windows by specifying the start and finish time ranges according to their trading preferences and local market conditions.
Signal Interpretation: The script generates long and short signals based on the analysis, custom moving averages, and signal processing techniques. Users should pay attention to these signals and take appropriate action, such as entering or exiting trades, depending on their trading strategies.
Trade Statistics: The script continuously tracks and updates trade statistics, providing users with a clear overview of their trading performance. These statistics help users assess the effectiveness of the strategy and make informed decisions.
Conclusion:
With its adherence to housing trading rules, advanced machine learning methods, customized moving averages like the CPMA, and signal processing techniques such as Lorentzian, Euclidean distance, Cosine similarity, Know sure thing, Rational Quadratic, and sigmoid transformation, this script offers users a powerful tool for housing market analysis and trading. By leveraging the provided signals, time windows, and trade statistics, users can enhance their trading strategies and improve their overall trading performance.
Disclaimer:
Please note that while this script incorporates established tradingview housing rules, advanced machine learning techniques, customized moving averages, and signal processing techniques, it should be used for informational purposes only. Users are advised to conduct their own analysis and exercise caution when making trading decisions. The script's performance may vary based on market conditions, user settings, and the accuracy of the machine learning methods and signal processing techniques. The trading platform and developers are not responsible for any financial losses incurred while using this script.
By publishing this script on the platform, traders can benefit from its professional presentation, clear instructions, and the utilisation of advanced machine learning techniques, customised moving averages, and signal processing techniques for enhanced trading signals and accuracy.
I extend my gratitude to TradingView, LUX ALGO, and JDEHORTY for their invaluable contributions to the trading community. Their innovative scripts, meticulous coding patterns, and insightful ideas have profoundly enriched traders' strategies, including my own.
Support Resistance Classification (VR) [LuxAlgo]The Support Resistance Classification (VR) indicator shows SR levels on any chart's visible range using higher time-frame data (HTF). Levels are classified 1 through 10 based on their strength, with lower values indicating stronger support/resistance levels.
This indicator uses visible range functionality, whereas if you adjust your chart to show previous price data, the indicator may show new levels.
🔶 USAGE
Certain indicators on higher timeframes can provide longer term support/resistance levels on lower timeframes. Users can use the provided levels on a chart visible range and use them as reference for future support/resistance levels.
The classification algorithm measures the strength of a support/resistance level using the entire chart visible range and is in a range of 1 to 10, with higher values indicating a weaker support/resistance.
Supports/resistances highlighted by the indicator can be used for future applications by marking them on the chart (quickly done with alt + h).
🔶 DETAILS
All calculations are based on what you see on the Visible Chart, as such changing the chart will recalculate the indicator.
Since only Swings which are not broken are included, every break would exclude that swing. Therefore, even when 'value' is chosen at Settings ('Value'), breaks are always calculated on the entire line.
🔶 SETTINGS
Fade: After x breaks the line becomes invisible
Value:
value:
• SMA, upper/lower: the breaks are triggered on the moving average itself
• Fibonacci Pivot Point levels, Previous High, Previous Low: only last HTF values can be used for breaks
• Swings (see SWING SETTINGS)
line:
• SMA, upper/lower: the breaks are triggered on the entire line, based on its latest value
• Fibonacci Pivot Point Levels, Previous High, Previous Low: breaks are triggered on the entire line, based on its latest value
• Swings (see SWING SETTINGS)
🔹 Swing Settings
Swings are always calculated at current timeframe, setting a HTF is not applicable on Swings.
Left/Right: for Swing calculation ( pivothigh , pivotlow )
Show: enables you to see the pivot points
🔹 Set
N°: The concerning number
TYPE:
• SMA (Simple Moving Average)
• Previous High/Low
• Upper/Lower ( Bollinger Bands )
• Pivot Point levels : "Fibonacci"
LENGTH: sets the 'Number of bars', needed for calculations (applicable for SMA, upper/lower)
MULT: sets the 'Standard deviation factor' (only applicable for upper/lower - BB)
HTF: sets 'Higher Time Frame' (applicable for SMA, upper/lower, Previous High/Low, Fibonacci)
🔹 Show Values
You can make up to 5 values visible (if you want to check/verify), except for Swings (see SWING SETTINGS)
To do so, enable (A -> E), and choose the N° you want to see.
This also is a useful tool if you're not sure which value you want to set.
Rolling Risk-Adjusted Performance RatiosThis simple indicator calculates and provides insights into different performance metrics of an asset - Sharpe, Sortino and Omega Ratios in particular. It allows users to customize the lookback period and select their preferred data source for evaluation of an asset.
Sharpe Ratio:
The Sharpe Ratio measures the risk-adjusted return of an asset by considering both the average return and the volatility or riskiness of the investment. A higher Sharpe Ratio indicates better risk-adjusted performance. It allows investors to compare different assets or portfolios and assess whether the returns adequately compensate for the associated risks. A higher Sharpe Ratio implies that the asset generates more return per unit of risk taken.
Sortino Ratio:
The Sortino Ratio is a variation of the Sharpe Ratio that focuses specifically on the downside risk or volatility of an asset. It takes into account only the negative deviations from the average return (downside deviation). By considering downside risk, the Sortino Ratio provides a more refined measure of risk-adjusted performance, particularly for investors who are more concerned with minimizing losses. A higher Sortino Ratio suggests that the asset has superior risk-adjusted returns when considering downside volatility.
Omega Ratio:
The Omega Ratio measures the probability-weighted ratio of gains to losses beyond a certain threshold or target return. It assesses the skewed nature of an asset's returns by differentiating between positive and negative returns and assigning more weight to extreme gains or losses. The Omega Ratio provides insights into the potential asymmetry of returns, highlighting the potential for significant positive or negative outliers. A higher Omega Ratio indicates a higher probability of achieving large positive returns compared to large negative returns.
Utility:
Performance Evaluation: Provides assessment of an asset's performance, considering both returns and risk factors.
Risk Comparison: Allows for comparing the risk-adjusted returns of different assets or portfolios. Helps identify investments with better risk-reward trade-offs.
Risk Management: Assists in managing risk exposure by evaluating downside risks and volatility.
XAUXXXThis simple script is meant to get around the limitations some data providers have, in terms of the length of historical data they choose to provide traders. Inspired by OANDA's XAUCAD pair only having data as far back as 2005, whereas XAUUSD has data back to to the 19th century.
By taking the OHLC data from XAUUSD and multiplying it by the price of USD in a desired currency you are able to see further back in time, the limitation now being the length of FX data available instead of the price of Precious metal / currency pair. As shown in the chart you can now see the price of Gold in CAD as far back as the late 1960s, a nearly half century of data uncovered for all to see!
Monthly Strategy Performance TableWhat Is This?
This script code adds a Monthly Strategy Performance Table to your Pine Script strategy scripts so you can see a month-by-month and year-by-year breakdown of your P&L as a percentage of your account balance.
The table is based on realized equity rather than open equity, so it only updates the metrics when a trade is closed.
That's why some numbers will not match the Strategy Tester metrics (such as max drawdown), as the Strategy Tester bases metrics like max drawdown on open trade equity and not realized equity (closed trades).
The script is still a work-in-progress, so make sure to read the disclaimer below. But I think it's ready to release the code for others to play around with.
How To Use It
The script code includes one of my strategies as an example strategy. You need to replace my strategy code with your own. To do that just copy the source code below into a blank script, delete lines 11 -> 60 and paste your strategy code in there instead of mine. The script should work with most systems, but make sure to read the disclaimer below.
It works best with a significant amount of historical data, so it may not work very effectively on intraday timeframes as there is a severe limitation of available bars on TradingView. I recommend using it on 4HR timeframes and above, as anything less will produce very little usable data. Having a premium TradingView plan will also help boost the number of available bars.
You can hover your mouse over a table cell to get more information in the form of tooltips (such as the Long and Short win rate if you hover over your total return cell).
Credit
The code in this script is based on open-source code originally written by QuantNomad, I've made significant changes and additions to the original script but all credit for the idea and especially the display table code goes to them - I just built on top of it:
Why Did I Make This?
None of this is trading or investment advice, just my personal opinion based on my experience as a trader and systems developer these past 6+ years:
The TradingView Strategy Tester is severely limited in some important ways. And unless you use complex Excel formulas on exported test data, you can't see a granular perspective of your system's historical performance.
There is much more to creating profitable and tradeable systems than developing a strategy with a good win rate and a good return with a reasonable drawdown.
Some additional questions we need to ask ourselves are:
What did the system's worst drawdown look like?
How long did it last?
How often do drawdowns occur, and how quickly are they typically recovered?
How often do we have a break-even or losing month or year?
What is our expected compounded annual growth rate, and how does that growth rate compare to our max drawdown?
And many more questions that are too long to list and take a lifetime of trading experience to answer.
Without answering these kinds of questions, we run the risk of developing systems that look good on paper, but when it comes to live trading, we are uncomfortable or incapable of enduring the system's granular characteristics.
This Monthly Performance Table script code is intended to help bridge some of that gap with the Strategy Tester's limited default performance data.
Disclaimer
I've done my best to ensure the numbers this code outputs are accurate, and according to my testing with my personal strategy scripts it appears to work fine. But there is always a good chance I've missed something, or that this code will not work with your particular system.
The majority of my TradingView systems are extremely simple single-target systems that operate on a closed-candle basis to minimize many of the data reliability issues with the Strategy Tester, so I was unable to do much testing with multiple targets and pyramiding etc.
I've included a Debug option in the script that will display important data and information on a label each time a trade is closed. I recommend using the Debug option to confirm that the numbers you see in the table are accurate and match what your strategy is actually doing.
Always do your own due diligence, verify all claims as best you can, and never take anyone's word for anything.
Take care, and best of luck with your trading :)
Kind regards,
Matt.
PS. If you're interested in learning how this script works, I have a free hour-long video lesson breaking down the source code - just check out the links below this script or in my profile.
Advanced Choppiness Indicator with CPMA"The Advanced Choppiness Indicator with CPMA is a technical analysis tool designed to assist traders in identifying choppy market conditions and determining trend direction. It combines two key components: the Choppiness Index and a Custom Price Moving Average (CPMA).
The Choppiness Index is calculated using the Average True Range (ATR), which measures market volatility. It compares the ATR to the highest high and lowest low over a specified period. A higher Choppiness Index value indicates choppier market conditions, while a lower value suggests smoother and more directional price movements.
The CPMA is a custom moving average that takes into account various price types, including the close, high, low, and other combinations. It calculates the average of these price types over a specific length. The CPMA provides a smoother trend line that can help identify support and resistance levels more accurately than traditional moving averages.
When using this indicator, pay attention to the following elements:
Yellow range boxes: These indicate choppy zones, where market conditions are characterized by low momentum and erratic price action. Avoid entering trades during these periods.
Histogram bars: Green bars suggest an uptrend, while red bars indicate a downtrend. These bars are based on the CPMA and can help confirm the prevailing trend direction.
CPMA angle: The angle of the CPMA line provides further insight into the trend. A positive angle indicates an uptrend, while a negative angle suggests a downtrend.
Choppiness thresholds: The indicator includes user-defined thresholds for choppiness. Values above the high threshold indicate high choppiness, while values below the low threshold suggest low choppiness.
Trade decisions: Consider the information provided by the indicator to make informed trading decisions. Avoid trading during choppy zones and consider entering trades in the direction of the prevailing trend.
Remember that the indicator's parameters, such as ATR length and CPMA length, can be adjusted to suit your trading preferences and timeframe. However, it's important to use this indicator in conjunction with other technical analysis tools and your trading strategy for comprehensive market analysis."
By combining the Choppiness Index, CPMA, and other visual cues, this indicator aims to help traders identify suitable trading conditions and make more informed decisions based on market trends and volatility.
Lot Size CalculatorThis is a public release of my Lot Size Calculator. I received a request for the code from a user so I am republishing the script so I can make it public (TV doesn't seem to give me the option to simply make it public once published ).
This is a very simple script to use. Simply choose your entry level and stop level on the chart and the indicator will calculate the lots. You can change your account risk and base currency units in the settings along with changing the scaling of the calculation to adjust the results with the lot sizing units of your broker. This allows the calculator to be used with CFDs, forex, Gold, etc.. Hope it helps in your trading it has been the single most useful tool in my trading as it has helped me always keep my risk locked up and on point that is why I released it.
One final quick note: Remember you can save your settings for your own account size and risk so you do not always have to modify the defaults when loading the script. Just a ease of use tip. I only add the script to my chart when I am about to take a trade so it is helpful to have everything set up in advance.
SMT Divergences [LuxAlgo]The SMT Divergences indicator highlights SMT divergences between the chart symbol and two user-selected tickers (ES and YM by default).
A dashboard returning the SMT divergences statistics is also provided within the settings.
🔶 SETTINGS
Swing Lookback: Calculation window used to detect swing points.
Comparison Ticker: If enabled, will detect SMT divergences between the chart prices and the prices of the selected ticker.
🔹 Dashboard
Show Dashboard: Displays statistics dashboard on the chart.
Location: Location of the dashboard on the chart.
Size: Size of the displayed dashboard.
🔶 USAGE
SMT Divergences are characterized by diverging swing points between two securities.
The detection of SMT Divergences is performed by detecting swing points using the user chart prices as well as the prices of the selected external tickers. If a swing point on the chart ticker is detected at the same time on external tickers, comparison is performed.
Due to the detection requiring swing point confirmation (3 candles by default), this indicator can better be used to study price behaviors on the occurrence of an SMT divergence.
The dashboard highlights the number of SMT divergences that occurred on a swing high and swing low between the chart ticker and the selected external tickers.
The returned percentage indicates the proportion of swing highs or swing lows that led to an SMT divergence.
Draw Line For High Low Custom Range Interactive█ OVERVIEW
This indicator is an educational indicator to make pine coders easier to how to use interactive inputs with User-Defined Type (UDT) especially when dealing input.time.
█ NOTES
This indicator is not perfect but it is a good starting point or template to start develop custom range interactive indicator.
█ INSPIRATIONS
ABC 123 Harmonic Ratio Custom Range Interactive
XABCD Harmonic Pattern Custom Range Interactive
PriceTimeInteractive
█ CREDITS
CAGR Custom Range
Pine scripts are now interactive
█ FEATURES
1. High Low points are determined based on points selected.
2. Line will be drawn after points are correctly arranged.
3. Label show error once wrong point is selected, move the point as instructed in example.
█ EXAMPLES / USAGE
Scalping Strategy (5min)This indicator is designed for scalping strategies on a 5-minute timeframe. It generates signals based on two RSI crossovers and incorporates moving averages to identify trends. Additionally, a Bollinger Band is included to eliminate the need for an additional Bollinger Band on the chart.
Please note that this indicator does not guarantee 100% accurate signals and may produce false signals. It is recommended to use this indicator in conjunction with other indicators such as Stochastic, MACD, SuperTrend, or any other suitable indicators to enhance the accuracy of trading decisions.
1) Signal Generation: The indicator generates buy and sell signals based on two RSI crossovers. A buy signal is generated when the fast RSI crosses above the slow RSI, indicating potential bullish momentum. Conversely, a sell signal is generated when the fast RSI crosses below the slow RSI, suggesting potential bearish momentum.
2) To adjust the indicator to your specific chart and trading preferences, you have the flexibility to modify the RSI and moving average (MA) values. By changing the RSI values (slow RSI length and fast RSI length), you can fine-tune the sensitivity of the RSI crossovers to suit different timeframes and market conditions. Similarly, adjusting the MA values (slow MA period and fast MA period) allows you to adapt the indicator to the desired trend identification and short-term trend confirmation.
3) Pay attention to trades that are confirmed by the short-term moving average (MA) aligning with the desired direction. For buy signals, ensure that the short MA is tending upward, indicating a potential uptrend. For sell signals, confirm that the short MA is trending downward, suggesting a potential downtrend.
4) Moving Averages: The indicator uses a 200-period moving average (MA) to identify the overall trend and a short-term MA for additional confirmation.
5) Bollinger Band: The included Bollinger Band is not directly used in the indicator's calculations. However, it is provided for convenience so that users don't need to add another Bollinger Band to their chart separately.
6) Exercise caution when the short MA is below the 200-period MA but showing signs of attempting an upward move. These situations may indicate a potential reversal or consolidation, and it is advisable to avoid taking trades solely based on the 200-period MA crossover in such cases.
Remember that these guidelines are intended to provide additional insights and should be used in combination with your trading judgment and analysis.
Pi - Intraday High-Low Predictor
Pi - Intraday High-Low Predictor
This is not my Strategy/Research , I've just coded it into a indicator.
I found it interesting & useful so I'm sharing it here.
This Strategy/Research is by Kshirod Chandra Mohanty ( y-o-u-t-u-b-e : Trade with IITIAN )
You can watch his video on y-o-u-t-u-b-e for more info on this one.
the video has following title :
"1Cr Paid Strategy For Free || 10000 Subscribers Special Giveaway || How to find Day High or Low"
This will not tell you which is day high or day low, but it will help you to predict the day high from a day low and day low from a day high.
It will give you a possible range to which the prices could move to.
He has explained/used this on Banknifty.
How to Find out Day High from Day Low & Day Low from Day High :-
He uses the value of Pi (3.14) and the Range of 1st 5minute candle to find out the possible highs from day low and the possible lows from day high.
Range = value of Pi * 1st 5minutes Range
Small range = Range / 2
Large range = Range + Small range
so to find out the possible lows from day high we do following calculations
Small range low = day high - Small range
Range low = day high - Range
Large range low = day high - Large range
and to find out the possible highs from day low we do following calculations
Small range high = day low + Small range
Range high = day low + Range
Large range high = day low + Large range
Note :- This Indicator does Repaint in following ways,
As the script uses the Day High to predict the possible lows ,
so if it's an up-trending day and price keeps on making new High's then the ranges for lows will keep on changing.
similarly the script uses the Day Low to predict the possible high's ,
so if it's an down-trending day and price keeps on making new Low's then the ranges for highs will keep on changing.
My observations / thoughts about this :-
This script does not provide buy/sell recommendations. it just provides possible ranges to where prices can go from Day-High & Day-Low.
It's better to avoid trading when the price is trading between the Small range high & Small range low levels.
As it has high probability that it will be a range bound day and price will stay in between those two levels.
There is a high probability that it will be a trending day if price breaks either the Small range high/low ,
then the price could move to Range low/high.
If price breaks from Range High/Low then there is a high probability that it will be a trending day and the price could move to Large Range low/high.
Note :- If you want to use this on instruments/scripts/indexes which are active for large session such as forex/cryptos , then i suggest that you use the Opening Range period of 4Hours i.e 240minutes, to get better results.
using the default setting of 5minutes will not give good results on them.
play around with this value to find out which one suits that instrument/script/index the best.
Don't trust these levels blindly, do backtest or live testing of this then use for real trade if you want.
Use Price action near these levels to make any trading decision's.
The script provides following options :
1. Option to display Ranges in a Table (which you can enable/hide as you wish)
You can set the Table's location, size , background color & text color according to your preference.
2. Option to enable/hide Predicted-Highs from Day-Low on chart.
3. Option to enable/hide Predicted-Lows from Day-High on chart.
4. Option to set the Opening range period - here you can select your preferred opening range for calculation purpose.
5. Option to enable/hide historical levels on chart.
6. Options to customize the colors & line styles for lines.
7. Options to customize the colors , position & size for labels.
Farzan Paid CaliburnFarzan Paid Caliburn is used to identify trends and smoothen out price fluctuations. It was derived from the candlestick charting techniques, and it is based on open, high, low and close prices from the previous session
The Farzan Paid Caliburn indicator is plotted as a candlestick chart with a series of Blue and Black candles. The Blue candles indicate an uptrend while Black candles indicate a downtrend.
The Farzan Paid Caliburn indicator is a trend-following indicator that helps traders identify the direction of the current market trend.
To use this Farzan Paid Caliburn indicator you need to follow these steps :-
*1.Open the chart of a particular stock you want to trade.
*2.Fix the time interval of 10 minutes for the intraday trading. For that, you can use Tradingview charts.
*3.Insert the Farzan Paid Caliburn as your indicator.
The Farzan Paid Caliburn is shown under the main chart and their plots indicate the current trend. Farzan Paid Caliburn indicator can be used with varying periods (daily, weekly, intraday etc.) and on varying instruments (stocks, futures or forex) .
My personal preference is to use the Indicator on Weekly chart for best result.
Non Adaptive Moving Average - Quan DaoThis Non-Adaptive Moving Average (NAMA) is my origin work. It came from the issues that I always face when using existing famous MA like EMA or RMA:
- What length should I choose for the MA for this security?
- Is there a length that works for multiple timeframes?
- Is there a length that works for multiple securities in multiple markets?
Choosing the right length for an MA is a tedious and boring work and is very subjective. One day in early 2023, I decided to create a new MA that will not be dependant a lot (non-adaptive) on the length of it, to make my life a little bit easier. The idea came from the formula of EMA and RMA:
ma = alpha * src + (1 - alpha) * ma
in which,
alpha = 1 / length for RMA
alpha = 2 / (length + 1) for EMA
I decided to use a constant alpha for the formula, which happened to be: 1.618 / 100 (i.e., golden ratio / 100)
This NAMA is using the length in the start only, after running for a while the MA value will be the same for every value of its length, which resolves good my 3 questions above.
The application of this NAMA is wide, I think.
- It can be used like a normal MA but you don't have to choose its length anymore.
- It can be used like EMA in DEMA, TEMA (I called it DNAMA, TNAMA)
- It can be used in calculating some famous indicators (RSI, TR, ...) so that these indicators will not be dependant on the length as well
In this example script, I included an EMA (in blue color) as well so that you can see how the EMA changes and NAMA stays the same when changing the value of its Length.