VT R Cloudsettings for the VT R Indicator
VT R TIme (Minues) = 10
Session Time = 09:25 - 09:35
Show VT R Ticked
Show VWMA Ticked
VWMA Period = 10
Long Trade Rules
1. Close ABove buy above
2. trade above ma
3. volume > ma (volume Settings Given Below)
4. sl below sell below
Short Trade Rules
1. close below sell below
2. trade below ma
3. volume > ma (volume Settings Given Below)
4. sl above buy above
Volume Indicator has to be added manually i suggest to use the default Volume Indicator
Settings for the Volume Indicator
Lookback = 10
ShowMA Ticked
LengthMA = 10
Recherche dans les scripts pour "选10只股票,统计十大股东中间基金的持股变化,结合消息与股票价格运动,看看有什么规律?"
Normalized Quantitative Qualitative Estimation nQQENormalized version of Quantitative Qualitative Estimation QQE:
Normalized QQE tries to overcome the problems of false signals due to RSI divergences on the original QQE indicator.
The main purpose is to determine and ride the trend as far as possible.
So users can identify:
UPTREND : when nQQE Histogram is GREEN (nQQE is above 10)
DOWNTREND : when nQQE Histogram is RED (nQQE is below -10)
SIDEWAYS: when nQQE Histogram is YELLOW (nQQE is between -10 and 10)
Calculation is very simple;
RSI based QQE oscillates between 0-100
nQQE is simply calculated as:
nQQE=QQE-50
to make the indicator fluctuate around 0 level to get more accurate signals.
Various alarms added.
Kıvanç Özbilgiç
BTC and ETH Long strategy - version 2I wrote my first article in May 2020. See below
BTC and ETH Long strategy - version1
After 6 months, it is now time to check the result of my script for the last 6 months.
XBTUSD (4H): 14/05/2020 --> 22/11/2020 = +78% in 4 trades
ETHXBT (4H): 14/05/2020 --> 22/11/2020 = +21% in 9 trades
ETHUSD (4H): 14/05/2020 --> 22/11/2020 = +90% in 6 trades
Using the signals from this strategy to trade manually has shown that this was a bit frustrating because of the low rate of winning trades.
If you have to enter 100 trades and see 75% of them failing and 25% winning, this is frustrating. For sure the strategy makes good money but it is difficult to hold this mentality.
So, I have reviewed and modified it to get a higher winning rate.
After few days of work, tests and validation, I managed to get a wining rate close to 60%.
The key element was also to decrease the number of trades by using a higher time frame. (4H candles instead of 2H candles).
- Entry in position is based on
MACD, EMA (20), SMA (100), SMA (200) moving up
AND EMA (20) > SMA (100)
AND SMA (100) > SMA (200)
- Exit the position if: Stoploss is reached OR EMA (20) crossUnder SMA (100)
The goal of this new script is to be able to follow the signals manually and only make few trades per years.
I have also validated it against some other altcoins where some are giving very good results.
Here are some results for 2020 (from 01/01/2020 until now (22/11/2020). Those results are the one I get when using 4H candles.
ETH/USD: +144% in 8 trades.
BTC/USD: +120% in 7 trades.
ETH/BTC: +33% in 9 trades.
ICX/USD: +123% in 10 trades.
LINK/USD: +155% in 11 trades.
MLN/USD: +388% in 8 trades.
ADA/USD: +180% in 7 trades.
LINK/BTC: +97% in 10 trades.
The best is that above results are without considering compound effect. If you re-invest all gains done in each new trade, this will give you the below results :)
ETH/USD: +189% in 8 trades.
BTC/USD: +260% in 7 trades.
ETH/BTC: +29% in 9 trades.
ICX/USD: +112% in 10 trades.
LINK/USD: +222% in 11 trades.
MLN/USD: +793% in 8 trades.
ADA/USD: +319% in 7 trades.
LINK/BTC: +103% in 10 trades.
As you can see, the results are good and the number of trades for 11 months is not big, which allows the trader to place orders manually.
But still, I'm lazy :), so, I have also coded this strategy in HaasScript language which allows you to automate this strategy using the HaasOnline software specialized in automated crypto trading.
I hope that this strategy will give you ideas or will be the starting point for your own strategy.
Let me know if you need more details.
Pipe Bottoms Indicator Based on Thomas Bulkowski's TheoriesPipe bottom is a great indicator of short-term bullish reversal trading. Pipe bottoms appear as 2 "spikes" on the chart after a 2 weeks price drop downtrend, which look like 2 parallel lines on the chart. Based on Bulkowski and the definition on his Patternsite, those 2 "spikes" candles can be any shape, whether doji or any other kinds, thus, wicks length or candle bodies are NOT required in this type of trends. However, a wide price range for these 2 spikes compared to other candles that appeared in 2 weeks is required, so I made sure these 2 pipe bottoms have true ranges (candle length) bigger than the average true ranges in the past 10 trading days (14 calendar days).
Then, a large price overlap must be between these 2 pipe bottoms, so I made sure that the high of either candle of the 2 pipe bottoms must be bigger than 40% of the true range added from the low of another candle, which in short, means that the high of the lower candle will at least be around the middle of the higher candle, and that will ensure price overlap. You can make this 50%, 60% or even 70% of the true range to ensure even greater price overlap, but you will find out that the signal amounts will decrease quite a lot after adjusting.
Bulkowski also suggested 1% variation of the bottom price (low) of those 2 candles, I put it 5% (0.05) personally to get more signals since I do not solely rely on this indicator, and I want more pipe bottoms to show up on my chart for screening purposes. So, feel free to adjust that number for the identification of this pattern.
Finally, the way I ensure it has been a downtrend or price drop is by checking if the price today is below the average of the last 10 trading days (14 calendar days), the price of the pipe bottoms must be below the moving averages of the past 10 trading days. I use hl2 here, feel free to change it to close or open as fit your strategy. Also, you can do this by making sure the candle close prices are decreasing in the past 10 trading days, or any other ways to ensure it's been in a downtrend, but for me, this works fine since again, this is just one of the many patterns I use, so I want more indicators to show up.
So, as you can see on the chart. Whenever the pattern fits the indicator, a small white cross will show up under the candle with "Pipe" text next to it. But do NOT rush to buy yet, because in order to satisfy the pipe bottom pattern, the current close price must be higher than the high of the pipe bottom. And you will see green arrowups when a pipe bottom occurred the last candle, and the current close price is above the high of the pipe bottoms, that would be the entry point of this indicator.
Overall it's a good pattern, especially for a trading bullish reversal after a huge price drop. You can adjust many numbers as I mentioned above to fit your needs, but make sure to add this with other indicators for your strategy, using only 1 indicator or pattern along is never a wise thing, especially in trading. Thanks guys, please like and share.
BTC VIP EMA CROSS Buy/Sell (GC & DC)EMA cross 5&10 standard-setting with add on of BUY/SELL signal ( GC & DC) which will make the traders have an indication of buy and sell easily and clearly.
An exponential moving average strategy, or EMA strategy, is used to identify the predominant trend in the market. It can also provide the support and resistance level to execute your trade. Indicators: v4 (default setting), EMA 5 10 Crossover (default setting)
Preferred Time Frame(s):15-Minute, 30-Minute, 1-Hour, 4-Hour, 1-Day
Strategy
Long Entry Rules
Enter a buy in the market if the following indicator or chart pattern takes center stage:
If the blue upward pointing arrow of the EMA 5 10 Crossover custom indicator gets aligned just somewhat below the candlesticks as seen in Fig. 1.0, the market sentiment is said to be bullish, hence a trigger to go long on the pair of interest.
If the light blue line of the custom indicator gets outlined just below price bars as illustrated in Fig. 1.0, price is said to be pushed somewhat higher i.e. a trigger to buy the asset of focus.
Exit Strategy/Take Profit for Buy Entry
Exit or take profit if the following rules or conditions takes precedence:
If the red downward pointing arrow of the EMA 5 10 Crossover custom indicator forms above price bars as depicted in Fig. 1.0 while a buy signal is ongoing in the market, a possible price dip is said to be looming, as such an exit or take profit is advised.
If the red line of the custom indicator forms above the candlestick during a bullish trend, it is a pointer to a possible price dip, hence an exit or take profit is advised.
Intrinsic value calculation Intrinsic value calculator based on Warren Buffet's and Ben Graham's work
In value investing determing the true value of a COMPANY instead of a stock price is crucial.
This little indicator shows the "Intrinsic value" of the choosen stock meaning the value of the stock in 10 years time. Calculation is based on historical book value's average annual growth rate and dividends paid.
Since this is about long therm investing, use monthly charts.
"Intrinsic value can be defined simply: It is the discounted value of the cash that can be taken out of a business during its remaining life.”
– Warren Buffett
One way to calculate that is by the growth in per share book value and dividends taken in the forseeable future (10 years) than discount it with the prevailing 10 year note's rate.
In the inputs you have to set 2 variables:
1. How many years back you have the first data for book value per share available?
2. What was the per share book value that year?
(Bookvalue is ploted in olive colour and you can get the oldest one if you move your cursor over the latest data on the left)
CAUTION! You have to reenter it for every stock you analyse as this is stock-specific data!
After setting the input data, you will see the "Intrinsic Value"'s pink curve ploted over the price chart.
If the price is well below the pink line, the company is undervalued and can be a possible applicant for long therm investment.
Margin of safety: when the current price is 50% below the intrinsic value that means a 10% yearly growth potential (100% growth in 10 years) or a 100% margin of safety.
I am a beginer in Pine so please excuse my coding...
If anybody knows hot to extract historical data from 15 years ago, please share it with me, so I can automate the whole calculation without inputs necessary.
M-OscillatorM-Oscillator developed By Mohamed Fawzy, MFTA, CFTe
as Written in IFTA Journal 2018 Edition
more info : ifta.org
Interpretation
• M-Oscillator is a bounded oscillator that moves between (-14) and (+14),
• Movement above 10 is considered overbought, and movement below -10 is oversold.
Overbought/Oversold rule:
• Buy when the M-Oscillator violates the (-10) level to the downside and crosses back to the upside.
• Sell when the M-Oscillator crosses above the (+10) level and crosses back to the downside.
Crossover on Extreme Levels
• Sell signals are triggered when the M-Oscillator crosses its signal line above (13), which indicates an extreme market condition
• Buy signals are triggered when the M-Oscillator crosses its signal line below (- 13)
2-Period RSI strategy (with filter)2-period RSI strategy backtest described in several books of the trader Larry Connors . This strategy uses a 2 periods RSI , one slow arithmetic moving average and one fast arithmetic moving average.
Entry signal:
- RSI 2 value below oversold level (Larry Connors usually sets oversold to be below 5, but other authors prefer to work below 10 due to the higher number of signals).
- Closing above the slow average (200 periods).
- Entry at closing of candle or opening of next candle.
Exit signal:
- Occurs when the candlestick closes above the fast average (the most common fast average is 5 periods, but some traders also suggest the 10 period average).
Entry Filter (modification made by me):
- Applied an RSI2 arithmetic moving average to smooth out oscillations.
- Entered only when RSI2 is below oversold level and RSI2 moving average is below 30.
* NOTE: In the stocks that I evaluate daily the averages of 4 and 6 periods work very well as a filter.
Comments:
This strategy works very well in Daily charts but can be applied in other chart times as well. As this is a strategy to catch market fluctuations, it presents different results with different stocks.
I have been applying this strategy to the stocks of the Brazilian market (BOVESPA) and have enjoyed the result. Every day I evaluate the stocks that are generating entry signals and choose which one to trade based on the stocks with the highest Profit Value.
The RSI 2 averaging filter probably will reduce profit of the backtests because reduces the number of signals, but the Profit Value will usually increase. For me this was a good thing because without the filter, this strategy usually shows more signals than I have capital to allocate.
Before entering a trade I look at which fast average the paper has the highest Profit Value and then I use this average as my output signal for that trade (this change has greatly improved the result of the outputs).
This strategy does not use Stop Loss because normally Stop Loss decreases effectiveness (profit). In any case, the option to apply a percentage Stop Loss if desired is added in the script. As the strategy does not use stop, extra caution with risk management is advisable. I advise not to allocate more than 20% of the trade capital in the same operation.
I'm still studying ways to improve this strategy, but so far this is the best setup I've found. Suggestions are always welcome and we can test to see if they improve the backtest result.
Good luck and good trades.
================================================
Backtest das estratégia do IFR de 2 períodos descrita em varios livros do trader Larry Connors . Esta estratégia usa um IFR de 2 períodos, uma média movel aritmética lenta e uma média movel aritmética rápida.
Sinal de entrada:
- Valor do IFR 2 abaixo do nível de sobrevenda (Larry Connors usualmente define sobrevenda sendo abaixo de 5, mas outros autores preferem trabalhar abaixo de 10 devido ao maior número de sinais).
- Fechamento acima da média lenta (200 períodos).
- Realizado a compra no fechamento do candle ou na abertura do candle seguinte.
Sinal de saída:
- Ocorre quando o candle fecha acima da média rápida (a média rápida mais comum é a de 5 períodos, mas alguns traders sugerem também a média de 10 períodos).
Filtro para entrada (modificação feita por mim):
- Aplicado uma média móvel aritmética do IFR2 para suavisar as oscilações.
- Realizado a entrada apenas quando o IFR2 está abaixo do nível de sobrevenda e a média móvel do IFR2 está abaixo de 30.
*OBS: nos ativos que avalio diariamente as médias de 4 e 6 períodos funcionam muito bem como filtro.
Comentários:
Esta estratégia funciona muito bem no tempo gráfico Diário mas pode ser aplicada tambem em outros tempos gráficos. Como trata-se de uma estratégia para pegar oscilações do mercado, ela apresenta diferentes resultados com diferentes ativos.
Eu venho aplicando esta estratégia nos ativos do mercado brasileiro (BOVESPA) e tenho gostado do resultado. Diariamente eu avalio os papeis que estão gerando entrada e escolho qual irei realizar o trade baseado nos papeis que apresentam maior Profit Value.
O filtro da média do IFR 2 reduz o lucro nos backtests pois reduz também a quantidade de sinais, mas em compensação o Profit Value irá normalmente aumentar. Para mim isto foi algo positivo pois, sem o filtro, normalmente esta estratégia apresenta mais sinais do que possuo capital para alocar.
Antes de entrar em um trade eu olho em qual média rápida o papel apresenta maior Profit Value e então eu utilizo está média como meu sinal de saída para aquele trade (esta mudança tem melhorado bastante o resultado das saídas).
Está estratégia não utiliza Stop Loss pois normalmente o Stop Loss diminui a eficácia (lucro). De qualquer maneira, foi acrescentado no script a opção de aplicar um Stop Loss percentual caso seja desejado. Como a estratégia não utiliza stop é aconselhável um cuidado redobrado com o gerenciamento de risco. Eu aconselho não alocar mais de 20% do capital de trade em uma mesma operação.
Ainda estou estudando formas de melhorar esta estratégia, mas até o momento está é a melhor configuração que encontrei. Sugestões são sempre bem vindas e podemos testar para verificar se melhoram o resultado do backtest.
Boa sorte e bons trades.
Pinescript v3 Compatibility Framework (v4 Migration Tool)Pinescript v3 Compatibility Framework (v4 Migration Tool)
This code makes most v3 scripts work in v4 with only a few minor changes below. Place the framework code before the first input statement.
You can totally delete all comments.
Pros:
- to port to v4 you only need to make a few simple changes, not affecting the core v3 code functionality
Cons:
- without #include - large redundant code block, but can be reduced as needed
- no proper syntax highlighting, intellisence for substitute constant names
Make the following changes in v3 script:
1. standard types can't be var names, color_transp can't be in a function, rename in v3 script:
color() => color.new()
bool => bool_
integer => integer_
float => float_
string => string_
2. init na requires explicit type declaration
float a = na
color col = na
3. persistent var init (optional):
s = na
s := nz(s , s) // or s := na(s ) ? 0 : s
// can be replaced with var s
var s = 0
s := s + 1
___________________________________________________________
Key features of Pinescript v4 (FYI):
1. optional explicit type declaration/conversion (you still can't cast series to int)
float s
2. persistent var modifier
var s
var float s
3. string series - persistent strings now can be used in cond and output to screen dynamically
4. label and line objects
- can be dynamically created, deleted, modified using get/set functions, moved before/after the current bar
- can be in if or a function unlike plot
- max limit: 50-55 label, and 50-55 line drawing objects in addition to already existing plots - both not affected by max plot outputs 64
- can only be used in the main chart
- can serve as the only output function - at least one is required: plot, barcolor, line, label etc.
- dynamic var values (including strings) can be output to screen as text using label.new and to_string
str = close >= open ? "up" : "down"
label.new(bar_index, high, text=str)
col = close >= open ? color.green : color.red
label.new(bar_index, na, "close = " + tostring(close), color=col, textcolor=color.white, style=label.style_labeldown, yloc=yloc.abovebar)
// create new objects, delete old ones
l = line.new(bar_index, high, bar_index , low , width=4)
line.delete(l )
// free object buffer by deleting old objects first, then create new ones
var l = na
line.delete(l)
l = line.new(bar_index, high, bar_index , low , width=4)
Turtle Trade Channels by KıvanÇ fr3762his trend following system was designed by Dennis Gartman and Bill Eckhart, and relies on breakouts of historical highs and lows to take and close trades: it is the complete opposite to the "buy low and sell high" approach. This trend following system was taught to a group of average and normal individuals, and almost everyone turned into a profitable trader.
The main rule is "Trade an N-day breakout and take profits when an M-day high or low is breached (N must me above M)". Examples:
Buy a 10-day breakout and close the trade when price action reaches a 5-day low.
Go short a 20-day breakout and close the trade when price action reaches a 10-day high.
In this indicator, the red line is the trading line, and the dotted blue line is the exit line. Original system is:
Go long when the trading line crosses below close price
Go short when the trading line rosses above close price
Exit long positions when the price touches the exit line
Exit short positions when the price touches the exit line
Recommended initial stop-loss is ATR * 2 from the opening price. Default system parameters were 20,10 and 55,20.
Original Turtle Rules:
To trade exactly like the turtles did, you need to set up two indicators representing the main and the failsafe system.
Set up the main indicator with TradePeriod = 20 and StopPeriod = 10 (A.k.a S1)
Set up the failsafe indicator with TradePeriod = 55 and StopPeriod = 20 using a different color. (A.k.a S2)
The entry strategy using S1 is as follows
Buy 20-day breakouts using S1 only if last signaled trade was a loss.
Sell 20-day breakouts using S1 only if last signaled trade was a loss.
If last signaled trade by S1 was a win, you shouldn't trade -Irregardless of the direction or if you traded last signal it or not-
The entry strategy using S2 is as follows:
Buy 55-day breakouts only if you ignored last S1 signal and the market is rallying without you
Sell 55-day breakouts only if you ignored last S1 signal and the market is pluging without you
The turtles had a progressive position sizing approach that boosted their winnings. Once a trading decision has been made you should...
Developers: Dennis Gartman and Bill Eckhart
İndikatörü geliştiren: Dennis Gartman and Bill Eckhart
Amazing Crossover System - 100+ pips per day!I got the main concept for this system on another site. While I have made one important change, I must stress that the heart of this system was created by someone else! We must give credit where credit is due!
Y'all know baby pips. @ForexPhantom published about this system and did both back and forward test around 10 years ago.
I found it on the sit and now I put it to code to see how it performs. I assume 10 points spread for every trade. I use Renesource or AxiTrader to get the low spreads.
There are 2 mods, the single trades and constant trading on the direction.
Main concept
Indicators
5 EMA -- YELLOW
10 EMA -- RED
RSI (10 - Apply to Median Price: HL/2) -- One level at 50.
TIME FRAME
1 Hour Only (very important!)
PAIRS
Virtually any pair seems to work as this is strictly technical analysis.
I recommend sticking to the main currencies and avoiding cross currencies (just his preference).
WHEN TO ENTER A TRADE
Enter LONG when the Yellow EMA crosses the Red EMA from underneath.
RSI must be approaching 50 from the BOTTOM and cross 50 to warrant entry.
Enter SHORT when the Yellow EMA crosses the Red EMA from the top.
RSI must be approaching 50 from the TOP and cross 50 to warrant entry.
I've attached a picture which demonstrates all these conditions.
That's it!
f.bpcdn.co
Trend Score by KIVANÇ fr3762Trend Score compares close prices between last close with previous closes by a certain period of time.
It's like momentum but gives a score +1 when close price is equal to or above (defaultly) 10 bars ago and gives a score of -1 when below.
calculation continues from default length to the 2 times of length.
Defaultly (for 10 bars length)
If Trend Score converges to 10; that means there's a strong uptrend
conversely if Trend Score converges to -10; that means a strong downtrend market is on.
JSE Wyckoff Wave Volume Code// The Stock Market Institute (SMI) describes an propriety indicator the "SMI Wyckoff Wave" for US Stocks. This code is an attempt to make a Wyckoff Wave for the Johannesburg Stock Exchange (JSE).
// The JSE Wyckoff Wave is in a separate code. This is the code for the volume of the wave. Please see code for the JSE Wyckoff Wave which goes with this indicator.
//
// The Wave presents a normalized price for the 10 selected stocks (An Index for the 10 stocks).
// The theory is to select stocks that are widely held, market leaders, actively traded and participate in important market moves.
// This is only my attempt to select 10 stocks and a different selection can be made.
// I am not certain how SMI determine their weightings but what I have done it to equalize the Rand value of the stock volumne so that moves are of equal magnitude.
// The then provides a view of the overall condition of the market and volume flow in the market.
//
// I have used the September 2018 price to normalize the stock price for the 10 selected stocks based. The stocks and weightings can be changed periodically depending on the performance and leadership.
//
// Please, let me know if there is a better work around this.
The stocks and their weightings are:
"JSE:BTI"/0.79
"JSE:SHP"/2.87
"JSE:NPN"/0.18
"JSE:AGL"/1.96
"JSE:SOL"/1.0
"JSE:CFR"/4.42
"JSE:MND"/1.40
"JSE:MTN"/7.63
"JSE:SLM"/7.29
"JSE:FSR"/8.25
JSE Wyckoff WaveThe Stock Market Institute (SMI) describes an propriety indicator the "SMI Wyckoff Wave" for US Stocks. This code is an attempt to make a Wyckoff Wave for the Johannesburg Stock Exchange (JSE). Once the wave has been established the volume can also be calculated. Please see code for the JSE Wyckoff Wave Volume which goes with this indicator.
The Wave presents a normalized price for the 10 selected stocks (An Index for the 10 stocks). The theory is to select stocks that are widely held, market leaders, actively traded and participate in important market moves. This is only my attempt to select 10 stocks and a different selection can be made. I am not certain how SMI determine their weightings but what I have done it to equalize the Rand value of the stock so that moves are of equal magnitude. The then provides a view of the overall condition of the market and volume flow in the market.
I have used the September 2018 price to normalize the stock price for the 10 selected stocks based. The stocks and weightings can be changed periodically depending on the performance and leadership.
Most Indecies when constructed assume that all high prices and all low prices happen at the same time and therefor inflate the wicks of the bars. To make the wave more representatives for the SMI Wyckoff Wave the price is determined on the 5 minute timeframe which removes this bias. However, TradingView does not calculate properly when selecting a lower timeframe than in current period. A work around is to call the sma of the highs and add these which provides more realistic tails. Please, let me know if there is a better work around this.
The stocks and their weightings are:
"JSE:BTI"*0.79
"JSE:SHP"*2.87
"JSE:NPN"*0.18
"JSE:AGL"*1.96
"JSE:SOL"*1.0
"JSE:CFR"*4.42
"JSE:MND"*1.40
"JSE:MTN"*7.63
"JSE:SLM"*7.29
"JSE:FSR"*8.25
OHLC Daily Resolution BandsShout out to nPE- for the idea.
Bands made with stdev from 10 day OHLC.
Keeps resolution to daily, so you can use bands as daily pivots for day trading.
Upper band 1=yesterday close + 0.5 std(ohlc,10)
Upper band 1=yesterday close + 1 std(ohlc,10)
Mid=yesterday close
Lower band 1=yesterday close - 0.5 std(ohlc,10)
Lower band 2=yesterday close - 1 std(ohlc,1
XPloRR MA-Buy ATR-Trailing-Stop Long Term Strategy Beating B&HXPloRR MA-Buy ATR-MA-Trailing-Stop Strategy
Long term MA Trailing Stop strategy to beat Buy&Hold strategy
None of the strategies that I tested can beat the long term Buy&Hold strategy. That's the reason why I wrote this strategy.
Purpose: beat Buy&Hold strategy with around 10 trades. 100% capitalize sold trade into new trade.
My buy strategy is triggered by the EMA(blue) crossing over the SMA curve(orange).
My sell strategy is triggered by another EMA(lime) of the close value crossing the trailing stop(green) value.
The trailing stop value(green) is set to a multiple of the ATR(15) value.
ATR(15) is the SMA(15) value of the difference between high and low values.
Every stock has it's own "DNA", so first thing to do is find the right parameters to get the best strategy values voor EMA, SMA and Trailing Stop.
Then keep using these parameter for future buy/sell signals only for that particular stock.
Do the same for other stocks.
Here are the parameters:
Exponential MA: buy trigger when crossing over the SMA value (use values between 11-50)
Simple MA: buy trigger when EMA crosses over the SMA value (use values between 20 and 200)
Stop EMA: sell trigger when Stop EMA of close value crosses under the trailing stop value (use values between 8 and 16)
Trailing Stop #ATR: defines the trailing stop value as a multiple of the ATR(15) value
Example parameters for different stocks (Start capital: 1000, Order=100% of equity, Period 1/1/2005 to now):
BAR(Barco): EMA=11, SMA=82, StopEMA=12, Stop#ATR=9
Buy&HoldProfit: 45.82%, NetProfit: 294.7%, #Trades:8, %Profit:62.5%, ProfitFactor: 12.539
AAPL(Apple): EMA=12, SMA=45, StopEMA=12, Stop#ATR=6
Buy&HoldProfit: 2925.86%, NetProfit: 4035.92%, #Trades:10, %Profit:60%, ProfitFactor: 6.36
BEKB(Bekaert): EMA=12, SMA=42, StopEMA=12, Stop#ATR=7
Buy&HoldProfit: 81.11%, NetProfit: 521.37%, #Trades:10, %Profit:60%, ProfitFactor: 2.617
SOLB(Solvay): EMA=12, SMA=63, StopEMA=11, Stop#ATR=8
Buy&HoldProfit: 43.61%, NetProfit: 151.4%, #Trades:8, %Profit:75%, ProfitFactor: 3.794
PHIA(Philips): EMA=11, SMA=80, StopEMA=8, Stop#ATR=10
Buy&HoldProfit: 56.79%, NetProfit: 198.46%, #Trades:6, %Profit:83.33%, ProfitFactor: 23.07
I am very curious to see the parameters for your stocks and please make suggestions to improve this strategy.
Mattzab ArrowsMattzab Arrows
THE BASICS
Buy and Sell Signal Arrows
Tack Marks to show how close the next opposite arrow might be- showing possible trend reversals
Standard Bollinger Bands
10-Day SMA Line
Configurable
Open Source
THE NITTY GRITTY
For starters, all values listed below can be changed in the settings. Length of time, as well as source, can be changed. For the Hidden EMA, this can be made visible by increasing its transparency.
ARROWS
The buy and sell signal arrows are based on price and MACD histogram.
The MACD settings are as follows: 10 day fast EMA , 20 day slow EMA , 5 day SMA signal smoothing. Instead of close price, we are using the average point of the day's high, low, and close.
For the arrows, current price and yesterday's price are using hl2 for high/low average.
A BUY arrow is created when:
Current Price IS GREATER THAN Previous Price _AND_ Current MACD Histogram IS GREATER THAN Previous MACD Histogram.
Important Note! Because the MACD Histogram repaints, the buy arrows may appear, then disappear later in the day, if the MACD changes. Check on the changelog to see if I've fixed it by the time you're reading this. (TradingView doesn't let you edit the description after it's been posted)
A SELL arrow is created when:
Current Price IS LESS THAN Previous Price _AND_ Current MACD Histogram IS LESS THAN Yesterday's MACD Histogram _AND_ Close Price is below _EITHER_ the Hidden EMA (default set to 4) _OR_ the Visible SMA (Default set to 10, which is the black line).
The hidden EMA can be made visible by increasing it's transparency in the Style tab.
Including the requirement to only sell if the standard conditions are met, PLUS being below one of those moving average lines, helps to prevent false sell arrows and repainting.
TACK MARKS
The Red Tack is the threshold, or barrier, for the next arrow. It will not move. It is based on previous High/Low/Close Price + MACD.
The Blue Tack is the current point in space for our average Price and MACD Delta Values. It will move throughout the day (or hour or minute depending on your resolution). The Blue Tack will give you an indication of how close or how far from the reversal threshold (Red Tack) the ticker is at that point.
While the Blue Tack is ABOVE Red, the most recent signal arrow will be a buy, and we are in a buy/hold period.
While the Blue Tack is BELOW Red, the most recent signal arrow will be a sell, and we are in a sell/wait period.
If the Blue Tack crosses above or below Red, you'll get the next arrow.
MOVING AVERAGE LINES
There are three moving average lines in this indicator.
The first is black, and is by default a 10-Day Simple Moving Average Line.
This black line is a good safeguard against selling too early. This is a good support line and that's how I use it.
The second is invisible, but can be made visible in the Styling, and is by default a 4-Day Exponential Moving Average Line
The third is the blue 20-Day Bollinger Band line.
BOLLINGER BANDS
The Bollinger Bands are unmodified and are just a background indicator for your use. If you prefer not to see the Bollinger Bands , change their transparency to 0% to hide them. I've cleaned up the Bollinger Bands to make the indicator as a whole- easier on the eyes.
Please leave feedback on how the script works for you, if you run into problems, if you have any changes you'd like to see, etc.
MACDouble + RSI (rec. 15min-2hr intrv) Uses two sets of MACD plus an RSI to either long or short. All three indicators trigger buy/sell as one (ie it's not 'IF MACD1 OR MACD2 OR RSI > 1 = buy", its more like "IF 1 AND 2 AND RSI=buy", all 3 match required for trigger)
The MACD inputs should be tweaked depending on timeframe and what you are trading. If you are doing 1, 3, 5 min or real frequent trading then 21/44/20 and 32/66/29 or other high value MACDs should be considered. If you are doing longer intervals like 2, 3, 4hr then consider 9/19/9 and 21/44/20 for MACDs (experiment! I picked these example #s randomly).
Ideal usage for the MACD sets is to have MACD2 inputs at around 1.5x, 2x, or 3x MACD1's inputs.
Other settings to consider: try having fastlength1=macdlength1 and then (fastlength2 = macdlength2 - 2). Like 10/26/10 and 23/48/20. This seems to increase net profit since it is more likely to trigger before major price moves, but may decrease profitable trade %. Conversely, consider FL1=MCDL1 and FL2 = MCDL2 + (FL2 * 0.5). Example: 10/26/10 and 22/48/30 this can increase profitable trade %, though may cost some net profit.
Feel free to message me with suggestions or questions.
Kay_BBandsV3This is the 3rd version of Kay_BBands.
When +DI (Directional Index ) is above -DI , then Upper band will be visible and vice-versa.
This is when the ADX is above the threshold. 28 is the default in this version. I found its more appealing in 5M time frame.
BLUE - ADX under 10
GREEN - Uptrend, ADX over 10
RED - Downtrend, ADX over 10
Use it with another band with setting 20, 0.6 deviation. Prices keeping above or below the 2nd bands upper or lower bounds shows trending conditions.
I didn't know how to update the old script so published it again.
Changes - :
1) Updated default settings for the indicator
2) ADX setting are now DI (28), ADX (10), adx level to check is 10.
3) IMPORTANT one - When DI is up/down, lower/upper band will also have color (more visible that way.)
Play around the settings.. It really eliminates extra indicator checking visually... Please like if you think idea is good.
CM Renko Overlay BarsCM_Renko Overlay Bars V1
Overlays Renko Bars on Regular Price Bars.
Default Renko plot is based on Average True Range. Look Back period adjustable in Inputs Tab.
If you Choose to use "Traditional" Renko bars and pick the Size of the Renko Bars the please read below.
Value in Input Tab is multiplied by .001 (To work on Forex)
1 = 10 pips on EURUSD - 1 X .001 = .001 or 10 Pips
10 = .01 or 100 Pips
1000 = 1 point to the left of decimal. 1 Point in Stocks etc.
10000 = 10 Points on Stocks etc.
***V2 will fix this issue.
Custom Indicator - No Trade Zone Warning Back Ground Highlights!Years ago I did an analysis of my trades. Every period of the day was profitable except for two. From 10:00-1030, and 1:00 to 1:30. (I was actively Day Trading Futures) Imagine a vertical graph broken down in to 30 minute time segments. I had nice Green bars in every time slot (Showing Net Profits), and HUGE Red Bars from 10 to 10:30 and 1 to 1:30. After analysis I found I made consistent profits at session open, but then I would enter in to bad setups around 10 to make more money. I also found after I took lunch when I came back at 1:00 I would force trades instead of patiently waiting for a great trade setup. I created an indicator that plotted a red background around those times telling me I was not allowed to enter a trade. Profits went up!!! Details on How to adjust times are in 1st Post. You can adjust times and colors to meet your own trading needs.
RSI Donchian Channel [DCAUT]█ RSI Donchian Channel
📊 ORIGINALITY & INNOVATION
The RSI Donchian Channel represents an important synthesis of two complementary analytical frameworks: momentum oscillators and breakout detection systems. This indicator addresses a common limitation in traditional RSI analysis by replacing fixed overbought/oversold thresholds with adaptive zones derived from historical RSI extremes.
Key Enhancement:
Traditional RSI analysis relies on static threshold levels (typically 30/70), which may not adequately reflect changing market volatility regimes. This indicator adapts the reference zones dynamically based on the actual RSI behavior over the lookback period, helping traders identify meaningful momentum extremes relative to recent price action rather than arbitrary fixed levels.
The implementation combines the proven momentum measurement capabilities of RSI with Donchian Channel's breakout detection methodology, creating a framework that identifies both momentum exhaustion points and potential continuation signals through the same analytical lens.
📐 MATHEMATICAL FOUNDATION
Core Calculation Process:
Step 1: RSI Calculation
The Relative Strength Index measures momentum by comparing the magnitude of recent gains to recent losses:
Calculate price changes between consecutive periods
Separate positive changes (gains) from negative changes (losses)
Apply selected smoothing method (RMA standard, also supports SMA, EMA, WMA) to both gain and loss series
Compute Relative Strength (RS) as the ratio of smoothed gains to smoothed losses
Transform RS into bounded 0-100 scale using the formula: RSI = 100 - (100 / (1 + RS))
Step 2: Donchian Channel Application
The Donchian Channel identifies the highest and lowest RSI values within the specified lookback period:
Upper Channel: Highest RSI value over the lookback period, represents the recent momentum peak
Lower Channel: Lowest RSI value over the lookback period, represents the recent momentum trough
Middle Channel (Basis): Average of upper and lower channels, serves as equilibrium reference
Channel Width Dynamics:
The distance between upper and lower channels reflects RSI volatility. Wide channels indicate high momentum variability, while narrow channels suggest momentum consolidation and potential breakout preparation. The indicator monitors channel width over a 100-period window to identify squeeze conditions that often precede significant momentum shifts.
📊 COMPREHENSIVE SIGNAL ANALYSIS
Primary Signal Categories:
Breakout Signals:
Upper Breakout: RSI crosses above the upper channel, indicates momentum reaching new relative highs and potential trend continuation, particularly significant when accompanied by price confirmation
Lower Breakout: RSI crosses below the lower channel, suggests momentum reaching new relative lows and potential trend exhaustion or reversal setup
Breakout strength is enhanced when the channel is narrow prior to the breakout, indicating a transition from consolidation to directional movement
Mean Reversion Signals:
Upper Touch Without Breakout: RSI reaches the upper channel but fails to break through, may indicate momentum exhaustion and potential reversal opportunity
Lower Touch Without Breakout: RSI reaches the lower channel without breakdown, suggests potential bounce as momentum reaches oversold extremes
Return to Basis: RSI moving back toward the middle channel after touching extremes signals momentum normalization
Trend Strength Assessment:
Sustained Upper Channel Riding: RSI consistently remains near or above the upper channel during strong uptrends, indicates persistent bullish momentum
Sustained Lower Channel Riding: RSI stays near or below the lower channel during strong downtrends, reflects persistent bearish pressure
Basis Line Position: RSI position relative to the middle channel helps identify the prevailing momentum bias
Channel Compression Patterns:
Squeeze Detection: Channel width narrowing to 100-period lows indicates momentum consolidation, often precedes significant directional moves
Expansion Phase: Channel widening after a squeeze confirms the initiation of a new momentum regime
Persistent Narrow Channels: Extended periods of tight channels suggest market indecision and accumulation/distribution phases
🎯 STRATEGIC APPLICATIONS
Trend Continuation Strategy:
This approach focuses on identifying and trading momentum breakouts that confirm established trends:
Identify the prevailing price trend using higher timeframe analysis or trend-following indicators
Wait for RSI to break above the upper channel in uptrends (or below the lower channel in downtrends)
Enter positions in the direction of the breakout when price action confirms the momentum shift
Place protective stops below the recent swing low (long positions) or above swing high (short positions)
Target profit levels based on prior swing extremes or use trailing stops to capture extended moves
Exit when RSI crosses back through the basis line in the opposite direction
Mean Reversion Strategy:
This method capitalizes on momentum extremes and subsequent corrections toward equilibrium:
Monitor for RSI reaching the upper or lower channel boundaries
Look for rejection signals (price reversal patterns, volume divergence) when RSI touches the channels
Enter counter-trend positions when RSI begins moving back toward the basis line
Use the basis line as the initial profit target for mean reversion trades
Implement tight stops beyond the channel extremes to limit risk on failed reversals
Scale out of positions as RSI approaches the basis line and closes the position when RSI crosses the basis
Breakout Preparation Strategy:
This approach positions traders ahead of potential volatility expansion from consolidation phases:
Identify squeeze conditions when channel width reaches 100-period lows
Monitor price action for consolidation patterns (triangles, rectangles, flags) during the squeeze
Prepare conditional orders for breakouts in both directions from the consolidation
Enter positions when RSI breaks out of the narrow channel with expanding width
Use the channel width expansion as a confirmation signal for the breakout's validity
Manage risk with stops just inside the opposite channel boundary
Multi-Timeframe Confluence Strategy:
Combining RSI Donchian Channel analysis across multiple timeframes can improve signal reliability:
Identify the primary trend direction using a higher timeframe RSI Donchian Channel (e.g., daily or weekly)
Use a lower timeframe (e.g., 4-hour or hourly) to time precise entry points
Enter long positions when both timeframes show RSI above their respective basis lines
Enter short positions when both timeframes show RSI below their respective basis lines
Avoid trades when timeframes provide conflicting signals (e.g., higher timeframe below basis, lower timeframe above)
Exit when the higher timeframe RSI crosses its basis line in the opposite direction
Risk Management Guidelines:
Effective risk management is essential for all RSI Donchian Channel strategies:
Position Sizing: Calculate position sizes based on the distance between entry point and stop loss, limiting risk to 1-2% of capital per trade
Stop Loss Placement: For breakout trades, place stops just inside the opposite channel boundary; for mean reversion trades, use stops beyond the channel extremes
Profit Targets: Use the basis line as a minimum target for mean reversion trades; for trend trades, target prior swing extremes or use trailing stops
Channel Width Context: Increase position sizes during narrow channels (lower volatility) and reduce sizes during wide channels (higher volatility)
Correlation Awareness: Monitor correlations between traded instruments to avoid over-concentration in similar setups
📋 DETAILED PARAMETER CONFIGURATION
RSI Source:
Defines the price data series used for RSI calculation:
Close (Default): Standard choice providing end-of-period momentum assessment, suitable for most trading styles and timeframes
High-Low Average (HL2): Reduces the impact of closing auction dynamics, useful for markets with significant end-of-day volatility
High-Low-Close Average (HLC3): Provides a more balanced view incorporating the entire period's range
Open-High-Low-Close Average (OHLC4): Offers the most comprehensive price representation, helpful for identifying overall period sentiment
Strategy Consideration: Use Close for end-of-period signals, HL2 or HLC3 for intraday volatility reduction, OHLC4 for capturing full period dynamics
RSI Length:
Controls the number of periods used for RSI calculation:
Short Periods (5-9): Highly responsive to recent price changes, produces more frequent signals with increased false signal risk, suitable for short-term trading and volatile markets
Standard Period (14): Widely accepted default balancing responsiveness with stability, appropriate for swing trading and intermediate-term analysis
Long Periods (21-28): Produces smoother RSI with fewer signals but more reliable trend identification, better for position trading and reducing noise in choppy markets
Optimization Approach: Test different lengths against historical data for your specific market and timeframe, consider using longer periods in ranging markets and shorter periods in trending markets
RSI MA Type:
Determines the smoothing method applied to price changes in RSI calculation:
RMA (Relative Moving Average - Default): Wilder's original smoothing method providing stable momentum measurement with gradual response to changes, maintains consistency with classical RSI interpretation
SMA (Simple Moving Average): Treats all periods equally, responds more quickly to changes than RMA but may produce more whipsaws in volatile conditions
EMA (Exponential Moving Average): Weights recent periods more heavily, increases responsiveness at the cost of potential noise, suitable for traders prioritizing early signal generation
WMA (Weighted Moving Average): Applies linear weighting favoring recent data, offers a middle ground between SMA and EMA responsiveness
Selection Guidance: Maintain RMA for consistency with traditional RSI analysis, use EMA or WMA for more responsive signals in fast-moving markets, apply SMA for maximum simplicity and transparency
DC Length:
Specifies the lookback period for Donchian Channel calculation on RSI values:
Short Periods (10-14): Creates tight channels that adapt quickly to changing momentum conditions, generates more frequent trading signals but increases sensitivity to short-term RSI fluctuations
Standard Period (20): Balances channel responsiveness with stability, aligns with traditional Bollinger Bands and moving average periods, suitable for most trading styles
Long Periods (30-50): Produces wider, more stable channels that better represent sustained momentum extremes, reduces signal frequency while improving reliability, appropriate for position traders and higher timeframes
Calibration Strategy: Match DC length to your trading timeframe (shorter for day trading, longer for swing trading), test channel width behavior during different market regimes, consider using adaptive periods that adjust to volatility conditions
Market Adaptation: Use shorter DC lengths in trending markets to capture momentum shifts earlier, apply longer periods in ranging markets to filter noise and focus on significant extremes
Parameter Combination Recommendations:
Scalping/Day Trading: RSI Length 5-9, DC Length 10-14, EMA or WMA smoothing for maximum responsiveness
Swing Trading: RSI Length 14, DC Length 20, RMA smoothing for balanced analysis (default configuration)
Position Trading: RSI Length 21-28, DC Length 30-50, RMA or SMA smoothing for stable signals
High Volatility Markets: Longer RSI periods (21+) with standard DC length (20) to reduce noise
Low Volatility Markets: Standard RSI length (14) with shorter DC length (10-14) to capture subtle momentum shifts
📈 PERFORMANCE ANALYSIS & COMPETITIVE ADVANTAGES
Adaptive Threshold Mechanism:
Unlike traditional RSI analysis with fixed 30/70 thresholds, this indicator's Donchian Channel approach provides several improvements:
Context-Aware Extremes: Overbought/oversold levels adjust automatically based on recent momentum behavior rather than arbitrary fixed values
Volatility Adaptation: In low volatility periods, channels narrow to reflect tighter momentum ranges; in high volatility, channels widen appropriately
Market Regime Recognition: The indicator implicitly adapts to different market conditions without manual threshold adjustments
False Signal Reduction: Adaptive channels help reduce premature reversal signals that often occur with fixed thresholds during strong trends
Signal Quality Characteristics:
The indicator's dual-purpose design provides distinct advantages for different trading objectives:
Breakout Trading: Channel boundaries offer clear, objective breakout levels that update dynamically, eliminating the ambiguity of when momentum becomes "too high" or "too low"
Mean Reversion: The basis line provides a natural profit target for reversion trades, representing the midpoint of recent momentum extremes
Trend Strength: Persistent channel boundary riding offers an objective measure of trend strength without additional indicators
Consolidation Detection: Channel width analysis provides early warning of potential volatility expansion from compression phases
Comparative Analysis:
When compared to traditional RSI implementations and other momentum frameworks:
vs. Fixed Threshold RSI: Provides market-adaptive reference levels rather than static values, helping to reduce false signals during trending markets where RSI can remain "overbought" or "oversold" for extended periods
vs. RSI Bollinger Bands: Offers clearer breakout signals and more intuitive extreme identification through actual high/low boundaries rather than statistical standard deviations
vs. Stochastic Oscillator: Maintains RSI's momentum measurement advantages (unbounded calculation avoiding scale compression) while adding the breakout detection capabilities of Donchian Channels
vs. Standard Donchian Channels: Applies breakout methodology to momentum space rather than price, providing earlier signals of potential trend changes before price breakouts occur
Performance Characteristics:
The indicator exhibits specific behavioral patterns across different market conditions:
Trending Markets: Excels at identifying momentum continuation through channel breakouts, RSI tends to ride one channel boundary during strong trends, providing trend confirmation
Ranging Markets: Channel width narrows during consolidation, offering early preparation signals for potential breakout trading opportunities
High Volatility: Channels widen to reflect increased momentum variability, automatically adjusting signal sensitivity to match market conditions
Low Volatility: Channels contract, making the indicator more sensitive to subtle momentum shifts that may be significant in calm market environments
Transition Periods: Channel squeezes often precede major trend changes, offering advance warning of potential regime shifts
Limitations and Considerations:
Users should be aware of certain operational characteristics:
Lookback Dependency: Channel boundaries depend entirely on the lookback period, meaning the indicator has no predictive element beyond identifying current momentum relative to recent history
Lag Characteristics: As with all moving average-based indicators, RSI calculation introduces lag, and channel boundaries update only as new extremes occur within the lookback window
Range-Bound Sensitivity: In extremely tight ranges, channels may become very narrow, potentially generating excessive signals from minor momentum fluctuations
Trending Persistence: During very strong trends, RSI may remain at channel extremes for extended periods, requiring patience for mean reversion setups or commitment to trend-following approaches
No Absolute Levels: Unlike traditional RSI, this indicator provides no fixed reference points (like 50), making it less suitable for strategies that depend on absolute momentum readings
USAGE NOTES
This indicator is designed for technical analysis and educational purposes to help traders understand momentum dynamics and identify potential trading opportunities. The RSI Donchian Channel has limitations and should not be used as the sole basis for trading decisions.
Important considerations:
Performance varies significantly across different market conditions, timeframes, and instruments
Historical signal patterns do not guarantee future results, as market behavior continuously evolves
Effective use requires understanding of both RSI momentum principles and Donchian Channel breakout concepts
Risk management practices (stop losses, position sizing, diversification) are essential for any trading application
Consider combining with additional analytical tools such as volume analysis, price action patterns, or trend indicators for confirmation
Backtest thoroughly on your specific instruments and timeframes before live trading implementation
Be aware that optimization on historical data may lead to curve-fitting and poor forward performance
The indicator performs best when used as part of a comprehensive trading methodology that incorporates multiple forms of market analysis, sound risk management, and realistic expectations about win rates and drawdowns.
JK_Traders_Reality_LibLibrary "JK_Traders_Reality_Lib"
This library contains common elements used in Traders Reality scripts
calcPvsra(pvsraVolume, pvsraHigh, pvsraLow, pvsraClose, pvsraOpen, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor, darkGreyCandleColor, lightGrayCandleColor)
calculate the pvsra candle color and return the color as well as an alert if a vector candle has apperared.
Situation "Climax"
Bars with volume >= 200% of the average volume of the 10 previous chart TFs, or bars
where the product of candle spread x candle volume is >= the highest for the 10 previous
chart time TFs.
Default Colors: Bull bars are green and bear bars are red.
Situation "Volume Rising Above Average"
Bars with volume >= 150% of the average volume of the 10 previous chart TFs.
Default Colors: Bull bars are blue and bear are violet.
Parameters:
pvsraVolume (float) : the instrument volume series (obtained from request.sequrity)
pvsraHigh (float) : the instrument high series (obtained from request.sequrity)
pvsraLow (float) : the instrument low series (obtained from request.sequrity)
pvsraClose (float) : the instrument close series (obtained from request.sequrity)
pvsraOpen (float) : the instrument open series (obtained from request.sequrity)
redVectorColor (simple color) : red vector candle color
greenVectorColor (simple color) : green vector candle color
violetVectorColor (simple color) : violet/pink vector candle color
blueVectorColor (simple color) : blue vector candle color
darkGreyCandleColor (simple color) : regular volume candle down candle color - not a vector
lightGrayCandleColor (simple color) : regular volume candle up candle color - not a vector
@return
adr(length, barsBack)
Parameters:
length (simple int) : how many elements of the series to calculate on
barsBack (simple int) : starting possition for the length calculation - current bar or some other value eg last bar
@return adr the adr for the specified lenght
adrHigh(adr, fromDo)
Calculate the ADR high given an ADR
Parameters:
adr (float) : the adr
fromDo (simple bool) : boolean flag, if false calculate traditional adr from high low of today, if true calcualte from exchange midnight
@return adrHigh the position of the adr high in price
adrLow(adr, fromDo)
Parameters:
adr (float) : the adr
fromDo (simple bool) : boolean flag, if false calculate traditional adr from high low of today, if true calcualte from exchange midnight
@return adrLow the position of the adr low in price
splitSessionString(sessXTime)
given a session in the format 0000-0100:23456 split out the hours and minutes
Parameters:
sessXTime (simple string) : the session time string usually in the format 0000-0100:23456
@return
calcSessionStartEnd(sessXTime, gmt)
calculate the start and end timestamps of the session
Parameters:
sessXTime (simple string) : the session time string usually in the format 0000-0100:23456
gmt (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
@return
drawOpenRange(sessXTime, sessXcol, showOrX, gmt)
draw open range for a session
Parameters:
sessXTime (simple string) : session string in the format 0000-0100:23456
sessXcol (simple color) : the color to be used for the opening range box shading
showOrX (simple bool) : boolean flag to toggle displaying the opening range
gmt (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
@return void
drawSessionHiLo(sessXTime, showRectangleX, showLabelX, sessXcolLabel, sessXLabel, gmt, sessionLineStyle)
Parameters:
sessXTime (simple string) : session string in the format 0000-0100:23456
showRectangleX (simple bool)
showLabelX (simple bool)
sessXcolLabel (simple color) : the color to be used for the hi/low lines and label
sessXLabel (simple string) : the session label text
gmt (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
sessionLineStyle (simple string) : the line stile for the session high low lines
@return void
calcDst()
calculate market session dst on/off flags
@return indicating if DST is on or off for a particular region
timestampPreviousDayOfWeek(previousDayOfWeek, hourOfDay, gmtOffset, oneWeekMillis)
Timestamp any of the 6 previous days in the week (such as last Wednesday at 21 hours GMT)
Parameters:
previousDayOfWeek (simple string) : Monday or Satruday
hourOfDay (simple int) : the hour of the day when psy calc is to start
gmtOffset (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
oneWeekMillis (simple int) : the amount if time for a week in milliseconds
@return the timestamp of the psy level calculation start time
getdayOpen()
get the daily open - basically exchange midnight
@return the daily open value which is float price
newBar(res)
new_bar: check if we're on a new bar within the session in a given resolution
Parameters:
res (simple string) : the desired resolution
@return true/false is a new bar for the session has started
toPips(val)
to_pips Convert value to pips
Parameters:
val (float) : the value to convert to pips
@return the value in pips
rLabel(ry, rtext, rstyle, rcolor, valid, labelXOffset)
a function that draws a right aligned lable for a series during the current bar
Parameters:
ry (float) : series float the y coordinate of the lable
rtext (simple string) : the text of the label
rstyle (simple string) : the style for the lable
rcolor (simple color) : the color for the label
valid (simple bool) : a boolean flag that allows for turning on or off a lable
labelXOffset (int) : how much to offset the label from the current position
rLabelOffset(ry, rtext, rstyle, rcolor, valid, labelOffset)
a function that draws a right aligned lable for a series during the current bar
Parameters:
ry (float) : series float the y coordinate of the lable
rtext (string) : the text of the label
rstyle (simple string) : the style for the lable
rcolor (simple color) : the color for the label
valid (simple bool) : a boolean flag that allows for turning on or off a lable
labelOffset (int)
rLabelLastBar(ry, rtext, rstyle, rcolor, valid, labelXOffset)
a function that draws a right aligned lable for a series only on the last bar
Parameters:
ry (float) : series float the y coordinate of the lable
rtext (string) : the text of the label
rstyle (simple string) : the style for the lable
rcolor (simple color) : the color for the label
valid (simple bool) : a boolean flag that allows for turning on or off a lable
labelXOffset (int) : how much to offset the label from the current position
drawLine(xSeries, res, tag, xColor, xStyle, xWidth, xExtend, isLabelValid, xLabelOffset, validTimeFrame)
a function that draws a line and a label for a series
Parameters:
xSeries (float) : series float the y coordinate of the line/label
res (simple string) : the desired resolution controlling when a new line will start
tag (simple string) : the text for the lable
xColor (simple color) : the color for the label
xStyle (simple string) : the style for the line
xWidth (simple int) : the width of the line
xExtend (simple string) : extend the line
isLabelValid (simple bool) : a boolean flag that allows for turning on or off a label
xLabelOffset (int)
validTimeFrame (simple bool) : a boolean flag that allows for turning on or off a line drawn
drawLineDO(xSeries, res, tag, xColor, xStyle, xWidth, xExtend, isLabelValid, xLabelOffset, validTimeFrame)
a function that draws a line and a label for the daily open series
Parameters:
xSeries (float) : series float the y coordinate of the line/label
res (simple string) : the desired resolution controlling when a new line will start
tag (simple string) : the text for the lable
xColor (simple color) : the color for the label
xStyle (simple string) : the style for the line
xWidth (simple int) : the width of the line
xExtend (simple string) : extend the line
isLabelValid (simple bool) : a boolean flag that allows for turning on or off a label
xLabelOffset (int)
validTimeFrame (simple bool) : a boolean flag that allows for turning on or off a line drawn
drawPivot(pivotLevel, res, tag, pivotColor, pivotLabelColor, pivotStyle, pivotWidth, pivotExtend, isLabelValid, validTimeFrame, levelStart, pivotLabelXOffset)
draw a pivot line - the line starts one day into the past
Parameters:
pivotLevel (float) : series of the pivot point
res (simple string) : the desired resolution
tag (simple string) : the text to appear
pivotColor (simple color) : the color of the line
pivotLabelColor (simple color) : the color of the label
pivotStyle (simple string) : the line style
pivotWidth (simple int) : the line width
pivotExtend (simple string) : extend the line
isLabelValid (simple bool) : boolean param allows to turn label on and off
validTimeFrame (simple bool) : only draw the line and label at a valid timeframe
levelStart (int) : basically when to start drawing the levels
pivotLabelXOffset (int) : how much to offset the label from its current postion
@return the pivot line series
getPvsraFlagByColor(pvsraColor, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor, lightGrayCandleColor)
convert the pvsra color to an internal code
Parameters:
pvsraColor (color) : the calculated pvsra color
redVectorColor (simple color) : the user defined red vector color
greenVectorColor (simple color) : the user defined green vector color
violetVectorColor (simple color) : the user defined violet vector color
blueVectorColor (simple color) : the user defined blue vector color
lightGrayCandleColor (simple color) : the user defined regular up candle color
@return pvsra internal code
updateZones(pvsra, direction, boxArr, maxlevels, pvsraHigh, pvsraLow, pvsraOpen, pvsraClose, transperancy, zoneupdatetype, zonecolor, zonetype, borderwidth, coloroverride, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor)
a function that draws the unrecovered vector candle zones
Parameters:
pvsra (int) : internal code
direction (simple int) : above or below the current pa
boxArr (array) : the array containing the boxes that need to be updated
maxlevels (simple int) : the maximum number of boxes to draw
pvsraHigh (float) : the pvsra high value series
pvsraLow (float) : the pvsra low value series
pvsraOpen (float) : the pvsra open value series
pvsraClose (float) : the pvsra close value series
transperancy (simple int) : the transparencfy of the vecor candle zones
zoneupdatetype (simple string) : the zone update type
zonecolor (simple color) : the zone color if overriden
zonetype (simple string) : the zone type
borderwidth (simple int) : the width of the border
coloroverride (simple bool) : if the color overriden
redVectorColor (simple color) : the user defined red vector color
greenVectorColor (simple color) : the user defined green vector color
violetVectorColor (simple color) : the user defined violet vector color
blueVectorColor (simple color) : the user defined blue vector color
cleanarr(arr)
clean an array from na values
Parameters:
arr (array) : the array to clean
@return if the array was cleaned
calcPsyLevels(oneWeekMillis, showPsylevels, psyType, sydDST)
calculate the psy levels
4 hour res based on how mt4 does it
mt4 code
int Li_4 = iBarShift(NULL, PERIOD_H4, iTime(NULL, PERIOD_W1, Li_0)) - 2 - Offset;
ObjectCreate("PsychHi", OBJ_TREND, 0, Time , iHigh(NULL, PERIOD_H4, iHighest(NULL, PERIOD_H4, MODE_HIGH, 2, Li_4)), iTime(NULL, PERIOD_W1, 0), iHigh(NULL, PERIOD_H4,
iHighest(NULL, PERIOD_H4, MODE_HIGH, 2, Li_4)));
so basically because the session is 8 hours and we are looking at a 4 hour resolution we only need to take the highest high an lowest low of 2 bars
we use the gmt offset to adjust the 0000-0800 session to Sydney open which is at 2100 during dst and at 2200 otherwize. (dst - spring foward, fall back)
keep in mind sydney is in the souther hemisphere so dst is oposite of when london and new york go into dst
Parameters:
oneWeekMillis (simple int) : a constant value
showPsylevels (simple bool) : should psy levels be calculated
psyType (simple string) : the type of Psylevels - crypto or forex
sydDST (bool) : is Sydney in DST
@return
adrHiLo(length, barsBack, fromDO)
Parameters:
length (simple int) : how many elements of the series to calculate on
barsBack (simple int) : starting possition for the length calculation - current bar or some other value eg last bar
fromDO (simple bool) : boolean flag, if false calculate traditional adr from high low of today, if true calcualte from exchange midnight
@return adr, adrLow and adrHigh - the adr, the position of the adr High and adr Low with respect to price
drawSessionHiloLite(sessXTime, showRectangleX, showLabelX, sessXcolLabel, sessXLabel, gmt, sessionLineStyle, sessXcol)
Parameters:
sessXTime (simple string) : session string in the format 0000-0100:23456
showRectangleX (simple bool)
showLabelX (simple bool)
sessXcolLabel (simple color) : the color to be used for the hi/low lines and label
sessXLabel (simple string) : the session label text
gmt (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
sessionLineStyle (simple string) : the line stile for the session high low lines
sessXcol (simple color) : - the color for the box color that will color the session
@return void
msToHmsString(ms)
converts milliseconds into an hh:mm string. For example, 61000 ms to '0:01:01'
Parameters:
ms (int) : - the milliseconds to convert to hh:mm
@return string - the converted hh:mm string
countdownString(openToday, closeToday, showMarketsWeekends, oneDay)
that calculates how much time is left until the next session taking the session start and end times into account. Note this function does not work on intraday sessions.
Parameters:
openToday (int) : - timestamps of when the session opens in general - note its a series because the timestamp was created using the dst flag which is a series itself thus producing a timestamp series
closeToday (int) : - timestamp of when the session closes in general - note its a series because the timestamp was created using the dst flag which is a series itself thus producing a timestamp series
@return a countdown of when next the session opens or 'Open' if the session is open now
showMarketsWeekends (simple bool)
oneDay (simple int)
countdownStringSyd(sydOpenToday, sydCloseToday, showMarketsWeekends, oneDay)
that calculates how much time is left until the next session taking the session start and end times into account. special case of intraday sessions like sydney
Parameters:
sydOpenToday (int)
sydCloseToday (int)
showMarketsWeekends (simple bool)
oneDay (simple int)