Weighted Fourier Transform: Spectral Gating & Main Frequency🙏🏻 This drop has 2 purposes:
1) to inform every1 who'd ever see it that Weighted Fourier Tranform does exist, while being available nowhere online, not even in papers, yet there's nothing incredibly complicated about it, and it can/should be used in certain cases;
2) to show TradingView users how they can use it now in dem endevours, to show em what spectral filtering is, and what can they do with all of it in diy mode.
... so we gonna have 2 sections in the description
Section 1: Weighted Fourier Transform
It's quite easy to include weights in Fourier analysis: you just premultiply each datapoint by its corresponding weight -> feed to direct Fourier Transform, and then divide by weights after inverse Fourier transform. Alternatevely, in direct transform you just multiply contributions of each data point to the real and imaginary parts of the Fourier transform by corresponding weights (in accumulation phase), and in inverse transform you divide by weights instead during the accumulation phase. Everything else stays the same just like in non-weighted version.
If you're from the first target group let's say, you prolly know a thing or deux about how to code & about Fourier Transform, so you can just check lines of code to see the implementation of Weighted Discrete version of Fourier Transform, and port it to to any technology you desire. Pine Script is a developing technology that is incredibly comfortable in use for quant-related tasks and anything involving time series in general. While also using Python for research and C++ for development, every time I can do what I want in Pine Script, I reach for it and never touch matlab, python, R, or anything else.
Weighted version allows you to explicetly include order/time information into the operation, which is essential with every time series, although not widely used in mainstream just as many other obvious and right things. If you think deeply, you'll understand that you can apply a usual non-weighted Fourier to any 2d+ data you can (even if none of these dimensions represent time), because this is a geometric tool in essence. By applying linearly decaying weights inside Fourier transform, you're explicetly saying, "one of these dimensions is Time, and weights represent the order". And obviously you can combine multiple weightings, eg time and another characteristic of each datum, allows you to include another non-spatial dimension in your model.
By doing that, on properly processed (not only stationary but Also centered around zero data), you can get some interesting results that you won't be able to recreate without weights:
^^ A sine wave, centered around zero, period of 16. Gray line made by: DWFT (direct weighted Fourier transform) -> spectral gating -> IWFT (inverse weighted Fourier transform) -> plotting the last value of gated reconstructed data, all applied to expanding window. Look how precisely it follows the original data (the sine wave) with no lag at all. This can't be done by using non-weighted version of Fourier transform.
^^ spectral filtering applied to the whole dataset, calculated on the latest data update
And you should never forget about Fast Fourier Transform, tho it needs recursion...
Section 2: About use cases for quant trading, about this particular implementaion in Pine Script 6 (currently the latest version as of Friday 13, December 2k24).
Given the current state of things, we have certain limits on matrix size on TradingView (and we need big dope matrixes to calculate polynomial regression -> detrend & center our data before Fourier), and recursion is not yet available in Pine Script, so the script works on short datasets only, and requires some time.
A note on detrending. For quality results, Fourier Transform should be applied to not only stationary but also centered around zero data. The rightest way to do detrending of time series
is to fit Cumulative Weighted Moving Polynomial Regression (known as WLSMA in some narrow circles xD) and calculate the deltas between datapoint at time t and this wonderful fit at time t. That's exactly what you see on the main chart of script description: notice the distances between chart and WLSMA, now look lower and see how it matches the distances between zero and purple line in WFT study. Using residuals of one regression fit of the whole dataset makes less sense in time series context, we break some 'time' and order rules in a way, tho not many understand/cares abouit it in mainstream quant industry.
Two ways of using the script:
Spectral Gating aka Spectral filtering. Frequency domain filtering is quite responsive and for a greater computational cost does not introduce a lag the way it works with time-domain filtering. Works this way: direct Fourier transform your data to get frequency & phase info -> compute power spectrum out of it -> zero out all dem freqs that ain't hit your threshold -> inverse Fourier tranform what's left -> repeat at each datapoint plotting the very first value of reconstructed array*. With this you can watch for zero crossings to make appropriate trading decisions.
^^ plot Freq pass to use the script this way, use Level setting to control the intensity of gating. These 3 only available values: -1, 0 and 1, are the general & natural ones.
* if you turn on labels in script's style settings, you see the gray dots perfectly fitting your data. They get recalculated (for the whole dataset) at each update. You call it repainting, this is for analytical & aesthetic purposes. Included for demonstration only.
Finding main/dominant frequency & period. You can use it to set up Length for your other studies, and for analytical purposes simply to understand the periodicity of your data.
^^ plot main frequency/main period to use the script this way. On the screenshot, you can see the script applied to sine wave of period 16, notice how many datapoints it took the algo to figure out the signal's period quite good in expanding window mode
Now what's the next step? You can try applying signal windowing techniques to make it all less data-driven but your ego-driven, make a weighted periodogram or autocorrelogram (check Wiener-Khinchin Theorem ), and maybe whole shiny spectrogram?
... you decide, choice is yours,
The butterfly reflect the doors ...
∞
อินดิเคเตอร์และกลยุทธ์
Scatter Plot with Symbol or Data Source InputsDescription of setting items
Use Symbol for X Data?
Type: Checkbox (input.bool)
Explanation: Selects whether the data used for the X axis is obtained from a “symbol” or a “data source”.
If true: data for the X axis will be taken from a symbol (e.g. stock ticker).
If false: X axis data will be taken from the specified data source (e.g., closing price or volume).
Use Symbol for Y Data?
type: checkbox (input.bool)
Explanation: Selects whether the data used for the Y axis is retrieved from a “symbol” or a “data source”.
If true: Y-axis data is obtained from symbols.
If false: Data for the Y axis is obtained from the specified data source.
Select Ticker Symbol for X Data
type: symbol input (input.symbol)
description: selects the symbol to be used for the X axis (default is “AAPL”).
If “Use Symbol for X Data?” is set to true, this symbol will be used as the data for the X axis.
Select Ticker Symbol for Y Data
Type: Symbol input (input.symbol)
description: selects the symbol to be used for the Y axis (default is “GOOG”).
If “Use Symbol for Y Data?” is set to true, this symbol will be used as the data for the Y axis.
X Data Source
type: data source input (input.source)
description: specifies the data source to be used for the X axis.
Default is “close” (closing price).
Other possible values include open, high, low, volume, etc.
Y Data Source
Type: data source input (input.source)
Description: Specifies the data source to be used for the Y axis.
Default is “volume” (volume).
Other possible values include open, high, low, close, etc.
X Offset
type: integer input (input.int)
description: sets the offset value of the X axis.
This shifts the position of the X axis on the grid. The range is from -500 to 500.
Y Offset
Type: Integer input (constant)
description: offset value for y-axis.
Defaults to 0, but can be changed to adjust the Y axis position.
grid_width
type: integer input (input.int)
description: sets the width of the grid.
The default is 200. Increasing the value results in a finer grid.
grid_height
type: integer input (input.int)
description: sets the height of the grid.
Defaults to 200. Increasing the value results in a finer grid.
Frequency of updates
type: integer input (input.int)
description: set frequency of updates.
The higher the frequency of updates, the more bars will be used to calculate minimum and maximum values.
X Tick Interval
type: integer input (input.int)
description: sets the tick interval for the X axis.
The default is 10. To increase the number of ticks, decrease the value.
Y Tick Interval
Box border color
type: select color (input.color)
description: select color for grid box border
Default is blue.
Explanation of usage
To use symbol data: Set Use Symbol for X Data?
When “Use Symbol for X Data?” and “Use Symbol for Y Data?” are set to true, the data of the specified symbol is displayed on each axis. For example, you can use “AAPL” (Apple's stock price data) for the X axis and “GOOG” (Google's stock price data) for the Y axis.
To set the symbol, select the desired ticker in Select Ticker Symbol for X Data and Select Ticker Symbol for Y Data.
To use a data source: select the
You can set Use Symbol for X Data? and Use Symbol for Y Data? to false and use the data source specified in X Data Source or Y Data Source instead (e.g., closing price or volume).
Change Grid Size:.
Set the width and height of the grid with grid_width and grid_height. Larger values allow for more detailed scatter plots.
Set Tick Intervals: Set the X Tick Interval and Y Tick Interval.
Adjust X Tick Interval and Y Tick Interval to change the tick spacing on the X and Y axes.
Data Range Adjustment: Adjust the Frequency of updates to change the frequency of updates.
The Frequency of updates can be changed to control how often the data range is updated. The higher this value, the more historical data is considered and displayed.
Box Color.
Box Border Color allows you to change the color of the box border.
This script is useful for visualizing different symbols and data sources, especially to show the relationship between financial data.
Caution.
Some data may exceed the memory size, but the scale is the same, so you will know most of the locations.
*I made it myself because I could not find anything to draw a scatter plot. You can also compare more than 3 pieces of data by displaying more than one scatter plot. Here is how to do it. Set X or Y as the reference data. Set the data you want to compare to the one that is not the standard. Next, set the same indicator and set the reference to another set of data you wish to compare. Now you can compare the three sets of data. It is effective to change the color of the display box to prevent the user from not knowing which is which. Thus, you should be able to compare more than 3 pieces of data, so give it a try.
Physical Levels (XAUUSD, 5$ Pricesteps)Functionality:
This indicator draws horizontal lines in the XAUUSD market at a fixed spacing of USD 5. The lines are both above and below the current market price. The number of lines is limited to optimize performance.
Use:
The indicator is particularly useful for traders who want to analyze psychological price levels, support and resistance areas, or significant price zones in the gold market. It helps to better visualize price movements and their proximity to round numbers.
How it works:
The indicator calculates a starting price based on the current price of XAUUSD, rounded to the nearest multiple of USD 5.
Starting from this starting price, evenly distributed lines are drawn up and down.
The lines are black throughout and are updated dynamically according to the current chart.
ATR/DTR with Custom Percentage DisplayThis Pine Script indicator provides a detailed view of the Average True Range (ATR) and Daily True Range (DTR), along with additional calculated metrics to assist in analyzing price volatility. The key features of the indicator include:
ATR Calculation:
The ATR is calculated over a user-defined timeframe, allowing traders to assess average market volatility over a specific period.
DTR Calculation:
The DTR represents the absolute range (high - low) of the current or chosen timeframe, providing insights into the day's price movement.
ATR/DTR Percentage:
This metric calculates the DTR as a percentage of the ATR, showing how the daily range compares to the average range, with dynamic coloring to highlight when it exceeds a user-defined threshold.
Custom Percentage of ATR:
Users can input a custom percentage to calculate and display a corresponding value of the ATR. For example, entering 15% will compute and display 15% of the ATR in the indicator’s table.
Dynamic Table Display:
The indicator outputs all these metrics in a well-organized table that is overlaid on the chart. The table includes:
ATR
DTR
ATR/DTR percentage
The user-defined percentage of ATR
Customizable Features:
Color Coding: The table dynamically changes its background color when the ATR/DTR percentage exceeds a user-defined threshold.
Placement Options: The table's position on the chart can be adjusted (e.g., bottom-right, top-center) for optimal visibility.
Use Case:
This indicator is ideal for traders who want a deeper understanding of market volatility and prefer visual representation of how current price movements compare to historical averages. It is especially useful for:
Setting volatility-based stop-loss levels.
Identifying high-volatility trading opportunities.
Tailoring strategies around price movement patterns.
VWAP SlopeThis script calculates and displays the slope of the Volume Weighted Average Price (VWAP) . It compares the current VWAP with its value from a user-defined lookback period to determine the slope. The slope is color-coded: green for an upward trend (positive slope) and red for a downward trend (negative slope) .
Key Points:
VWAP Calculation: The script calculates the VWAP based on a user-defined timeframe (default: daily), which represents the average price weighted by volume.
Slope Determination: The slope is calculated by comparing the current VWAP to its value from a previous period, providing insight into market trends.
Color-Coding: The slope line is color-coded to visually indicate the market direction: green for uptrend and red for downtrend.
This script helps traders identify the direction of the market based on VWAP , offering a clear view of trends and potential turning points.
VWAP - TrendThis Pine Script calculates the Volume Weighted Average Price (VWAP) for a specified timeframe and plots its Linear Regression over a user-defined lookback period . The regression line is color-coded: green indicates an uptrend and red indicates a downtrend. The line is broken at the end of each day to prevent it from extending into the next day, ensuring clarity on a daily basis.
Key Features:
VWAP Calculation: The VWAP is calculated based on a selected timeframe, providing a smoothed average price considering volume.
Linear Regression: The script calculates a linear regression of the VWAP over a custom lookback period to capture the underlying trend.
Color-Coding: The regression line is color-coded to easily identify trends—green for an uptrend and red for a downtrend.
Day-End Break: The regression line breaks at the end of each day to prevent continuous plotting across days, which helps keep the analysis focused within daily intervals.
User Inputs: The user can adjust the VWAP timeframe and the linear regression lookback period to tailor the indicator to their preferences.
This script provides a visual representation of the VWAP trend, helping traders identify potential market directions and turning points based on the linear regression of the VWAP.
Breakout Point Highlighting//@version=6
indicator("Breakout Point Highlighting", overlay=true)
// Input: Lookback period for finding breakout points
lookbackPeriod = input.int(20, title="Lookback Period", minval=1)
// Calculate the highest high and lowest low over the lookback period
highestHigh = ta.highest(high, lookbackPeriod)
lowestLow = ta.lowest(low, lookbackPeriod)
// Breakout conditions: price breaks above the highest high or below the lowest low
breakoutUp = close > highestHigh
breakoutDown = close < lowestLow
// Plot the breakout points
plotshape(breakoutUp, color=color.green, style=shape.triangleup, location=location.belowbar, title="Breakout Up", size=size.small)
plotshape(breakoutDown, color=color.red, style=shape.triangledown, location=location.abovebar, title="Breakout Down", size=size.small)
// Highlight the breakout zones
bgcolor(breakoutUp ? color.new(color.green, 90) : na, title="Breakout Up Highlight")
bgcolor(breakoutDown ? color.new(color.red, 90) : na, title="Breakout Down Highlight")
// Alert conditions
alertcondition(breakoutUp, title="Breakout Up Alert", message="Price has broken above the highest high.")
alertcondition(breakoutDown, title="Breakout Down Alert", message="Price has broken below the lowest low.")
Moving Average Cross; Linear RegressionThis Pine Script is designed to display smoothed linear regression lines on a chart, with an option to adjust the regression period lengths and smoothing factor. The script calculates short-term and long-term linear regression lines based on the selected timeframe. These regression lines act as a regressed moving average cross , visually representing the interaction between the two smoothed linear regressions.
Short Regression Line: A linear regression line based on a short lookback period, colored blue for an uptrend and orange for a downtrend .
Long Regression Line: A linear regression line based on a longer lookback period, similarly colored blue for an uptrend and orange for a downtrend .
The script provides input options to adjust:
The length of short and long regression periods.
The smoothing length for the regression lines.
The timeframe for the linear regression calculations.
This tool can help traders observe the crossovers between the two smoothed linear regression lines, which are similar to moving average crossovers, but with the added benefit of regression-based smoothing to reduce noise. The color-coding allows for easy trend identification, with blue indicating an uptrend and orange indicating a downtrend.
Custom ChoCH Indicator (10m) - SayajeeCustom ChoCH Indicator (10m) - Sayajee
This custom Pine Script indicator identifies and marks Change of Character (ChoCH) events on a 10-minute chart. ChoCH is a price action concept that highlights potential market reversals. The indicator detects bullish and bearish Change of Character points and displays them as labels and background color highlights on the chart.
Features:
Bullish & Bearish ChoCH Signals: Detects price reversals and trends based on the relationship between recent highs and lows.
Bullish ChoCH: When the close price is greater than the previous swing high and the previous low is lower than the previous swing low.
Bearish ChoCH: When the close price is lower than the previous swing low and the previous high is greater than the previous swing high.
Visual Indicators:
Labels ("ChoCH↑" for bullish, "ChoCH↓" for bearish) are displayed at the high or low of the bar where the signal occurs.
Background highlights in green for bullish and red for bearish conditions to make the signals easily recognizable.
Customization:
Option to toggle the visibility of labels.
Option to customize the colors for bullish and bearish signals.
Alerts: Configured alert conditions to notify you when a Bullish ChoCH or Bearish ChoCH occurs.
Inputs:
Show Labels for ChoCH: Toggle to display ChoCH labels on the chart.
Bullish ChoCH Color: Choose the color for bullish signals.
Bearish ChoCH Color: Choose the color for bearish signals.
Usage:
This indicator is useful for detecting potential trend reversals and market shifts, especially when combined with other technical analysis tools. It's designed for traders who rely on price action and prefer visual cues to make informed decisions.
Multi TimeFrame OHLC Overlay @MaxMaseratiMulti TimeFrame OHLC Overlay @MaxMaserati
A powerful and versatile indicator that displays OHLC (Open, High, Low, Close) data across multiple timeframes with enhanced visualization features. Perfect for traders who need to analyze price action across different time periods simultaneously.
Key Features:
Customizable multi-timeframe OHLC visualization with box and line overlays
Extended OHLC lines from higher timeframes with clear labeling
Distinct bullish and bearish candle representations
Fully configurable color schemes and display options
Real-time timeframe information display
Main Components:
Multi-Timeframe Display
Primary timeframe OHLC visualization with boxes and lines
Extended timeframe overlay for broader market context
Clear visual distinction between timeframes
Customizable Visuals
Separate color settings for bullish and bearish patterns
Adjustable transparency for both body and wick components
Configurable OHLC line colors and visibility
Extended Lines Features
Higher timeframe OHLC level overlay
Custom labels with timeframe identification
Adjustable line properties and visibility
Information Display
Current timeframe indicator
Extended timeframe reference
Clean and unobtrusive interface
Settings Groups:
Extended OHLC Lines
Labels Options
Display Options
Bullish/Bearish Candle Settings
OHLC Lines Configuration
Usage Tips:
Start with the default 240-minute timeframe or adjust to your preferred interval
Use the extended lines feature to view higher timeframe levels
Customize colors and transparency to match your chart theme
Enable/disable specific components based on your analysis needs
Perfect For:
Multi-timeframe analysis
Support/Resistance identification
Price action trading
Trend following strategies
Market structure analysis
This indicator combines powerful multi-timeframe analysis capabilities with clean visualization, making it an essential tool for traders who need to maintain awareness of price action across different time periods.
Note:
For optimal performance, adjust the visual settings according to your chart's timeframe and color scheme. The indicator is designed to work seamlessly across all trading instruments and timeframes.
DemaRSI StrategyThis is a repost to a old script that cant be updated anymore, the request was made on Feb, 27, 2016.
Here's a engaging description for the tradingview script:
**DemaRSI Strategy: A Proven Trading System**
Join thousands of traders who have already experienced the power of this highly effective strategy. The DemaRSI system combines two powerful indicators - DEMA (Double Exponential Moving Average) and RSI (Relative Strength Index) - to generate profitable trades with minimal risk.
**Key Features:**
* **Trend-Following**: Our algorithm identifies strong trends using a combination of DEMA and RSI, allowing you to ride the waves of market momentum.
* **Risk Management**: The system includes built-in stop-loss and take-profit levels, ensuring that your gains are protected and losses are minimized.
* **Session-Based Trading**: Trade during specific sessions only (e.g., London or New York) for even more targeted results.
* **Customizable Settings**: Adjust the length of moving averages, RSI periods, and other parameters to suit your trading style.
**What You'll Get:**
* A comprehensive strategy that can be used with any broker or platform
* Easy-to-use interface with customizable settings
* Real-time performance metrics and backtesting capabilities
**Start Trading Like a Pro Today!**
This script is designed for intermediate to advanced traders who want to take their trading game to the next level. With its robust risk management features, this strategy can help you achieve consistent profits in various market conditions.
**Disclaimer:** This script is not intended as investment advice and should be used at your own discretion. Trading carries inherent risks, and losses are possible.
~Llama3
MicuRobert EMA Cross StrategyThis is a repost of a old strategy that cant be updated anymore, it was a request for a user made in Oct, 6, 2015
Here's a possible engaging description for the tradingview script:
**MicuRobert EMA Cross V2: A Powerful Trading Strategy**
Join the ranks of successful traders with this advanced strategy, designed to help you profit from market trends. The MicuRobert EMA Cross V2 combines two essential indicators - Exponential Moving Average (EMA) and Divergence EMA (DEMA) - to generate buy and sell signals.
**Key Features:**
* **Trading Session Filter**: Only trade during your preferred session, ensuring you're in sync with market conditions.
* **Trailing Stop**: Automatically adjust stop-loss levels to lock in profits or limit losses.
* **Customizable Trade Size**: Set the size of each trade based on your risk tolerance and trading goals.
**How it Works:**
The script uses two EMAs (5-period and 34-period) to identify trends. When the shorter EMA crosses above the longer one, a buy signal is generated. Conversely, when the shorter EMA falls below the longer one, a sell signal is triggered. The strategy also incorporates divergence analysis between price action and the EMAs.
**Visual Aids:**
* **EMA Plots**: Visualize the two EMAs on your chart to gauge market momentum.
* **Buy/Sell Signals**: See when buy or sell signals are generated, along with their corresponding entry prices.
* **Trailing Stop Lines**: Monitor stop-loss levels as they adjust based on price action.
**Get Started:**
Download this script and start trading like a pro! With its robust features and customizable settings, the MicuRobert EMA Cross V2 is an excellent addition to any trader's arsenal.
~Llama3
LRI Momentum Cycles [AlgoAlpha]Discover the LRI Momentum Cycles indicator by AlgoAlpha, a cutting-edge tool designed to identify market momentum shifts using trend normalization and linear regression analysis. This advanced indicator helps traders detect bullish and bearish cycles with enhanced accuracy, making it ideal for swing traders and intraday enthusiasts alike.
Key Features :
🎨 Customizable Appearance : Set personalized colors for bullish and bearish trends to match your charting style.
🔧 Dynamic Trend Analysis : Tracks market momentum using a unique trend normalization algorithm.
📊 Linear Regression Insight : Calculates real-time trend direction using linear regression for better precision.
🔔 Alert Notifications : Receive alerts when the market switches from bearish to bullish or vice versa.
How to Use :
🛠 Add the Indicator : Favorite and apply the indicator to your TradingView chart. Adjust the lookback period, linear regression source, and regression length to fit your strategy.
📊 Market Analysis : Watch for color changes on the trend line. Green signals bullish momentum, while red indicates bearish cycles. Use these shifts to time entries and exits.
🔔 Set Alerts : Enable notifications for momentum shifts, ensuring you never miss critical market moves.
How It Works :
The LRI Momentum Cycles indicator calculates trend direction by applying linear regression on a user-defined price source over a specified period. It compares historical trend values, detecting bullish or bearish momentum through a dynamic scoring system. This score is normalized to ensure consistent readings, regardless of market conditions. The indicator visually represents trends using gradient-colored plots and fills to highlight changes in momentum. Alerts trigger when the momentum state changes, providing actionable trading signals.
[blackcat]L3 Strong Power Wave █ OVERVIEW
The script is an indicator named ' L3 Strong Power Wave' (SPW) designed to identify buy and sell signals based on the contraction and expansion of candlestick patterns. It calculates various indicators and plots them on a separate chart panel. The main purpose is to detect when candlestick patterns transition from contracting to expanding (buy signal) and from expanding to contracting (sell signal).
█ LOGICAL FRAMEWORK
The script is structured into several key sections:
Input Parameters and Initialization: The script uses indicator() to define the title, short title, and other properties.
Custom Functions: Several custom functions are defined for calculations, including calculate_weighted_moving_average, calculate_spw_variation, and calculate_strong_power_wave.
Calculations: The script performs complex calculations for the SPW indicators using multiple ta.alma and ta.sma functions.
Plotting: The indicators are plotted on the chart using plot().
Signal Detection: The script detects buy and sell signals based on changes in candlestick sizes.
Labeling: Buy and sell signals are indicated on the chart using label.new().
The flow of data and logic involves first calculating the SPW indicators, then plotting them, and finally detecting and labeling the buy and sell signals based on candlestick pattern changes.
█ CUSTOM FUNCTIONS
1 — calculate_weighted_moving_average(src, length, weight) :
• Purpose: Calculates a weighted moving average of the source data.
• Parameters: src (source data), length (period length), weight (weighting factor).
• Return Value: Weighted moving average value.
2 — calculate_spw_variation(base, multiplier) :
• Purpose: Computes a variation of the base value using a simple moving average and a multiplier.
• Parameters: base (base value), multiplier (multiplier factor).
• Return Value: Calculated variation value.
3 — calculate_strong_power_wave(src) :
• Purpose: Calculates multiple SPW indicators including various ta.alma and ta.sma values.
• Parameters: src (source data, typically close).
• Return Value: A tuple containing calculated SPW indicators.
█ KEY POINTS AND TECHNIQUES
• Weighted Moving Average: The script uses a custom function to calculate a weighted moving average, which can provide more emphasis on recent data points.
• Exponential Moving Averages (ALMA): The script uses ta.alma to smooth data, which is useful for identifying trends.
• Custom Indicators: The script defines and uses multiple custom indicators, demonstrating how to create and integrate complex calculations.
• Signal Detection: The script uses logical conditions to detect buy and sell signals based on candlestick pattern changes, showcasing practical application of technical analysis concepts.
• Labeling: The use of label.new() to mark buy and sell signals provides clear visual cues on the chart.
█ EXTENDED KNOWLEDGE AND APPLICATIONS
• Enhancements: The script could be enhanced by adding additional filters or parameters to refine signal accuracy.
• Backtesting: Implementing backtesting to evaluate the effectiveness of the buy and sell signals.
• Optimization: Optimizing the parameters of the moving averages and multipliers to better suit different market conditions.
• Alternative Indicators: Exploring other indicators that could complement or replace the SPW indicators.
• Related Concepts: Understanding the principles of candlestick pattern analysis and how they can be integrated into Pine Script.
Drawdown from All-Time High (Line)This Pine Script is a **Drawdown Indicator from All-Time High** for TradingView. It calculates and plots the percentage drawdown from the highest price the asset has ever reached (the all-time high). Here's a breakdown of what this script does:
### Description:
- **Drawdown Calculation**:
- The drawdown is calculated as the difference between the current price (`close`) and the all-time high, divided by the all-time high, and multiplied by 100 to express it as a percentage.
- If the current price is higher than the previous all-time high, the all-time high is updated to the current price.
- **All-Time High Tracking**:
- The script tracks the highest price (`allTimeHigh`) that the asset has ever reached. Each time a new high is reached, the `allTimeHigh` value is updated.
- **Line Plot**:
- The drawdown percentage is then plotted as a line on the chart, with a color of **blue** for easy visualization.
- The line shows how much the price has dropped relative to its all-time high.
- **Zero Line**:
- A horizontal line is added at the **0%** level to act as a reference point, which is helpful to identify when the asset has fully recovered to its all-time high.
### Key Features:
- **Track Drawdown**: The indicator helps visualize how far the current price has fallen from its highest point, which is useful for understanding the depth of losses (drawdowns) during a period.
- **Update All-Time High**: The indicator automatically updates the all-time high whenever a new high is detected.
- **Visual Reference**: The 0% horizontal line provides a clear indication of when the asset is at its all-time high, and the drawdown is at 0%.
### How it Works:
- If the current price surpasses the all-time high, the script will reset the all-time high to the new price.
- The drawdown percentage is calculated from the current price relative to this all-time high, and it is displayed as a line on the chart.
### Visuals:
- **Drawdown Line**: Plots the percentage of the drawdown, which is the drop from the all-time high.
- **Zero Line**: A dotted horizontal line at 0% marks the level of the all-time high.
This indicator is valuable for understanding the extent of price corrections and potential recoveries relative to the historical peak of the asset. It is especially useful for traders and investors who want to assess the risk of drawdowns in relation to the highest price achieved by the asset.
C|M Capital (Market Structure Pro)CM Capital (Market Structure Pro)
Overview:
The CM Capital (Market Structure Pro) Indicator is a groundbreaking tool for traders seeking a comprehensive market analysis. This closed-source script merges multiple facets of market dynamics into a single, user-friendly interface, designed to enhance decision-making by providing a multi-dimensional view of market behavior. By combining advanced market structure detection, liquidity event identification, Fair Value Gap analysis, and session-specific insights, this indicator offers traders a strategic advantage in navigating the complexities of financial markets.
Key Functionalities:
Market Structure Insights:
Break of Structure (BOS) and Market Structure Shifts (MSS):
Methodology: Our approach uses fractal analysis coupled with custom algorithms to dissect price movements, identifying pivotal moments where market structure breaks or shifts. The script evaluates candle patterns, volume data, and price momentum to flag these events.
Customization: Users can choose between candle close or wick confirmations and select from various line styles for visualization, tailoring the sensitivity to match their trading strategy, whether it's scalping or swing trading.
Utility: These markers act as early signals for trend changes, allowing traders to prepare for potential reversals or continuations, especially useful in volatile markets where timely decisions are crucial.
Structure Strength:
Highs and Lows Definition: The 'Structure Strength' setting in this indicator directly influences the identification of structure highs and lows. It's not just about detecting market structure; it's about defining what constitutes a significant high or low based on your trading horizon.
Swing vs. Internal Structure:
Lower Strength: Opting for a lower strength setting will highlight more extreme, swing-type structures. This means the indicator will mark out only the most pronounced highs and lows, which are ideal for traders focusing on broader market swings or longer-term trends.
Higher Strength: Conversely, increasing the strength level plots more internal structure levels. This setting is perfect for traders who want to dive into the market's micro-movements, offering insights into potential support and resistance within ongoing trends, essentially capturing more reactive and detailed price action.
Strategic Application: This adjustable parameter allows traders to zoom in or out on the market structure, aligning with their trading style or the specific market conditions they're navigating. Whether you're looking to catch significant market turns or to finesse entries and exits within a trend, the structure strength setting provides the granularity needed for nuanced market analysis.
Liquidity Sweeps:
Detection: Beyond traditional price action analysis, our indicator incorporates a unique method to spot liquidity sweeps. By analyzing price movements against historical support/resistance zones, it highlights instances where significant orders might have been absorbed, suggesting areas of potential price reversal or continuation.
Visualization: Liquidity sweeps are visually marked with customizable colors and an 'X' label, making them instantly recognizable. This feature is particularly beneficial for traders looking to enter or exit trades based on market inefficiencies or anticipated institutional activity.
Application: Traders can use these signals to anticipate where the market might react strongly, either as support for entries or as a caution for exits, enhancing trade precision.
Fair Value Gaps (FVGs):
Identification: Our proprietary FVG detection algorithm looks for price discrepancies over recent bars, signaling where the market could aim to rebalance. This is not merely about spotting gaps but understanding their context within the market's flow.
Enhanced Visualization: Users can extend FVGs across the chart, providing a clearer view of potential mean reversion points or continuation levels, aiding in setting targets or stop-losses.
Strategic Use: FVGs serve as dynamic levels where traders might expect price action to revisit, offering opportunities for mean reversion trades or confirming trend strength.
Session Visualization:
Session Markers: By delineating Asia, London, and New York session times, the indicator helps traders recognize session-specific volatility, trends, and liquidity conditions. Each session can be customized for color and duration, aligning with various trading strategies.
Timeframe Correlation: Integrating session analysis with structural and liquidity insights allows for a strategy where trades are timed not just by price action but by when in the global market cycle they occur, potentially increasing the effectiveness of entry and exit points.
Watermark Display:
Personalization: Add a personal touch or brand identity to your charts with customizable text and color options for the watermark, enhancing both the aesthetic and functional aspects of your trading setup.
Originality:
This script's originality lies in its holistic approach to market analysis. The integration of these diverse yet synergistic components provides a unique toolset:
Confluence of Signals: Each element enhances the others, creating a confluence where structural changes, liquidity events, and time-based market conditions are analyzed in concert, offering a more complete trading signal than isolated indicators.
Customization for Diverse Trading Styles: From high-frequency scalping to long-term trend following, the script's flexibility caters to a broad spectrum of trading strategies by allowing adjustments in sensitivity, visualization, and application.
How to Use:
Setup: Add the script to your chart and explore the settings in the input panel. Customize the visual and functional aspects to align with your trading style.
Strategy Application:
Use BOS/MSS for trend confirmation, liquidity sweeps for entry/exit precision, FVGs for mean reversion opportunities, and session markers to time your trades optimally.
Consider combining signals for stronger trade validation; for instance, a BOS during the London session might be more significant if it coincides with a liquidity sweep and an FVG from the Asian session.
Big Money by ChartedhighsBig Money by Chartedhighs
Script Overview:
The "Big Money" indicator is designed to help traders easily identify significant price movements on their charts. This script visually highlights candles where the price change from open to close exceeds a user-defined threshold. It draws attention to these key moments, providing a clear indication of potential big-money moves in the market.
Key Features:
Customizable Threshold:
Allows users to set a specific price change threshold via the input menu (Highlight Threshold).
Only candles with a price change greater than or equal to this value are highlighted.
Candle Highlighting:
Uses color-coded bars to emphasize candles meeting the threshold condition.
Candles are highlighted in yellow for immediate visual clarity.
Dynamic Box Annotation:
Draws a semi-transparent yellow box around highlighted candles.
Extends the box dynamically to subsequent bars, providing an area of interest for continued analysis.
Labeling for Key Moments:
Automatically adds a label ("BigMoney") above highlighted bars to further indicate significant price action.
How It Works:
The script calculates the price change for each bar (close - open) and compares it to the user-defined threshold.
If the price change meets or exceeds the threshold:
The bar color changes to yellow.
A box is drawn around the candle to highlight the price movement visually.
A label is added above the candle to emphasize its significance.
The box extends dynamically until the next highlighted candle, allowing users to track zones of activity.
Customization Options:
Highlight Threshold: Modify the threshold value to suit your trading style or instrument volatility.
Use Case:
This indicator is ideal for traders looking to identify significant price movements quickly. It helps to locate areas where "big money" might be flowing into the market, offering potential entry or exit opportunities.
How to Use:
Add the "Big Money by Chartedhighs" script to your TradingView chart.
Set the Highlight Threshold to a value suitable for your market or timeframe.
Observe highlighted candles and boxes for potential trading signals or areas of interest.
This script is highly visual, intuitive, and customizable, making it a great addition to any trader's toolkit!
Multi VWAPThe Multi-VWAP Indicator is a versatile tool designed to plot up to three Volume Weighted Average Price (VWAP) lines simultaneously, each anchored to a user-defined period. This indicator provides traders with a comprehensive view of price action across multiple timeframes, making it ideal for analyzing trends, support, and resistance levels.
Key Features:
Multiple Anchoring Options:
Each VWAP can be independently anchored to one of the following periods:
Session: Resets at the start of each trading day.
Week: Resets at the start of each week.
Month: Resets at the start of each month.
Quarter: Resets at the start of each quarter.
Year: Resets at the start of each year.
User Customization:
Choose the anchoring period for each VWAP line via dropdown menus.
Assign distinct colors to each VWAP for better visual differentiation.
Dynamic Price Source:
The VWAP calculation is based on the average price (hlc3) by default but can be modified by the user to use other price inputs.
Clear Visualization:
Displays three separate VWAP lines simultaneously, helping traders identify confluences or divergences in price action across timeframes.
Use Cases:
Intraday Trading: Use session-anchored VWAP to track intraday trends and mean reversion points.
Swing Trading: Combine weekly and monthly VWAPs to identify longer-term support and resistance levels.
Multi-Timeframe Analysis: Visualize how price interacts with VWAPs from different periods to spot key zones of interest.
This indicator is a powerful tool for traders who want to incorporate VWAP into their strategies while maintaining flexibility to adapt to various market conditions.
Three Step Future-Trend [BigBeluga]Three Step Future-Trend by BigBeluga is a forward-looking trend analysis tool designed to project potential future price direction based on historical periods. This indicator aggregates data from three consecutive periods, using price averages and delta volume analysis to forecast trend movement and visualize it on the chart with a projected trend line and volume metrics.
🔵 Key Features:
Three Period Analysis: Calculates price averages and delta volumes from three specified periods, creating a consolidated view of historical price movement.
Future Trend Line Projection: Plots a forward trend line based on the calculated averag of three periods, helping traders visualize potential future price movement.
Avg Delta Volume and Future Price Label: Shows a delta average Volume a long with a Future Price label at the end of the projected trend line, indicating the possible future delta volume and future Price.
Volume Data Table: Displays a detailed table showing delta and total volume for each of the three periods, allowing quick volume comparison to support the projected trend.
This indicator provides a dynamic way to anticipate market direction by blending price and volume data, giving traders insights into both volume and trend strength in upcoming periods.
Log Regression OscillatorThe Log Regression Oscillator transforms the logarithmic regression curves into an easy-to-interpret oscillator that displays potential cycle tops/bottoms.
🔶 USAGE
Calculating the logarithmic regression of long-term swings can help show future tops/bottoms. The relationship between previous swing points is calculated and projected further. The calculated levels are directly associated with swing points, which means every swing point will change the calculation. Importantly, all levels will be updated through all bars when a new swing is detected.
The "Log Regression Oscillator" transforms the calculated levels, where the top level is regarded as 100 and the bottom level as 0. The price values are displayed in between and calculated as a ratio between the top and bottom, resulting in a clear view of where the price is situated.
The main picture contains the Logarithmic Regression Alternative on the chart to compare with this published script.
Included are the levels 30 and 70. In the example of Bitcoin, previous cycles showed a similar pattern: the bullish parabolic was halfway when the oscillator passed the 30-level, and the top was very near when passing the 70-level.
🔹 Proactive
A "Proactive" option is included, which ensures immediate calculations of tentative unconfirmed swings.
Instead of waiting 300 bars for confirmation, the "Proactive" mode will display a gray-white dot (not confirmed swing) and add the unconfirmed Swing value to the calculation.
The above example shows that the "Calculated Values" of the potential future top and bottom are adjusted, including the provisional swing.
When the swing is confirmed, the calculations are again adjusted, showing a red dot (confirmed top swing) or a green dot (confirmed bottom swing).
🔹 Dashboard
When less than two swings are available (top/bottom), this will be shown in the dashboard.
The user can lower the "Threshold" value or switch to a lower timeframe.
🔹 Notes
Logarithmic regression is typically used to model situations where growth or decay accelerates rapidly at first and then slows over time, meaning some symbols/tickers will fit better than others.
Since the logarithmic regression depends on swing values, each new value will change the calculation. A well-fitted model could not fit anymore in the future.
Users have to check the validity of swings; for example, if the direction of swings is downwards, then the dataset is not fitted for logarithmic regression.
In the example above, the "Threshold" is lowered. However, the calculated levels are unreliable due to the swings, which do not fit the model well.
Here, the combination of downward bottom swings and price accelerates slower at first and faster recently, resulting in a non-fit for the logarithmic regression model.
Note the price value (white line) is bound to a limit of 150 (upwards) and -150 (down)
In short, logarithmic regression is best used when there are enough tops/bottoms, and all tops are around 100, and all bottoms around 0.
Also, note that this indicator has been developed for a daily (or higher) timeframe chart.
🔶 DETAILS
In mathematics, the dot product or scalar product is an algebraic operation that takes two equal-length sequences of numbers (arrays) and returns a single number, the sum of the products of the corresponding entries of the two sequences of numbers.
The usual way is to loop through both arrays and sum the products.
In this case, the two arrays are transformed into a matrix, wherein in one matrix, a single column is filled with the first array values, and in the second matrix, a single row is filled with the second array values.
After this, the function matrix.mult() returns a new matrix resulting from the product between the matrices m1 and m2.
Then, the matrix.eigenvalues() function transforms this matrix into an array, where the array.sum() function finally returns the sum of the array's elements, which is the dot product.
dot(x, y)=>
if x.size() > 1 and y.size() > 1
m1 = matrix.new()
m2 = matrix.new()
m1.add_col(m1.columns(), y)
m2.add_row(m2.rows (), x)
m1.mult (m2)
.eigenvalues()
.sum()
🔶 SETTINGS
Threshold: Period used for the swing detection, with higher values returning longer-term Swing Levels.
Proactive: Tentative Swings are included with this setting enabled.
Style: Color Settings
Dashboard: Toggle, "Location" and "Text Size"
Support and Resistance LinesDraw the last 5 support and resistance lines. It works on the current timeframe. You can adjust the sensibility by changing the diff variable.
Sweep + Cement Candle Coloring with EMA hopdcCertainly! Here's an introduction for the indicator:
---
## Introduction to the Sweep + Cement Candle Coloring with EMA Indicator
The **Sweep + Cement Candle Coloring with EMA Indicator** is a powerful tool designed to enhance your technical analysis and trading strategies. This indicator combines the unique characteristics of Sweep and Cement candle patterns with the dynamic capabilities of Exponential Moving Averages (EMAs), providing traders with insightful signals for potential market movements.
### Key Features:
1. **Candle Coloring**:
- **Sweep + Cement Bullish Candles**: Highlighted in teal when the low of the current candle is lower than the previous candle, and the close is above the previous high. This indicates potential bullish momentum.
- **Sweep + Cement Bearish Candles**: Marked in red when the high of the current candle is higher than the previous candle, and the close is below the previous low, signaling possible bearish pressure.
2. **Exponential Moving Averages (EMAs)**:
- **EMA 0 (Default Length: 9)**: Provides short-term trend direction.
- **EMA 1 (Default Length: 21)** and **EMA 2 (Default Length: 50)**: Offer insights into medium and long-term trends.
- Customizable settings allow traders to adjust EMA lengths and colors based on their preferences.
3. **Trading Signals**:
- **Buy Signal**: Triggered when a bullish Sweep + Cement candle forms, EMA 1 is above EMA 2, and the price closes above all EMAs.
- **Sell Signal**: Activated with a bearish Sweep + Cement candle, EMA 1 below EMA 2, and the price closes below all EMAs.
- Visual arrows on the chart indicate buy and sell opportunities.
4. **Alerts**:
- Configurable alerts notify traders when the price touches any of the EMAs, ensuring you never miss critical levels.
- Alerts for buy and sell signals keep you informed of potential entries and exits.
### How It Benefits Traders:
This indicator is ideal for traders looking to identify and capitalize on market reversals and trend continuations. By integrating candle patterns with EMA analysis, it provides a comprehensive view of market dynamics, making it easier to spot high-probability trading opportunities.
Whether you are a beginner or an experienced trader, the Sweep + Cement Candle Coloring with EMA Indicator can be a valuable addition to your trading toolkit, helping you make informed decisions with confidence.
---
Feel free to adjust the content to better fit your audience or specific use case!
Custom Strategy: ETH Martingale 2.0Strategic characteristics
ETH Little Martin 2.0 is a self-developed trading strategy based on the Martingale strategy, mainly used for trading ETH (Ethereum). The core idea of this strategy is to place orders in the same direction at a fixed price interval, and then use Martin's multiple investment principle to reduce losses, but this is also the main source of losses.
Parameter description:
1 Interval: The minimum spacing for taking profit, stop loss, and opening/closing of orders. Different targets have different spacing. Taking ETH as an example, it is generally recommended to have a spacing of 2% for fluctuations in the target.
2 Base Price: This is the price at which you triggered the first order. Similarly, I am using ETH as an example. If you have other targets, I suggest using the initial value of a price that can be backtesting. The Base Price is only an initial order price and has no impact on subsequent orders.
3 Initial Order Amount: Users can set an initial order amount to control the risk of each transaction. If the stop loss is reached, we will double the amount based on this value. This refers to the value of the position held, not the number of positions held.
4 Loss Multiplier: The strategy will increase the next order amount based on the set multiple after the stop loss, in order to make up for the previous losses through a larger position. Note that after taking profit, it will be reset to 1 times the Initial Order Amount.
5. Long Short Operation: The first order of the strategy is a multiple entry, and in subsequent orders, if the stop loss is reached, a reverse order will be opened. The position value of a one-way order is based on the Loss Multiplier multiple investment, so it is generally recommended that the Loss Multiplier default to 2.
Improvement direction
Although this strategy already has a certain trading logic, there are still some improvement directions that can be considered:
1. Dynamic adjustment of spacing: Currently, the spacing is fixed, and it can be considered to dynamically adjust the spacing based on market volatility to improve the adaptability of the strategy. Try using dynamic spacing, which may be more suitable for the actual market situation.
2. Filtering criteria: Orders and no orders can be optimized separately. The biggest problem with this strategy is that it will result in continuous losses during fluctuations, and eventually increase the investment amount. You can consider filtering out some fluctuations or only focusing on trend trends.
3. Risk management: Add more risk management measures, such as setting a maximum loss limit to avoid huge losses caused by continuous stop loss.
4. Optimize the stop loss multiple: Currently, the stop loss multiple is fixed, and it can be considered to dynamically adjust the multiple according to market conditions to reduce risk.