Autocorrelation - The Quant ScienceAutocorrelation - The Quant Science it is an indicator developed to quickly calculate the autocorrelation of a historical series. The objective of this indicator is to plot the autocorrelation values and highlight market moments where the value is positive and exceeds the attention threshold.
This indicator can be used for manual analysis when a trader needs to search for new price patterns within the historical series or to create complex formulas in estimating future prices.
What is autocorrelation?
Autocorrelation in trading is a statistical measure used to determine the presence of a relationship or pattern of dependence between values in a financial time series over time. It represents the correlation of past values in a series with its future values. In other words, autocorrelation in trading aims to identify if there are systematic relationships between the past prices or returns of a security or market and its future prices or returns. This analysis can be helpful in identifying patterns or trends that can be leveraged for informed trading decisions. The presence of autocorrelation may suggest that market prices or returns follow a certain pattern or trend over time.
Limitations of the model
It is important to note that autocorrelation does not necessarily imply a causal relationship between past and future values. Other variables or market factors may influence the dynamics of prices or returns, and therefore autocorrelation could be merely a random coincidence. Therefore, it is essential to carefully evaluate the results of autocorrelation analysis along with other information and trading strategies to make informed decisions.
How to use
The usage is very simple, you just need to add it to the current chart to activate the indicator.
From the user interface, you can manage two important features:
1. Lenght: the delay period applied to the historical series during the autocorrelation calculation can be managed from the user interface. By default, it is set to 20, which means that the autocorrelation ratio within the historical series is calculated with a delay of 20 bars.
2. Threshold: the threshold value that the autocorrelation level must meet can be managed from the user interface. By default, it is set to 0.50, which means that the autocorrelation value must be higher than this threshold to be considered valid and displayed on the chart.
3. Bar color: the color used to display the autocorrelation data and highlight the bars when autocorrelation is valid can be managed from the user interface.
To set up the chart
We recommend disabling the 'wick' and 'border' of the candlesticks from the chart settings for a high-quality user experience.
Gestión de carteras
DZ Strategy ICTThe script presented is a trading strategy called "Breaker Block Strategy with Price Channel". This strategy uses multiple time frames (1 minute, 5 minutes, 15 minutes, 1 hour, and 4 hours) to detect support and resistance areas on the chart.
The strategy uses parameters such as length, deviations, multiplier, Fibonacci level, move lag and volume threshold for each time frame. These parameters are adjustable by the user.
The script then calculates support and resistance levels using the simple moving average (SMA) and standard deviation (STDEV) of closing prices for each time frame.
It also detects "Breaker Blocks" based on price movement from support and resistance levels, as well as trade volume. A Breaker Block occurs when there is a significant breakout of a support or resistance level with high volume.
Buy and sell signals are generated based on the presence of a Breaker Block and price movement from support and resistance levels. When a buy signal is generated, a buy order is placed, and when a sell signal is generated, a sell order is placed.
The script also plots price channels for each time frame, representing resistance and support levels.
Profit limit levels are set for each time range, indicating that the price levels assigned to positions should be closed with a profit. Stop-loss levels are also set to limit losses in the event of canceled price movements.
In summary, this trading strategy uses a combination of Breaker Block detection, support and resistance levels, price channels and profit limit levels to generate buy and sell signals and manage positions on different time ranges.
Simple Dollar Cost AverageThis simple DCS indicator shows:
Invested Amount
Portfolio Value
Profit
Assets
Cost per Share
Fees
You can define:
Starting Investment
Investment per Cycle
Fee Ratio
Cycle Frequency
Start and End Date
Take profit and Stop Loss ATR HL [Tcs] | ALGOThis indicator helps traders set stop loss and take profit levels based on either ATR or High-Low range.
The indicator calculates stop loss and take profit levels for both long and short positions, based on the user's input of ATR length, ATR smoothing method, and multiplier levels for each level. It’s possible to set 3 levels of take profit, for both long and short trades.
The indicator also includes the option to show or hide levels, bands, and labels for the calculated stop loss and take profit levels.
Additionally, the indicator has a function to calculate the user's risk based on their account balance, risk percentage, and broker fees.
Overall, this indicator can be helpful for traders who use stop loss and take profit levels in their trading strategies and want a visual representation of those levels on their charts.
Please note that this indicator is for educational purposes only and should not be used for trading without further testing and analysis.
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.
Cobra's CryptoMarket VisualizerCobra's Crypto Market Screener is designed to provide a comprehensive overview of the top 40 marketcap cryptocurrencies in a table\heatmap format. This indicator incorporates essential metrics such as Beta, Alpha, Sharpe Ratio, Sortino Ratio, Omega Ratio, Z-Score, and Average Daily Range (ADR). The table utilizes cell coloring resembling a heatmap, allowing for quick visual analysis and comparison of multiple cryptocurrencies.
The indicator also includes a shortened explanation tooltip of each metric when hovering over it's respected cell. I shall elaborate on each here for anyone interested.
Metric Descriptions:
1. Beta: measures the sensitivity of an asset's returns to the overall market returns. It indicates how much the asset's price is likely to move in relation to a benchmark index. A beta of 1 suggests the asset moves in line with the market, while a beta greater than 1 implies the asset is more volatile, and a beta less than 1 suggests lower volatility.
2. Alpha: is a measure of the excess return generated by an investment compared to its expected return, given its risk (as indicated by its beta). It assesses the performance of an investment after adjusting for market risk. Positive alpha indicates outperformance, while negative alpha suggests underperformance.
3. Sharpe Ratio: measures the risk-adjusted return of an investment or portfolio. It evaluates the excess return earned per unit of risk taken. A higher Sharpe ratio indicates better risk-adjusted performance, as it reflects a higher return for each unit of volatility or risk.
4. Sortino Ratio: is a risk-adjusted measure similar to the Sharpe ratio but focuses only on downside risk. It considers the excess return per unit of downside volatility. The Sortino ratio emphasizes the risk associated with below-target returns and is particularly useful for assessing investments with asymmetric risk profiles.
5. Omega Ratio: measures the ratio of the cumulative average positive returns to the cumulative average negative returns. It assesses the reward-to-risk ratio by considering both upside and downside performance. A higher Omega ratio indicates a higher reward relative to the risk taken.
6. Z-Score: is a statistical measure that represents the number of standard deviations a data point is from the mean of a dataset. In finance, the Z-score is commonly used to assess the financial health or risk of a company. It quantifies the distance of a company's financial ratios from the average and provides insight into its relative position.
7. Average Daily Range: ADR represents the average range of price movement of an asset during a trading day. It measures the average difference between the high and low prices over a specific period. Traders use ADR to gauge the potential price range within which an asset might fluctuate during a typical trading session.
Utility:
Comprehensive Overview: The indicator allows for monitoring up to 40 cryptocurrencies simultaneously, providing a consolidated view of essential metrics in a single table.
Efficient Comparison: The heatmap-like coloring of the cells enables easy visual comparison of different cryptocurrencies, helping identify relative strengths and weaknesses.
Risk Assessment: Metrics such as Beta, Alpha, Sharpe Ratio, Sortino Ratio, and Omega Ratio offer insights into the risk associated with each cryptocurrency, aiding risk assessment and portfolio management decisions.
Performance Evaluation: The Alpha, Sharpe Ratio, and Sortino Ratio provide measures of a cryptocurrency's performance adjusted for risk. This helps assess investment performance over time and across different assets.
Market Analysis: By considering the Z-Score and Average Daily Range (ADR), traders can evaluate the financial health and potential price volatility of cryptocurrencies, aiding in trade selection and risk management.
Features:
Reference period optimization, alpha and ADR in particular
Source calculation
Table sizing and positioning options to fit the user's screen size.
Tooltips
Important Notes -
1. The Sharpe, Sortino and Omega ratios cell coloring threshold might be subjective, I did the best I can to gauge the median value of each to provide more accurate coloring sentiment, it may change in the future.
The median values are : Sharpe -1, Sortino - 1.5, Omega - 20.
2. Limitations - Some cryptos have a Z-Score value of NaN due to their short lifetime, I tried to overcome this issue as with the rest of the metrics as best I can. Moreover, it limits the time horizon for replay mode to somewhere around Q3 of 2021 and that's with using the split option of the top half, to remain with the older cryptos.
3. For the beginner Pine enthusiasts, I recommend scimming through the script as it serves as a prime example of using key features, to name a few : Arrays, User Defined Functions, User Defined Types, For loops, Switches and Tables.
4. Beta and Alpha's benchmark instrument is BTC, due to cryptos volatility I saw no reason to use SPY or any other asset for that matter.
Limit Order + ATR Stop-Loss [TANHEF]This indicator enables interactive placement of limit or stop-limit orders with a trailing ATR stop-loss and optional profit target (with alerts). Refer to the images below for further clarification.
Why use a trailing stop-loss?
A trailing stop-loss serves as an exit strategy when price moves against you, while also allowing you to adjust the exit point further into profit when price moves favorably. The ATR (Average True Range), a reliable measure of volatility, acts as an effective risk management tool, functioning as a trailing stop-loss.
Indicator Explanation
Initial indicator placement: Select Long Limit or Long-Stop Limit order.
Change Entry Type: Switch between Long and Short within settings.
Modify entry price: Drag circle, adjust in settings, or re-add indicator to chart.
Optional Profit Target: Use Risk/Reward ratio or specify price.
Entry anticipation: Estimated ATR stop-loss and profit target as blue circles (fluctuates with volatility changes).
Entry triggered: Actual ATR stop-loss and profit target plotted.
Exit conditions: Stop-loss or profit target hit, exit entry.
Update Frequency: Continuously, Bar Open, or Bar Open on entry then continuously.
ATR Overlap: no entry occurs if the ATR overlaps with price (stop-loss 'hit' already on entry bar)
Table: Displays input settings selected.
Show Only On Ticker: Ability to hide indicator on other tickers.
Long Limit
Long Stop-Limit
Short Limit
Short Stop-Limit
Alerts
1. 'Check' alerts to use within indicator settings (entry, trailing stop hit, profit target hit, and failed entry).
2. Select 'Create Alert'
3. Set the condition to 'Limit Order + ATR Stop-Loss''
4. Select create.
Additional details can be added to the alert message using these words in between Curly (Brace) Brackets:
{{trail}} = ATR trailing stop-loss (price)
{{target}} = Price target (price)
{{type}} = Long or Short stop-loss (word)
{{traildistance}} = Trailing Distance (%)
{{targetdistance}} = Target Distance (%)
{{starttime}} = Start time of position (day:hr:min)
{{maxdrawdown}} = max loss
{{maxprofit}} = max profit
{{update}} = stoploss update frequency
{{entrysource}} = entry as 1st bar source (yes/no)
{{triggerentry}} = Wick/Close Trigger entry input
{{triggerexit}} = Wick/Close Trigger exit input
{{triggertarget}} = Wick/Close Trigger target input
{{atrlength}} = ATR length input
{{atrmultiplier}} = ATR multiplier input
{{atrtype}} = ATR type input
{{ticker}} = Ticker of chart (word)
{{exchange}} = Exchange of chart (word)
{{description}} = Description of ticker (words)
{{close}} = Bar close (price)
{{open}} = Bar open (price)
{{high}} = Bar high (price)
{{low}} = Bar low (price)
{{hl2}} = Bar HL2 (price)
{{volume}} = Bar volume (value)
{{time}} = Current time (day:hr:min)
{{interval}} = Chart timeframe
{{newline}} = New line for text
Consensio Allocation ToolOriginally created and taught by Taylor Jenks, this indicator provides portfolio allocation suggestions based on the behaviour of price and 3 simple moving averages (4/10/40 by default)
(ie. when short & medium term SMAs are above the long term then allocation is to be 100%).
This percentage allocated to the stock/commodity is to be reduced as it passes below the SMA's, particularly as each moving average crosses.
Consensio is useful for scaling in and out of a position as the portfolio allocation will change according to the momentum of the asset.
The rules below are my own based on understanding of the trading system developed by Jenks and his online content.
This script has the following rules:
if fastAboveSlowMA and not mediumAboveSlowMA
allocation := 30.0
else if longAboveFastMA
allocation := 0.0
else if fastAboveMediumMA and fastAboveSlowMA
allocation := 100.0
else if not fastAboveMediumMA and fastAboveSlowMA
allocation := 80.0
else if not fastAboveMediumMA and not fastAboveSlowMA
allocation := 50.0
else if not mediumAboveSlowMA and fastAboveSlowMA
allocation := 50.0
// Calculate adjusted allocation percentage based on crossing moving averages
allocation := allocation + (priceAboveFastMA ? 10.0 : -10.0)
allocation := allocation + (priceAboveMediumMA ? 10.0 : -10.0)
Crypto Correlation MatrixA crypto correlation matrix or table is a tool that displays the correlation between different cryptocurrencies and other financial assets. The matrix provides an overview of the degree to which various cryptocurrencies move in tandem or independently of each other. Each cell represents the correlation between the row and column assets respectively.
The correlation matrix can be useful for traders and investors in several ways:
First, it allows them to identify trends and patterns in the behavior of different cryptocurrencies. By looking at the correlations between different assets, traders can gain insight into the intra-relationships of the crypto market and make more informed trading decisions. For example, if two cryptocurrencies have a high positive correlation, meaning that they tend to move in the same direction, a trader may want to diversify their portfolio by choosing to invest in only one of the two assets.
Additionally, the correlation matrix can help traders and investors to manage risk. By analyzing the correlations between different assets, traders can identify opportunities to hedge their positions or limit their exposure to particular risks. For example, if a trader holds a portfolio of cryptocurrencies that are highly correlated with each other, they may be at greater risk of losses if the market moves against them. By diversifying their portfolio with assets that are less correlated with each other, they can reduce their overall risk.
Some of the unique properties for this specific script are the correlation strength levels in conjunction with the color gradient of cells, intended for clearer readability.
Features:
Supports up to 64 different crypto assets.
Dark/Light mode.
Correlation strength levels and cell coloring.
Adjustable positioning on the chart.
Alerts at the close of a bar. (Daily timeframe or higher recommended)
Manual PnL (Profit and Loss) % Tracker - spot long only
This is a manual profit and loss tracker. It takes the user's manual input of total cost and quantity, and then outputs a table on the bottom right of the chart showing the profit or loss %, average purchase price, gross profit or loss, and market value.
Instructions:
1. Double click the indicator title at the top left of the chart
2. Select the "Inputs" tab and click the empty field next to "Symbol" to enter the traded symbol+exchange. This entry MUST be the same as the chart you are on, for example BTCUSDT/BINANCE (indicator will not display otherwise)
3. Enter the Total Cost and Qty of shares/coins owned
4. Optional - change positive or negative colors
5. Optional - under the "Style" tab, change the color of the average price (AVG) line
Note that for the average price (AVG) line to be shown/hidden you must enable/disable "Indicator and financials labels" in the scales settings.
For crypto or other tickers that have prices in many decimal places I would suggest, for the sake of accuracy, adjusting the decimal places in the code so that for prices under $1 you will display more info.
For example let's say you purchase x number of crypto at a price of 0.031558 you should change the code displaying "0.00" on line 44 to "0.000000"
This will ensure that the output table and plotted line will calculate an average price with the same number of decimals.
Recessions & crises shading (custom dates & stats)Shades your chart background to flag events such as crises or recessions, in similar fashion to what you see on FRED charts. The advantage of this indicator over others is that you can quickly input custom event dates as text in the menu to analyse their impact for your specific symbol. The script automatically labels, calculates and displays the peak to through percentage corrections on your current chart.
By default the indicator is configured to show the last 6 US recessions. If you have custom events which will benefit others, just paste the input string in the comments below so one can simply copy/paste in their indicator.
Example event input (No spaces allowed except for the label name. Enter dates as YYYY-MM-DD.)
2020-02-01,2020-03-31,COVID-19
2007-12-01,2009-05-31,Subprime mortgages
2001-03-01,2001-10-30,Dot-com bubble
1990-07-01,1991-03-01,Oil shock
1981-07-01,1982-11-01,US unemployment
1980-01-01,1980-07-01,Volker
1973-11-01,1975-03-01,OPEC
Joel Greenblatt Magic FormulaJoel Greenblatt Magic Formula. I always wanted to make this.
The Indicator shows 3 values.
ROC,EY,SUM.
ROC= Return On Capital.
EY=Earnings Yield
SUM= Addition of Two.
Formula:
ROC=EBIT / (Net Working Capital + Net Fixed Assets).
EY = EBIT / Enterprise value
Enterprise Value=(Market value of equity + Net Interest-bearing debt)
To implement the strategy, investors start by identifying a universe of stocks, typically large-cap or mid-cap companies that trade on a major stock exchange. Next, they rank the stocks based on their ROC and EY. The companies with the best combination of these two metrics are considered the best investments (based on this ranking).
For example, a stock that ranks 10th on EY and 99th on ROIC gets a value of 109. The two ranks are simply added together and all stocks are ranked on the sum of the two ranks. The stocks with the lowest values are best.
All credits to "The Little Book That Beats The Market" by Joel Greenblatt
The Magic Formula strategy is a stock selection method popularized by Joel Greenblatt’s book The Little Book That Beats the Market.
It involves ranking companies based on Two factors:
A high return on capital and A high Earnings Yield.
The companies with the best combination of these two metrics are considered the best investments. The strategy aims to find undervalued companies with strong financials that have the potential for high returns over the long term.
Scenario Close Price [Skiploss]You have opened multiple positions in your account ? This is what will help you calculate. It will definitely calculate the total lots size that you have opened. Furthermore, it will also calculate the results of how much profit or loss you have made. All you have to do is slide the line to the scenario line.
The system will calculate the data for each order that you have entered and display the results in the table in the top right of the screen.
Maximum is 7 positions.
Risk Reward Calculator [lovealgotrading]
OVERVIEW:
This Risk Reward Calculator strategy can help you maximize your RR value with help of algorithmic trading.
INDICATOR:
I wanted to setup my trades more easier with this indicator, I didn't want to calculate everytime before orders, with help this indicator we can calculate R:R value, avarage price, stoploss price, take-profit price, order prices, all position cost and more ...
Our strategy is a risk revard calculation indicator that is made easy to use by using visualized lines and panels, and also has algorithmic trading support.
With the help of this indicator, we can quickly and easily calculate our risk reward values and enter the positions.
If we want to ensure that our balance grows regularly while trading in the stock market, we need to manage the risks and rewards otherwise we may fall below our initial balance at the end of the day, even if we seem to be winning.
What is the Risk-Reward value ?
This value is a value that shows how many times the amount of risk we take when entering the position is successful, we will earn.
- For example, you risked $100 while entering the trade, so if your trade stops, you will lose 100 $.
Your Risk-Reward(RR) value is 2 means that if your position is successful, you will have 200 $ in your pocket.
A trader's success is determined by the amount of R he earns monthly or yearly, not how much money he makes.
What is different in this indicator ?
I want to say thank you to © EvoCrypto. His Calculator (weighted) – evo indicator helped me when I was developed my indicator.
I want to explain what I have improved:
1-In this strategy, we can determine the time period in which we want to open our positions.
2-We can open a maximum of 4 positions in the same direction and close our positions at a single level. StopLoss or TakeProfit
3-This indicator, which works in the form of a strategy, shows where our positions have been opened or closed. With the help of this, it helps us to determine our strategy in our future positions more accurately.
4-The most important improvement is that we do not miss our positions with the help of alarms (WEB HOOK). if we want, we receive by quickly connecting all these positions to our robot, the software can enter and exit the position while we are busy.
IMPLEMENTATION DETAILS – SETTINGS:
1 - We can set the start and end dates of the positions we will take.
2- We can set our take profit, stoploss levels.
3- If your trade is stopped, we can determine the amount of the trade that we will lose.
4- We can adjust our entry levels to positions and our position sizes at entry levels.
(Sum of positions weight must be 100%)
5- We can receive our positions even if we are busy with the help of algorithmic trading. For this, we must paste our Jshon codes into the fields specified in the settings panel.
6- Finally, we can change the settings we want and don't want to have in our visual elements.
Let's make a LONG side example together
We have determined our positions to enter stoploss, take profit and long positions. We did not forget to set the start time of our strategy
Our strategy appear on the graph as follows.
Our strategy has calculated the total position size, our R-R value, the distance of the current price to the stop and take profit levels, in short, a lot of things we could look visually.
Notes:
If you're going to connect this bot to an automatic Long or Short direction,
Don’t forget! you need to Webhook URL,
Don’t miss paste this code to your message window {{strategy.order.alert_message}}
ALSO:
If you have any ideas what to add to my work to add more sources or make calculations cooler, feel free to write me.
Pip CrosshairsThis is a simple tool designed to help you visualize your stop loss and take profit levels before entering a trade. The tool plots two lines on the chart - a green dotted line for take profit and a red dotted line for stop loss (similar to the price line) - with a simulated default spread of one pip factored in. The indicator has the option to toggle between long and short positions.
Please note that the spread used in the tool is not based on your actual spread and should be adjusted accordingly. As, to the best of my knowledge Pine Script does not have the ability to automatically include spread in an indicator, so you will need to input your spread manually. (if you can please let me know cause that would be a game changer).
Overall, should help save you a bit of time by not having to manually measure stop loss and take profit levels for each trade.
Happy hunting :)
Market Structure Trailing Stop [LuxAlgo]This script returns trailing stops on the occurrence of market structure (CHoCH/BOS labeling). Trailing stops are adjusted based on trailing maximums/minimums with the option for users to be able to control how quickly a trailing stop can converge toward the price.
🔶 SETTINGS
Pivot Lookback: Pivot length used for the detection of swing points.
Increment Factor %: Controls how fast trailing stops converge toward the price, with lower values returning slower converging trailing stops.
Reset Stop On: Determines if trailing stops are reset on CHoCH structure or all (CHoCH + BOS).
Show Structure: Determines if market structure is displayed.
🔶 USAGE
Trailing stops allow traders to protect them against downside risk while also guaranteeing a potential profit in case the market goes in the expected direction of the trade.
Users making use of market structure as a primary entry condition can benefit from having trailing stops based on these to either provide an additional exit condition or to provide points of support/resistance with the price.
Trailing stops can avoid being hit more frequently by using a lower Increment Factor % setting.
Finally, users can reset the trailing stop when any market structure is detected (or only on CHoCHs). Allowing trailing stops to reset on the detection of any market structure allows the indicator to return trailing stops closer to the price. CHoCH labels are highlighted as dashed lines while BOS labels are highlighted as dotted lines.
🔶 DETAILS
When a new structure (or only CHoCH if specified by the user) is detected, trailing stops will initially be set based on the maximum/minimum made on the previous trend. This will also set the trailing maximum/minimum to the current price value.
If an uptrend is detected (most recent market structure is bullish) then the trailing stop will increase if the trailing maximum increase, the increment is calculated as:
trailing stop = trailing stop + Increment Factor % of (trailing maximum - previous trailing maximum)
If a downtrend is detected (most recent market structure is bearish) then the trailing stop will decrease if the trailing minimum decrease, the decrement is calculated as:
trailing stop = trailing stop + Increment Factor % of (trailing minimum - previous trailing minimum)
Lorentzian Classification Strategy Based in the model of Machine learning: Lorentzian Classification by @jdehorty, you will be able to get into trending moves and get interesting entries in the market with this strategy. I also put some new features for better backtesting results!
Backtesting context: 2022-07-19 to 2023-04-14 of US500 1H by PEPPERSTONE. Commissions: 0.03% for each entry, 0.03% for each exit. Risk per trade: 2.5% of the total account
For this strategy, 3 indicators are used:
Machine learning: Lorentzian Classification by @jdehorty
One Ema of 200 periods for identifying the trend
Supertrend indicator as a filter for some exits
Atr stop loss from Gatherio
Trade conditions:
For longs:
Close price is above 200 Ema
Lorentzian Classification indicates a buying signal
This gives us our long signal. Stop loss will be determined by atr stop loss (white point), break even(blue point) by a risk/reward ratio of 1:1 and take profit of 3:1 where half position will be closed. This will be showed as buy.
The other half will be closed when the model indicates a selling signal or Supertrend indicator gives a bearish signal. This will be showed as cl buy.
For shorts:
Close price is under 200 Ema
Lorentzian Classification indicates a selling signal
This gives us our short signal. Stop loss will be determined by atr stop loss (white point), break even(blue point) by a risk/reward ratio of 1:1 and take profit of 3:1 where half position will be closed. This will be showed as sell.
The other half will be closed when the model indicates a buying signal or Supertrend indicator gives a bullish signal. This will be showed as cl sell.
Risk management
To calculate the amount of the position you will use just a small percent of your initial capital for the strategy and you will use the atr stop loss or last swing for this.
Example: You have 1000 usd and you just want to risk 2,5% of your account, there is a buy signal at price of 4,000 usd. The stop loss price from atr stop loss or last swing is 3,900. You calculate the distance in percent between 4,000 and 3,900. In this case, that distance would be of 2.50%. Then, you calculate your position by this way: (initial or current capital * risk per trade of your account) / (stop loss distance).
Using these values on the formula: (1000*2,5%)/(2,5%) = 1000usd. It means, you have to use 1000 usd for risking 2.5% of your account.
We will use this risk management for applying compound interest.
> In settings, with position amount calculator, you can enter the amount in usd of your account and the amount in percentage for risking per trade of the account. You will see this value in green color in the upper left corner that shows the amount in usd to use for risking the specific percentage of your account.
> You can also choose a fixed amount, so you will have to activate fixed amount in risk management for trades and set the fixed amount for backtesting.
Script functions
Inside of settings, you will find some utilities for display atr stop loss, break evens, positions, signals, indicators, a table of some stats from backtesting, etc.
You will find the settings for risk management at the end of the script if you want to change something or trying new values for other assets for backtesting.
If you want to change the initial capital for backtest the strategy, go to properties, and also enter the commisions of your exchange and slippage for more realistic results.
In risk managment you can find an option called "Use leverage ?", activate this if you want to backtest using leverage, which means that in case of not having enough money for risking the % determined by you of your account using your initial capital, you will use leverage for using the enough amount for risking that % of your acount in a buy position. Otherwise, the amount will be limited by your initial/current capital
I also added a function for backtesting if you had added or withdrawn money frequently:
Adding money: You can choose how often you want to add money (Monthly, yearly, daily or weekly). Then a fixed amount of money and activate or deactivate this function
Withdraw money: You can choose if you want to withdraw a fixed amount or a percentage of earnings. Then you can choose a fixed amount of money, the period of time and activate or deactivate this function. Also, the percentage of earnings if you choosed this option.
Some other assets where strategy has worked
BTCUSD 4H, 1D
ETHUSD 4H, 1D
BNBUSD 4H
SPX 1D
BANKNIFTY 4H, 15 min
Some things to consider
USE UNDER YOUR OWN RISK. PAST RESULTS DO NOT REPRESENT THE FUTURE.
DEPENDING OF % ACCOUNT RISK PER TRADE, YOU COULD REQUIRE LEVERAGE FOR OPEN SOME POSITIONS, SO PLEASE, BE CAREFULL AND USE CORRECTLY THE RISK MANAGEMENT
Do not forget to change commissions and other parameters related with back testing results!. If you have problems loading the script reduce max bars back number in general settings
Strategies for trending markets use to have more looses than wins and it takes a long time to get profits, so do not forget to be patient and consistent !
Please, visit the post from @jdehorty called Machine Learning: Lorentzian Classification for a better understanding of his script!
Any support and boosts will be well received. If you have any question, do not doubt to ask!
[MiV] MA Screener v1.0In my trading I stick to the following strategy: I buy an asset above the 100/200 moving average and then sell it.
The most problematic thing in all this is to look for assets that are above the 100 or 200 moving average, and to assess how "far" the price is from that moving average.
In fact, to solve this problem I created this indicator.
It works with 30 different assets and displays the state of its two moving averages, whether the price is higher or not, and how much higher the price is from that level.
*Backtesting System ⚉ OVERVIEW ⚉
One of the best Systems for Backtesting your Strategies.
Incredibly flexible, simple, fast and feature-rich system — will solve most of your queries without much effort.
Many systems for setting StopLoss, TakeProfit, Risk Management and advanced Filters.
All you need to do is plug in your indicator and start Backtesting .
I intentionally left the option to use my System on Full Power before you load your indicator into it.
The system uses the built-in simple and popular moving average crossover signal for this purpose. (EMA 50 & 200).
Also Highly Recommend that you Fully use ALL of the features of this system so that you understand how they work before you ask questions.
Also tried to leave TIPS for each feature everywhere, read Tips, activate them and see how they work.
But before you use this system, I Recommend you to read the following description in Full.
—————— How to connect your indicator in 2 steps:
Adapt your indicator by adding only 2 lines of code and then connect it to this Backtesting System.
Step 1 — Create your connector, For doing so:
• 1 — Find or create in your indicator where are the conditions printing the Long-Buy and Short-Sell signals.
• 2 — Create an additional plot as below
I'm giving an example with a Two moving averages cross.
Please replicate the same methodology for your indicator wether it's a MACD, RSI , Pivots, or whatever indicator with Clear Buy and Sell conditions.
//@version=5
indicator('Moving Average Cross', overlay = true)
MA200 = ta.𝚎𝚖𝚊(close, 200)
MA50 = ta.𝚎𝚖𝚊(close, 50)
// Generate Buy and Sell conditions
buy = ta.crossover (MA200, MA50)
sell = ta.crossunder (MA200, MA50)
plot(MA200, color=color.green)
plot(MA50 , color=color.red )
bgcolor(color = buy ? color.green : sell ? color.red : na, title='SIGNALS')
// ———————————————— SIGNAL FOR SYSTEM ————————————————
Signal = buy ? +1 : sell ? -1 : 0
plot(Signal, title='🔌Connector🔌', display = display.none)
// —————— 🔥 The Backtesting System expects the value to be exactly +1 for the 𝚋𝚞𝚕𝚕𝚒𝚜𝚑 signal, and -1 for the 𝚋𝚎𝚊𝚛𝚒𝚜𝚑 signal
Basically, I identified my Buy & Sell conditions in the code and added this at the bottom of my indicator code
Now you can connect your indicator to the Backtesting System using the Step 2
Step 2 — Connect the connector
• 1 — Add your updated indicator to a TradingView chart and Add the Backtesting System as well to the SAME chart
• 2 — Open the Backtesting System settings and in the External Source field select your 🔌Connector🔌 (which comes from your indicator)
_______________________________
⚉ MAIN SETTINGS ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
𝐄𝐱𝐭𝐞𝐫𝐧𝐚𝐥 𝐒𝐨𝐮𝐫𝐜𝐞 — Select your indicator. Add your indicator by following the 2 steps described above and select it in the menu. To familiarize yourself with the system until you select your indicator, you will have an in-built strategy of crossing the two moving EMA's of 50 and 200.
Long Deals — Enable/Disable Long Deals.
Short Deals — Enable/Disable Short Deals.
Wait End Deal — Enable/Disable waiting for a trade to close at Stop Loss/Take Profit. Until the trade closes on the Stop Loss or Take Profit, no new trade will open.
Reverse Deals — To force the opening of a trade in the opposite direction.
ReEntry Deal — Automatically open the same new deal after the deal is closed.
ReOpen Deal — Reopen the trade if the same signal is received. For example, if you are already in the long and a new signal is received in the long, the trade will reopen. * Does not work if Wait End Deal is enabled.
𝐓𝐚𝐤𝐞 𝐏𝐫𝐨𝐟𝐢𝐭:
None — Disables take profit. Useful if you only want to use dynamic stoplosses such as MA, Fast-Trailing, ATR Trail.
FIXED % — Fixed take profit in percent.
FIXED $ — Fixed Take in Money.
ATR — Fixed Take based on ATR.
R:R — Fixed Take based on the size of your stop loss. For example, if your stop is 10% and R:R=1, then the Take would be 10%. R:R=3 Take would be 30%, etc.
HH / LL — Fixed Take based on the previous maximum/minimum (extremum).
𝐒𝐭𝐨𝐩 𝐋𝐨𝐬𝐬:
None — Disables Stop Loss. Useful if you want to work without a stop loss. *Be careful if Wait End Deal is enabled, the trade may not close for a long time until it reaches the Take.
FIXED % — Fixed Stop in percent.
FIXED $ — Fixed Stop in Money.
TRAILING — Dynamic Trailing Stop like on the stock exchanges.
FAST TRAIL — Dynamic Fast Trailing Stop moves immediately in profit and stays in place if the price stands still or the price moves in loss.
ATR — Fixed Stop based on the ATR.
ATR TRAIL — Dynamic Trailing Stop based on the ATR.
LO / HI — A Fixed Stop based on the last Maximum/Minimum extemum. Allows you to place a stop just behind or above the low/high candle.
MA — Dynamic Stop based on selected Moving Average. * You will have 8 types of MA (EMA, SMA, HMA, etc.) to choose from, but you can easily add dozens of other MAs, which makes this type of stop incredibly flexible.
Add % — If true, then with the "𝗦𝘁𝗼𝗽 %" parameter you can add percentages to any of the current SL. Can be especially useful when using Stop - 𝗔𝗧𝗥 or 𝗠𝗔 or 𝗟𝗢/𝗛𝗜. For example with 𝗟𝗢/𝗛𝗜 to put a stop for the last High/Low and add 0.5% additional Stoploss.
Fixed R:R — If the stop loss is Dynamic (Trailing or MA) then if R:R true can also be made Dynamic * Use it carefully, the function is experimental.
_________________________________________
⚉ TAKE PROFIT LEVELS ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
A unique method of constructing intermediate Take Profit Levels will allow you to select up to 5 intermediate Take Profit Levels and one intermediate Stop Loss.
Intermediate Take Profit Levels are perfectly calculated into 5 equal parts in the form of levels from the entry point to the final Take Profit target.
All you need to do is to choose the necessary levels for fixing and how much you want to fix at each level as a percentage. For example, TP 3 will always be exactly between the entry point and the Take Profit target. And the value of TP 3 = 50 will close 50% of the amount of the remaining size of the position.
Note: all intermediate SL/TP are closed from the remaining position amount and not from the initial position size, as TV does by default.
SL 0 Position — works in the same way as TP 1-5 but it's Stop. With this parameter you can set the position where the intermediate stop will be set.
Breakeven on TP — When activated, it allows you to put the stop loss at Breakeven after the selected TP is reached. For this function to work as it should - you need to activate an intermediate Take. For example, if TP 3 is activated and Breakeven on TP = 3, then after the price reaches this level, the Stop loss will go to Breakeven.
* This function will not work with Dynamic Stoplosses, because it simply does not make sense.
CoolDown # Bars — When activated, allows you to add a delay before a new trade is opened. A new trade after CoolDown will not be opened until # bars pass and a new signal appears.
_____________________________
⚉ TIME FILTERS ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
Powerful time filter code that allows you to filter data based on specific time zones, dates, and session days. This code is ideal for those who need to analyze data from different time zones and weed out irrelevant data.
With Time Filter, you can easily set the starting and ending time zones by which you want to filter the data.
You can also set a start and end date for your data and choose which days of the week to include in the analysis. In addition, you can specify start and end times for a specific session, allowing you to focus your analysis on specific time periods.
_________________________________
⚉ SIGNAL FILTERS ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
Signal Filters — allows you to easily customize and optimize your trading strategies based on 10 filters.
Each filter is designed to help you weed out inaccurate signals to minimize your risks.
Let's take a look at their features:
__________________________________
⚉ RISK MANAGEMENT ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
Risk management tools that allow you to set the maximum number of losing trades in a row, a limit on the number of trades per day or week and other filters.
Loss Streak — Set Max number of consecutive loss trades.
Win Streak — Max Winning Streak Length.
Row Loss InDay — Max of consecutive days with a loss in a row.
DrawDown % — Max DrawDown (in % of strategy equity).
InDay Loss % — Set Max Intraday Loss.
Daily Trades — Limit the number of MAX trades per day.
Weekly Trades — Limit the number of MAX trades per week.
* 🡅 I would Not Recommend using these functions without understanding how they work.
Order Size — Position Size
• NONE — Use the default position size settings in Tab "Properties".
• EQUITY — The amount of the allowed position as a percentage of the initial capital.
• Use Net Profit — On/Off the use of profit in the following trades. *Only works if the type is EQUITY.
• SIZE — The size of the allowed position in monetary terms.
• Contracts — The size of the allowed position in the contracts. 1 Сontract = Сurrent price.
________________
⚉ NOTES ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
It is important to note that I have never worked with Backtesting and the functions associated with them before.
It took me about a month of slow work to build this system.
I want to say Big Thanks:
• The PineScripters🌲 group in Telegram , the guys suggested how to implement some features. Especially @allanster
• Thanks to all those people who share their developments for free on TV and not only.
• I also thank myself for not giving up and finishing the project, and not trying to monetize the system by selling it. * Although I really want the money :)
I tried hard to make it as fast and convenient as possible for everyone who will use my code.
That's why I didn't use any libraries and dozens of heavy functions, and I managed to fit in 8+-functions for the whole code.
Absolutely every block of code I tried to make full-fledged modular, that it was easy to import/edit for myself (you).
I have abused the Ternary Pine operator a little (a lot) so that the code was as compact as possible.
Nevertheless, I tried very hard to keep my code very understandable even for beginners.
At last I managed to write 500 lines of code, making it one of the fastest and most feature-rich systems out there.
I hope everyone enjoys my work.
Put comments and write likes.
Strategy Template + Performance & Returns table + ExtrasA script I've been working on since summer 2022. A template for any strategy so you just have to write or paste the code and go straight into risk management settings
Features:
>Signal only Longs/only Shorts/Both
>Leverage system
>Proper fees calculation (even with leverage on)
>Different Stop Loss systems: Simple percentage, 4 different "move to Break Even" systems and Scaling SL after each TP order (read the disclaimer at the bottom regarding this and the TV % profitable metric)
>2 Take Profit systems: Simple percentages, or Risk/reward ratios based on SL level
>Additional option on TP so last one "rides free" until closure of position or Stoploss is hit (for more than 1 orders)
>Up to 5 TP orders
>Show or hide SL/TP levels on demand
>2 date filters. Manual filter is nothing new, enter two dates/hours and filter will turn on. BUT automatic filter is another thing (thanks to user @bfr_ for his help in codingthis feature)
>AUTOMATIC DATE FILTER. Allows you to split all historical data on the chart in X periods, then choose the range of periods used. Up to 10 but that can be changed, instructions included. Useful for WalkForward simulations, haven't seen a script in TradingView that allows you to do this and test your strategy on "unseen data" automatically
EXTRA SETTINGS
Besides, some additions I like to add to my codes:
>Returns table for monthly and weekly performance. Requires recalculation on every tick. This is a modified version of @QuantNomad's work. May add lower TF options later on
>Volume Based S/R system. Original work from @shtcoinr
>One feature that was made by me, the "portfolio table". Yields info and metrics of your strategy, current position and balance. You're able to turn it off and change its size
Should anyone find an error, or have any idea on how to improve this code, please contact me. Future updates could come, stay tuned
DISCLAIMER:
In order to have accurate StopLoss hit, I had to change the previous system, which was a "close position on candle close" instead at actual stoploss level. It was fixed, but resulted on inflation of the number of trading orders, thus reducing the percent profitable and making it strongly biased and unreal. Keep that in mind, that "real" profitability could be 2x or 3x the metric TradingView says. If your strategy has a really high trading frequency, resulting in 3000+ orders, might be a problem. Try to make use of the automatic/manual date filter as workaround, I have no means of changing this, seems it is not a bug but an intended design of the PineScript Code
Correlation AnalysisAs the name suggests, this indicator is a market correlation analysis tool.
It contains two main features:
- The Curve: represents the historic correlation coefficient between the current chart and the “Reference Market” input from the settings menu. It aims to give more depth to the current correlation values found in the second feature.
- The Screener: this second feature displays all correlation coefficient values between the (max) 20 markets inputs. You can use it to create several screeners for several market types (crypto, forex, metals, etc.) or even replicate your current portfolio of investments and gauge the correlation of its components.
Aside from these two previous features, you can visually plot the variation rate from one bar to another along with the covariance coefficient (both used in the correlation calculation). Finally, a simple “signal” moving average can be applied to the correlation coefficient .
I might add alerts to this script or even turn it into a strategy to do some backtesting. Do not hesitate to contact me or comment below if this is something you would be interested in or if you have any suggestions for improvement.
Enjoy!!
Leverage HelperCalculate position size & leverage the easy way!
- Drag & drop entry + stop loss level
- Input account size + risk size in the settings
- Calculation plotted on table
FuriousFX Trading Confirmation ListThis is a simple script that allows user to define the confirmations, position them (pin them) to the top middle bottom left or right on the screen and check them off
Once the user checks the confirmation it changes from red or any other default color to green (indicating it has played out).
There are similar script out there but what makes this script unique is one how it is generated and more importantly the mechanism of changing color.. You also have the option to pick from a pick list in the options of how many (up to 10) confirmations you want to generate and you can define change them at any time..
To use this script simply do the following :
1) add it to your chart, double click on the default table
2)select the desired number of confirmations
3)Select the desired position and default colors (default is top right and dark red)
4)Define your criteria for confirmations in appropriate boxes by writing over the default values
5)Start using it, when you see your desired confirmation, double click on the table again and select "Confirmed?" check box.. Once selected the color of that confirmation will turn green...
This script is done to keep people disciplined and enter only according to their trading strategy, as we all know that the biggest reason why people lose in trading is impatience fear and greed...
This script attemps to solve problems of overtrading, entering too early or too late..
Hope you guys enjoy it..
Feel free to write comments for improvements or copy it for your needs.