[MAD] Acceleration based dampened SMA projectionsThis indicator utilizes concepts of arrays inside arrays to calculate and display projections of multiple Smoothed Moving Average (SMA) lines via polylines.
This is partly an experiment as an educational post, on how to work with multidimensional arrays by using User-Defined Types
------------------
Input Controls for User Interaction:
The indicator provides several input controls, allowing users to adjust parameters like the SMA window, acceleration window, and dampening factors.
This flexibility lets users customize the behavior and appearance of the indicator to fit their analysis needs.
sma length:
Defines the length of the simple moving average (SMA).
acceleration window:
Sets the window size for calculating the acceleration of the SMA.
Input Series:
Selects the input source for calculating the SMA (typically the closing price).
Offset:
Determines the offset for the input source, affecting the positioning of the SMA. Here it´s possible to add external indicators like bollinger bands,.. in that case as double sma this sma should be very short.
(Thanks Fikira for that idea)
Startfactor dampening:
Initial dampening factor for the polynomial curve projections, influencing their starting curvature.
Growfactor dampening:
Growth rate of the dampening factor, affecting how the curvature of the projections changes over time.
Prediction length:
Sets the length of the projected polylines, extending beyond the current bar.
cleanup history:
Boolean input to control whether to clear the previous polyline projections before drawing new ones.
Key technologies used in this indicator include:
User-Defined Types (UDT) :
This indicator uses UDT to create a custom type named type_polypaths.
This type is designed to store information for each polyline, including an array of points (array), a color for the polyline, and a dampening factor.
UDTs in Pine Script enable the creation of complex data structures, which are essential for organizing and manipulating data efficiently.
type type_polypaths
array polyline_points = na
color polyline_color = na
float dampening_factor= na
Arrays and Nested Arrays:
The script heavily utilizes arrays.
For example, it uses a color array (colorpreset) to store different colors for the polyline.
Moreover, an array of type_polypaths (polypaths) is used, which is an array consisting of user-defined types. Each element of this array contains another array (polyline_points), demonstrating nested array usage.
This structure is essential for handling multiple polylines, each with its set of points and attributes.
var type_polypaths polypaths = array.new()
Polyline Creation and Manipulation:
The core visual aspect of the indicator is the creation of polylines.
Polyline points are calculated based on a dampened polynomial curve, which is influenced by the SMA's slope and acceleration.
Filling initial dampening data
array_size = 9
middle_index = math.floor(array_size / 2)
for i = 0 to array_size - 1
damp_factor = f_calculate_damp_factor(i, middle_index, Startfactor, Growfactor)
polyline_color = colorpreset.get(i)
polypaths.push(type_polypaths.new(array.new(0, na), polyline_color, damp_factor))
The script dynamically generates these polyline points and stores them in the polyline_points array of each type_polypaths instance based on those prefilled dampening factors
if barstate.islast or cleanup == false
for damp_factor_index = 0 to polypaths.size() - 1
GET_RW = polypaths.get(damp_factor_index)
GET_RW.polyline_points.clear()
for i = 0 to predictionlength
y = f_dampened_poly_curve(bar_index + i , src_input , sma_slope , sma_acceleration , GET_RW.dampening_factor)
p = chart.point.from_index(bar_index + i - src_off, y)
GET_RW.polyline_points.push(p)
polypaths.set(damp_factor_index, GET_RW)
Polyline Drawout
The polyline is then drawn on the chart using the polyline.new() function, which uses these points and additional attributes like color and width.
for pl_s = 0 to polypaths.size() - 1
GET_RO = polypaths.get(pl_s)
polyline.new(points = GET_RO.polyline_points, line_width = 1, line_color = GET_RO.polyline_color, xloc = xloc.bar_index)
If the cleanup input is enabled, existing polylines are deleted before new ones are drawn, maintaining clarity and accuracy in the visualization.
if cleanup
for pl_delete in polyline.all
pl_delete.delete()
------------------
The mathematics
in the (ABDP) indicator primarily focuses on projecting the behavior of a Smoothed Moving Average (SMA) based on its current trend and acceleration.
SMA Calculation:
The indicator computes a simple moving average (SMA) over a specified window (sma_window). This SMA serves as the baseline for further calculations.
Slope and Acceleration Analysis:
It calculates the slope of the SMA by subtracting the current SMA value from its previous value. Additionally, it computes the SMA's acceleration by evaluating the sum of differences between consecutive SMA values over an acceleration window (acceleration_window). This acceleration represents the rate of change of the SMA's slope.
sma_slope = src_input - src_input
sma_acceleration = sma_acceleration_sum_calc(src_input, acceleration_window) / acceleration_window
sma_acceleration_sum_calc(src, window) =>
sum = 0.0
for i = 0 to window - 1
if not na(src )
sum := sum + src - 2 * src + src
sum
Dampening Factors:
Custom dampening factors for each polyline, which are based on the user-defined starting and growth factors (Startfactor, Growfactor).
These factors adjust the curvature of the projected polylines, simulating various future scenarios of SMA movement.
f_calculate_damp_factor(index, middle, start_factor, growth_factor) =>
start_factor + (index - middle) * growth_factor
Polynomial Curve Projection:
Using the SMA value, its slope, acceleration, and dampening factors, the script calculates points for polynomial curves. These curves represent potential future paths of the SMA, factoring in its current direction and rate of change.
f_dampened_poly_curve(index, initial_value, initial_slope, acceleration, damp_factor) =>
delta = index - bar_index
initial_value + initial_slope * delta + 0.5 * damp_factor * acceleration * delta * delta
damp_factor = f_calculate_damp_factor(i, middle_index, Startfactor, Growfactor)
Have fun trading :-)
Educationalposts
Selected Dates Filter by @zeusbottradingWe are presenting you feature for strategies in Pine Script.
This function/pine script is about NOT opening trades on selected days. Real usage is for bank holidays or volatile days (PPI, CPI, Interest Rates etc.) in United States and United Kingdom from 2020 to 2030 (10 years of dates of bank holidays in mentioned countries above). Strategy is simple - SMA crossover of two lengts 14 and 28 with close source.
In pine script you can see we picked US and GB bank holidays. If you add this into your strategy, your bot will not open trades on those days. You must make it a rule or a condition. We use it as a rule in opening long/short trades.
You can also add some of your prefered dates, here is just example of our idea. If you want to add your preffered days you can find them on any site like forexfactory, myfxbook and so on. But don’t forget to add function “time_tradingday ! = YourChoosedDate” as it is writen lower in the pine script.
Sometimes the date is substituted for a different day, because the day of the holiday is on Saturday or Sunday.
Made with ❤️ for this community.
If you have any questions or suggestions, let us know.
The script is for informational and educational purposes only. Use of the script does not constitutes professional and/or financial advice. You alone the sole responsibility of evaluating the script output and risks associated with the use of the script. In exchange for using the script, you agree not to hold zeusbottrading TradingView user liable for any possible claim for damages arising from any decision you make based on use of the script.
Short Swing Bearish MACD Cross (By Coinrule)This strategy is oriented towards shorting during downside moves, whilst ensuring the asset is trading in a higher timeframe downtrend, and exiting after further downside.
This script can work well on coins you are planning to hodl for long-term and works especially well whilst using an automated bot that can execute your trades for you. It allows you to hedge your investment by allocating a % of your coins to trade with, whilst not risking your entire holding. This mitigates unrealised losses from hodling as it provides additional cash from the profits made. You can then choose to hodl this cash, or use it to reinvest when the market reaches attractive buying levels. Alternatively, you can use this when trading contracts on futures markets where there is no need to already own the underlying asset prior to shorting it.
ENTRY
This script utilises the MACD indicator accompanied by the Exponential Moving Average (EMA) 450 to enter trades. The MACD is a trend following momentum indicator and provides identification of short-term trend direction. In this variation it utilises the 11-period as the fast and 26-period as the slow length EMAs, with signal smoothing set at 9.
The EMA 450 is used as additional confirmation to prevent the script from shorting when price is above this long-term moving average. Once price is above the EMA 450 the script will not open any shorts - preventing the rule from attempting to short uptrends. Due to this, this strategy is ideal for setting and forgetting.
The script will enter trades based on two conditions:
1) When the MACD signals a bearish cross. This occurs when the EMA 11 crosses below the EMA 26 within the MACD signalling the start of a potential downtrend.
2) Price has closed below the EMA 450. Price closing below this long-term EMA signals that the asset is in a sustained downtrend. Price breaking above this could indicate a bullish strength in which shorting would not be profitable.
EXIT
This script utilises a set take-profit and stop-loss from the entry of the trade. The take profit is set at 8% and the stop loss of 4%, providing a risk reward ratio of 2. This indicates the script will be profitable if it has a win ratio greater than 33%.
Take-Profit Exit: -8% price decrease from entry price.
OR
Stop-Loss Exit: +4% price increase from entry price.
Based on backtesting results across a selection of assets, the 45-minute and 1-hour timeframes are the best for this strategy.
The strategy assumes each order is using 30% of the available coins to make the results more realistic and to simulate you only ran this strategy on 30% of your holdings. A trading fee of 0.1% is also taken into account and is aligned to the base fee applied on Binance.
The backtesting data was recorded from December 1st 2021, just as the market was beginning its downtrend. We therefore recommend analysing the market conditions prior to utilising this strategy as it operates best on weak coins during downtrends and bearish conditions, however the EMA 450 condition should mitigate entries during bullish market conditions.
BEST Strategy Template w/ Custom SL/TP Size - EducationalHello traders
I'm getting this question at least once per week: "how to define a custom exit quantity for my stop loss and a different one for my take profit"
Instead of answering every day the same question in my DMs, I've decided to publish an educational strategy template script using this
Features
- Select to use or not the SL and/or TP
- Define how many pips/USD the SL/TP should be set at from the entry
- Define what quantity percentage you want to close at SL and/or at TP (lines 301 to 320 in the code)
- Classical custom trailing stop where the SL is moved to breakeven once the TP is hit
- Get real-time backtesting stats based on the options you've selected
Update
You might not know it yet but from last week (or maybe the week before), the qty/qty_percent from the strategy.exit function refers now to the initial position size (and not the remaining position size like before)
For example:
strategy.exit("EX1", qty_percent = 50, stop = constant)
strategy.exit("EX2", qty_percent = 20, stop = constant)
What happened before
After "EX1" reaches SL levels, "EX2" exits 20% from the % of the remaining position size.
If the initial position size = 100 contracts
EX1 exits 50 contracts
EX2 exits 20% of 50 contracts = 10 contracts
What's happening now
After "EX1" reaches SL levels, "EX2" exits 20% from the % of the original position size.
If the initial position size = 100 contracts
EX1 exits 50 contracts
EX2 exits 20 (20% of 100 contracts) contracts
I think this is an improvement and I really enjoy this new behavior.
See you in a few days with another post :)
ALL THE BEST
Dave