ISM Indicator As a Strategy Here's a very easy code, plotting the ISM against the SPX. In this exercise, i wanted to see if one could use the ISM indicator only to generate buy/sell signal, and what would be the performance.
What is the ISM
The ISM Manufacturing Index monitors employment, production inventories, new orders and supplier deliveries.By monitoring the ISM Manufacturing Index, investors are able to better understand national economic conditions. When this index is increasing, investors can assume that the stock markets should increase because of higher corporate profits. The opposite can be thought of the bond markets, which may decrease as the ISM Manufacturing Index increases because of sensitivity to potential inflation.
Buy/Sell Signal
ISM above 50 usually good economic condition and vice versa when below 50 . For this code I used 48.50 as my buy/sell signal line.
Results
To test this on a longer time period, I use the SPX index instead of SPY. The results are surprisingly good. 76.92% profitability with 3.03 profit factor.
Conclusion
Investors could use the ISM with other indicators to determine better entry and exit point. I will see if combining the ISM with other custom indicators , could generate better result. Feel free to share your results here.
Cheers
Algo.
Cerca negli script per "profit"
MACD + SMA 200 Strategy (by ChartArt)Here is a combination of the classic MACD (moving average convergence divergence indicator) with the classic slow moving average SMA with period 200 together as a strategy.
This strategy goes long if the MACD histogram and the MACD momentum are both above zero and the fast MACD moving average is above the slow MACD moving average. As additional long filter the recent price has to be above the SMA 200. If the inverse logic is true, the strategy goes short. For the worst case there is a max intraday equity loss of 50% filter.
Save another $999 bucks with my free strategy.
This strategy works in the backtest on the daily chart of Bitcoin, as well as on the S&P 500 and the Dow Jones Industrial Average daily charts. Current performance as of November 30, 2015 on the SPX500 CFD daily is percent profitable: 68% since the year 1970 with a profit factor of 6.4. Current performance as of November 30, 2015 on the DOWI index daily is percent profitable: 51% since the year 1915 with a profit factor of 10.8.
All trading involves high risk; past performance is not necessarily indicative of future results. Hypothetical or simulated performance results have certain inherent limitations. Unlike an actual performance record, simulated results do not represent actual trading. Also, since the trades have not actually been executed, the results may have under- or over-compensated for the impact, if any, of certain market factors, such as lack of liquidity. Simulated trading programs in general are also subject to the fact that they are designed with the benefit of hindsight. No representation is being made that any account will or is likely to achieve profits or losses similar to those shown.
CamarillaStrategy -V1 - H4 and L4 breakout - exits addedExits added using trailing stops.
2.6 Profit Factor and 76% Profitable on SPY , 5M - I think it's a pretty good number for an automated strategy that uses Pivots. I don't think it's possible to add volume and day open price in relation to pivot levels -- that's what I do manually ..
Still trying to add EMA for exits.. it will increase profitability. You can play in pinescript with trailing stops entries..
Madrid Trend SqueezeThis study spots the points that are most profitable in the trend with a code color and shape. This also shows trend divergences and possible reversal or reentry points
Keeping the parameters simple, this study only needs one parameter, the length of the base moving average, which by default is set to 34.
There are seven colors used for the study
Green : Uptrend in general
Lime : Spots the current uptrend leg
Aqua : The maximum profitability of the leg in a long trade
The Squeeze happens when Green+Lime+Aqua are aligned (the larger the values the better)
Maroon : Downtrend in general
Red : Spots the current downtrend leg
Fuchsia: The maximum profitability of the leg in a short trade
The Squeeze happens when Maroon+Red+Fuchsia are aligned (the larger the values the better)
Yellow : The trend has come to a pause and it is either a reversal warning or a continuation. These are the entry, re-entry or closing position points.
When either the fuchsia or the aqua colors disappear or shrinks meaningfully it could mean a possible leg exhaustion that will have to be confirmed with the subsequent bars.
When the squeeze color appears without the intermediate color (fuchsia+yellow, fuchsia+maroon, aqua+yellow, aqua+green) it could mean this is just a shake off move, a pump/dump move, a buy the dip or a sell the peak move or a gap.
In the example there are three divergences spotted, the first one between march 2009 and september 2010 when the peaks in the indicator made a lower low, meanwhile the price made a higher high, this is a negative divergence and a trend reversal. On the second example, between april 2013 and July 2013 the indicator made a higher high meanwhile the price made a double bottom, this is a positive divergence and a reversal to the upside.
BACKTEST SCRIPT 0.999 ALPHATRADINGVIEW BACKTEST SCRIPT by Lionshare (c) 2015
THS IS A REAL ALTERNATIVE FOR LONG AWAITED TV NATIVE BACKTEST ENGINE.
READY FOR USE JUST RIGHT NOW.
For user provided trading strategy, executes the trades on pricedata history and continues to make it over live datafeed.
Calculates and (plots on premise) the next performance statistics:
profit - i.e. gross profit/loss.
profit_max - maximum value of gross profit/loss.
profit_per_trade - each trade's profit/loss.
profit_per_stop_trade - profit/loss per "stop order" trade.
profit_stop - gross profit/loss caused by stop orders.
profit_stop_p - percentage of "stop orders" profit/loss in gross profit/loss.
security_if_bought_back - size of security portfolio if bought back.
trades_count_conseq_profit - consecutive gain from profitable series.
trades_count_conseq_profit_max - maxmimum gain from consecutive profitable series achieved.
trades_count_conseq_loss - same as for profit, but for loss.
trades_count_conseq_loss_max - same as for profit, but for loss.
trades_count_conseq_won - number of trades, that were won consecutively.
trades_count_conseq_won_max - maximum number of trades, won consecutively.
trades_count_conseq_lost - same as for won trades, but for lost.
trades_count_conseq_lost_max - same as for won trades, but for lost.
drawdown - difference between local equity highs and lows.
profit_factor - profit-t-loss ratio.
profit_factor_r - profit(without biggest winning trade)-to-loss ratio.
recovery_factor - equity-to-drawdown ratio.
expected_value - median gain value of all wins and loss.
zscore - shows how much your seriality of consecutive wins/loss diverges from the one of normal distributed process. valued in sigmas. zscore of +3 or -3 sigmas means nonrandom realitonship of wins series-to-loss series.
confidence_limit - the limit of confidence in zscore result. values under 0.95 are considered inconclusive.
sharpe - sharpe ratio - shows the level of strategy stability. basically it is how the profit/loss is deviated around the expected value.
sortino - the same as sharpe, but is calculated over the negative gains.
k - Kelly criterion value, means the percentage of your portfolio, you can trade the scripted strategy for optimal risk management.
k_margin - Kelly criterion recalculated to be meant as optimal margin value.
DISCLAIMER :
The SCRIPT is in ALPHA stage. So there could be some hidden bugs.
Though the basic functionality seems to work fine.
Initial documentation is not detailed. There could be english grammar mistakes also.
NOW Working hard on optimizing the script. Seems, some heavier strategies (especially those using the multiple SECURITY functions) call TV processing power limitation errors.
Docs are here:
docs.google.com
EPS and Sales Magic Indicator V2EPS and Sales Magic Indicator V2
EPS and Sales Magic Indicator V2
Short Title: EPS V2
Author: Trading_Tomm
Platform: TradingView (Pine Script v6)
License: Free for public use under fair usage guidelines
Overview
The EPS and Sales Magic Indicator V2 is a powerful stock fundamental visualization tool built specifically for TradingView users who wish to incorporate earnings intelligence directly onto their price chart. Designed and developed by Trading_Tomm, this upgraded version of the original 'EPS and Sales Magic Indicator' includes an enriched and more insightful presentation of company performance metrics — now with TTM EPS support, advanced color-coding, label sizing, and refined control options.
This indicator is tailored for retail traders, swing investors, and long-term fundamental analysts who need to view Quarter-over-Quarter (QoQ) earnings and revenue changes directly on the price chart without switching tabs or breaking focus.
What Does It Display?
The EPS and Sales Magic Indicator V2 intelligently detects quarterly financial updates and displays the following data points via labels:
1. EPS (Earnings Per Share) – Current Quarterly Value
This is the most recent Diluted EPS published by the company, fetched using TradingView’s request.financial() function.
Displayed in the format: EPS: ₹20.45
2. EPS QoQ Percentage Change
Shows the percentage change in EPS compared to the previous quarter.
Highlights improvement or decline using arrows (up for improvement, down for decline).
Displayed in the format: EPS: ₹20.45 (up 15.3 percent)
3. Sales (Revenue) – Current Quarterly Value
Fetches and displays Total Revenue of the company in ₹Crores for easier Indian-market readability.
Displayed in the format: Sales: ₹460Cr
4. Sales QoQ Percentage Change
Measures and presents the quarter-over-quarter percentage change in total revenue.
Uses arrows to indicate growth or contraction.
Displayed in the format: Sales: ₹460Cr (down 3.8 percent)
5. EPS TTM (Trailing Twelve Months)
You now get the TTM EPS — the sum of the last four quarterly EPS values.
This value provides a better long-term earnings snapshot compared to a single quarter.
Displayed in the format: TTM EPS: ₹78.12
All of these values are automatically calculated and displayed only on the bars where a new financial report is detected, keeping your chart clean and insightful.
Customization Features
This indicator is built with user control in mind, allowing you to personalize how and what you want to see:
Show EPS in Label: Enable or disable the display of EPS and EPS QoQ values.
Show Sales in Label: Toggle the visibility of revenue and sales change percentage.
Color Options for Label Themes: The label background color is automatically determined based on performance.
Green: Both EPS and Sales increased QoQ.
Red: Both decreased.
Orange: One increased and the other decreased.
Gray: Default color (if values are unavailable or mixed).
Label Text Size: Choose from Tiny, Small (default), or Normal.
Visual Design
Placement: The labels are positioned just below the candlesticks using yloc.belowbar, so they do not obstruct price action or interfere with technical indicators.
Anchor: Aligned precisely with the financial reporting bars to maintain clarity in historical comparisons.
Background Style: Clean, semi-transparent styling with soft text colors for comfortable viewing.
How It Works
The indicator relies on TradingView’s powerful request.financial() function to extract fiscal quarterly financials (FQ). Internally, it uses detection logic to identify fresh data updates by comparing current vs. previous values, arithmetic to compute QoQ percentage changes in EPS and Sales, logic to build formatted labels dynamically based on user selections, and conditional color and sizing logic to enhance interpretability.
Use Cases
For Long-Term Investors: Quickly identify if a company’s profitability and revenue are improving over time.
For Swing Traders: Combine recent earnings trends with price action to evaluate if post-result momentum has real backing.
For Technical and Fundamental Traders: Layer it with moving averages, RSI, or volume to create a hybrid analysis environment.
Limitations and Notes
Financial data is provided by TradingView’s financial API, and occasional missing values may occur for less-covered stocks.
This tool does not repaint but depends on the timing of the official financial updates.
All values are rounded and formatted to prioritize readability.
Works best on Daily or higher timeframes (weekly or monthly also supported).
License and Fair Use
This script is free to use and share under TradingView’s open-use guidelines. You may copy, fork, and build upon this indicator for personal or educational purposes, but commercial usage requires attribution to the author: Trading_Tomm.
Future Enhancements (Planned)
Addition of Net Profit (QoQ and TTM)
Inclusion of Operating Margin, Profit Margin, and Book Value
Option to switch between numeric and graphical display (table mode)
Alerts on extreme earnings deviation or sales slumps
Final Thoughts
The EPS and Sales Magic Indicator V2 represents a clean, visual, and smart way to monitor a company’s core performance from your chart screen. It helps you align fundamental strength with technical strategies and provides instant financial clarity, which is especially vital in today’s fast-moving markets.
Whether you’re preparing for an earnings season or scanning past performance to pick your next investment, this indicator saves time, enhances insights, and sharpens decisions.
Mahnam BTC with breake outThis strategy is designed and coded specifically for trading Bitcoin in the 15-minute timeframe.
Of course, those who are skilled in coding can use it in other timeframes and currencies by changing its codes and personalizing it.
Of course, it is strongly recommended that people who want to use it first perform the necessary backtests or test this strategy on demo sites and then trade on the Tetri platform.
In this strategy, it only checks the entry and exit conditions and connects to the exchange using the API code and trades completely automatically.
This strategy determines the stop loss and take profit points on the exchange at the same time as entering the transaction and sets them.
///////////////////////// Code ////////////////////////////////
//@version=5
// Copyright (c) 2021-present, Alex Orekhov (everget)
//indicator('HalfTrend and TMA', overlay=true , max_lines_count = 500, max_labels_count = 500)
strategy(title='Mahnam BTC with breake out', overlay=true , max_bars_back=5000 , max_labels_count= 500 , max_boxes_count = 500,max_lines_count = 500, initial_capital=1000, currency = currency.USDT, default_qty_type=strategy.cash )
import PineCoders/Time/4
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
newyork = '0000-2400' // input.session(title='Session', defval='0000-2400')
time_newyork = time(timeframe.period, newyork)
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// تعیین تاریخ شروع و پایان (بر حسب timestamp یونیکس)
// تنظیمات Input برای تاریخ شروع و پایان
startDate = input.time(timestamp('01 Jan 2025 00:00 UTC'), "📅 تاریخ شروع معاملات", inline="dateRange")
endDate = input.time(timestamp('31 Dec 2025 23:59 UTC'), "📅 تاریخ پایان معاملات", inline="dateRange")
// بررسی اینکه آیا زمان فعلی در بازه مجاز است یا خیر
isTradeEnabled = (time >= startDate) //and (time <= endDate)
///////////////////////////////////////////////////////////////////////////////////////////
// currentTime = time("15", "GMT+0")
// hourOfDay = hour(currentTime)
// notrade_hours1 = input.(12 , minval = 0 , maxval = 24 , title = "Hours Friday")
// notrade_hours2 = input.int(12 , minval = 0 , maxval = 24 , title = "Hours Monday")
////////////////////////////////////////////////////////////Holidays/////////////////////
// تعریف روزهای هفته
isSaturday = dayofweek == dayofweek.saturday //and hourOfDay > 12
isSunday = dayofweek == dayofweek.sunday
// isMonday = dayofweek == dayofweek.monday and hourOfDay < notrade_hours1
// isFriday = dayofweek == dayofweek.friday and hourOfDay > notrade_hours2
// رنگآمیزی پسزمینه برای شنبه (آبی کمرنگ) و یکشنبه (نارنجی کمرنگ)
bgcolor(isSaturday ? color.new(color.blue, 90) : isSunday ? color.new(color.orange, 90) : na)
//bgcolor(isMonday ? color.new(color.white, 90) : isFriday ? color.new(color.green, 90) : na)
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//تنظیمات پوزیشن
leverage = input.int(defval = 10 , title = "leverage" , minval = 1 , maxval = 20,step = 5 , group="Posistion Settings==========================================")
quantity = input.float(defval = 500 , title = "quantity" , minval = 1, group="Posistion Settings==========================================")
sl_manager = input.float(defval = 0.5 , step = 0.1 , title = "Risk Percent Of Capital", group="Posistion Settings==========================================")
persent_fee = input.float(defval = 0.05 , title = "Persent Fee Eexchange" , minval = 0 , maxval = 1,step = 0.01 , group="Posistion Settings==========================================")
position_type = input.string(defval = "Buy_And_Sell" , title = "Position_type" , options = , group="Posistion Settings==========================================" )
r_r_long = input.float(defval = 2 , step = 0.1 , title = "R - R =>", group="Posistion Settings==========================================")
r_r_short = r_r_long // input.float(defval = 1.8 , step = 0.1 , title = "r_r Short =>")
//////////////////////////////////////////////////////// END ROC /////////////////////////////////////
day_of_week = input.bool(false , title = "Trade in 7 days", group="Posistion Settings==========================================")
show_tp_sl_ent = true // input.bool(defval=true, title= "Show Tp Sl Ent Box", group="Posistion Settings==========================================")
show_qty = true // input.bool(defval = true , title = "Show Qty Label", group="Posistion Settings==========================================")
//////////////////////////////////////////////////////// Information Position ////////////////////////////////////////////////////
var short_is_open = false
var long_is_open = false
//variant for sell position
var sl1 = 0.0
var tp1 = 0.0
var ent1 = 0.0
var equity1 = 0.0
var qty1 = ""
//variant for buy position
var sl3 = 0.0
var qty2 = ""
var tp3 = 0.0
var ent2 = 0.0
var equity2 = 0.0
symbol = str.tostring(syminfo.basecurrency + "-" + syminfo.currency )
////////////////////////////////////////////////////////////////////////////////////////////////////////
var long_condition = false
var short_condition = false
persent_candel = 0.7 // input.float(defval = 0.7 , step = 0.1 , title = "درصد حرکت آخرین کندل", group="CANDEL Settings==========================================")
////////////////////////////////////////////////////////////////////////////////////////////////////////
amplitude = 2 // input.int(title='Amplitude', defval=2)
channelDeviation =2 //input.int(title='Channel Deviation', defval=2)
showChannels =true // input.bool(title='Show Channels', defval=true)
var int trend = 0
var int nextTrend = 0
var float maxLowPrice = nz(low , low)
var float minHighPrice = nz(high , high)
var float up = 0.0
var float down = 0.0
float atrHigh = 0.0
float atrLow = 0.0
float arrowUp = na
float arrowDown = na
len_atr = 130 // input.int(130 , title = "Len Half Trend")
atr2 = ta.atr(len_atr) / 2
dev = channelDeviation * atr2
highPrice = high
lowPrice = low
highma = ta.sma(high, amplitude)
lowma = ta.sma(low, amplitude)
if nextTrend == 1
maxLowPrice := math.max(lowPrice, maxLowPrice)
if highma < maxLowPrice and close < nz(low , low)
trend := 1
nextTrend := 0
minHighPrice := highPrice
minHighPrice
else
minHighPrice := math.min(highPrice, minHighPrice)
if lowma > minHighPrice and close > nz(high , high)
trend := 0
nextTrend := 1
maxLowPrice := lowPrice
maxLowPrice
if trend == 0
if not na(trend ) and trend != 0
up := na(down ) ? down : down
arrowUp := up - atr2
arrowUp
else
up := na(up ) ? maxLowPrice : math.max(maxLowPrice, up )
up
atrHigh := up + dev
atrLow := up - dev
atrLow
else
if not na(trend ) and trend != 1
down := na(up ) ? up : up
arrowDown := down + atr2
arrowDown
else
down := na(down ) ? minHighPrice : math.min(minHighPrice, down )
down
atrHigh := down + dev
atrLow := down - dev
atrLow
//////////////////////////////////////////////////////////////////////////////////////////////////////////
len_rsi = 14 // input.int(14, group = "RSI Setting=================================")
rsi = ta.rsi(close , len_rsi)
//////////////////////////////////////////////////////////////////////////////////
// محاسبات مربوط به تعیین خطوط حمایت و مقاومت و شکست آنها
show_ATR = input.bool(false)
lookback_15 = 4 // input.int(4, title = "====>Look Back 1H=====>", inline = "2", group = "Setting Pivot======================", tooltip = "Drawing support and resistance in time frame 15 min in selected look back")
pl60 = fixnan(ta.pivotlow( low , lookback_15 , lookback_15 ))
ph60 = fixnan(ta.pivothigh( high , lookback_15 , lookback_15 ))
plot(show_ATR ? pl60 : na , color = color.red)
plot(show_ATR ? ph60 : na , color = color.green)
//////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
len_ema_fast_long = 2 // input.int(2)
sorce_tma_long = low // input.source(low)
ema_fast_long = ta.ema(sorce_tma_long , len_ema_fast_long)
len_ema_slow_long = 25 // input.int(25)
ema_slow_long = ta.ema(sorce_tma_long , len_ema_slow_long)
//**********************************
len_ema_fast_short = 2 // input.int(2)
sorce_tma_short = high // input.source(close)
ema_fast_short = ta.ema(sorce_tma_short , len_ema_fast_short)
len_ema_slow_short = 25 // input.int(25)
ema_slow_short = ta.ema(sorce_tma_short , len_ema_slow_short)
///////////////////////////////////////////////////////////////////////////////////////////////////////////
bars = 2 // input.int(9,title="Volume Previous bars to check")
//one_side = input.bool(false, title="Positive values only")
float volume_up = 0
float volume_down = 0
for i = 0 to bars
if (close >open )
volume_up:=volume_up+volume
else
volume_down:=volume_down+volume
total_up_down_vol= volume_up-volume_down
vol_bb = 8 // input.int(8)
vol_aa = 2 // input.int(2)
pivot_high_vol = fixnan(ta.pivothigh(total_up_down_vol , vol_bb , vol_aa ))
pivot_low_vol = fixnan(ta.pivotlow(total_up_down_vol , vol_bb , vol_aa ))
///////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
CLOSE = close
LOW = low
HIGH = high
//////////////////////////////////////////////////////////////////////////////////
//
//reg_trend_on = input(true, 'Activate Reg Trend Line')
length_bull_bear = 4 // input.int(defval= 4, title='🔹 Length Reg Trend line=', minval=1)
//
BullTrend_hist = 0.0
BearTrend_hist = 0.0
BullTrend = (CLOSE - ta.lowest(LOW, length_bull_bear)) / (ta.sma(ta.tr(true), length_bull_bear ))
BearTrend = (ta.highest(HIGH, length_bull_bear) - CLOSE) / (ta.sma(ta.tr(true), length_bull_bear ))
BearTrend2 = -1 * BearTrend
Trend = BullTrend - BearTrend
// plot columun
if BullTrend < 2
BullTrend_hist := BullTrend - 2
BullTrend_hist
if BearTrend2 > -2
BearTrend_hist := BearTrend2 + 2
BearTrend_hist
//alexgrover-Regression Line Formula
x = bar_index
y = Trend
x_ = ta.sma(x, length_bull_bear)
y_ = ta.sma(y, length_bull_bear)
mx = ta.stdev(x, length_bull_bear)
my = ta.stdev(y, length_bull_bear)
c = ta.correlation(x, y, length_bull_bear)
slope = c * (my / mx)
inter = y_ - slope * x_
reg_trend = x * slope + inter
/////////////////////////////////////////////////
long2 = true
short2 = true
close_H = request.security("" , "" , close )
open_H = request.security("" , "" , open )
if close_H > open_H and close_H > open_H
short2 := false
if close_H < open_H and close_H < open_H
long2 := false
nnn = 1.4 // input.float(1.4 , step = 0.1)
long_1 = BullTrend > nnn and ta.sma(reg_trend , 4 ) > ta.sma(reg_trend , 8 )
short_1 = BearTrend2 < -nnn and ta.sma(reg_trend , 4 ) < ta.sma(reg_trend , 8 )
///////////////////////////////////////////////////
lensig_mdi = 8 // input.int(8, title="ADX Smoothing", minval=1)
len_mdi = 2 // input.int(2, minval=1, title="DI Length")
up_mdi = ta.change(high)
down_mdi = -ta.change(low)
plusDM = na(up_mdi) ? na : (up_mdi > down_mdi and up_mdi > 0 ? up_mdi : 0)
minusDM = na(down_mdi) ? na : (down_mdi > up_mdi and down_mdi > 0 ? down_mdi : 0)
trur_mdi = ta.rma(ta.tr, len_mdi)
plus_mdi = fixnan(100 * ta.rma(plusDM, len_mdi) / trur_mdi)
minus_mdi = fixnan(100 * ta.rma(minusDM, len_mdi) / trur_mdi)
sum = plus_mdi + minus_mdi
adx = 100 * ta.rma(math.abs(plus_mdi - minus_mdi) / (sum == 0 ? 1 : sum), lensig_mdi)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// تنظیمات SuperTrend
atrPeriod = 28 // input(28, title="ATR Period Super Trend")
factor = 3 // input(3.0, title="Multiplier")
= ta.supertrend(factor, atrPeriod)
// تعریف تایمفریمهای بالاتر
htf0 = "30" // input.timeframe("30", title="تایمفریم تأیید اول (1H)")
htf1 = "60" // input.timeframe("60", title=" ایمفریم تأیید دوم (1H)")
htf2 = "240" // input.timeframe("240", title="تایمفریم تأیید سوم (4H)")
// محاسبه SuperTrend در تایمفریمهای بالاتر
supertrend1 = request.security(syminfo.tickerid, htf0, supertrend)
direction1 = request.security(syminfo.tickerid, htf0, direction)
supertrend1H = request.security(syminfo.tickerid, htf1, supertrend )
direction1H = request.security(syminfo.tickerid, htf1, direction)
supertrend4H = request.security(syminfo.tickerid, htf2, supertrend )
direction4H = request.security(syminfo.tickerid, htf2, direction)
// شرایط ورود
Condition_supertrend_long = (direction1H > 0 or direction4H > 0 or direction1 > 0) and volume > fixnan(ta.pivotlow(volume , 16 , 2 ))
Condition_supertrend_short = (direction1H < 0 or direction4H < 0 or direction1 < 0) and volume > fixnan(ta.pivotlow(volume , 16 , 2 ))
//////////////////////////////////////////////////////////////////////////////////////////////////////////
open_4h = request.security("" , "240" , open )
close_4h = request.security("" , "240" , close )
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
if day_of_week == false
if isTradeEnabled == true and time == time_newyork and not isSaturday and not isSunday //and not isFriday and not isMonday
long_condition := long_is_open == false and short_is_open == false and total_up_down_vol > pivot_low_vol and rsi > 51 and rsi < 80
and math.abs(close - open) < (persent_candel/100) * close and ema_fast_long > ema_slow_long and high > ph60 and open < ph60 and long_1 == true and long2 == true
and plus_mdi > minus_mdi and Condition_supertrend_long == true and high > close_4h and close > atrHigh
short_condition := long_is_open == false and short_is_open == false and total_up_down_vol > pivot_low_vol and rsi < 49 and rsi > 20
and math.abs(close - open) < (persent_candel/100) * close and ema_fast_short < ema_slow_short and low < pl60 and open > pl60 and short_1 == true and short2 == true
and plus_mdi < minus_mdi and Condition_supertrend_short == true and low < close_4h and close < atrLow
if day_of_week == true
if isTradeEnabled == true and time == time_newyork
long_condition := long_is_open == false and short_is_open == false and total_up_down_vol > pivot_low_vol and rsi > 51 and rsi < 80
and math.abs(close - open) < (persent_candel/100) * close and ema_fast_long > ema_slow_long and high > ph60 and open < ph60 and long_1 == true and long2 == true
and plus_mdi > minus_mdi and Condition_supertrend_long == true and high > close_4h and close > atrHigh
short_condition := long_is_open == false and short_is_open == false and total_up_down_vol > pivot_low_vol and rsi < 49 and rsi > 20
and math.abs(close - open) < (persent_candel/100) * close and ema_fast_short < ema_slow_short and low < pl60 and open > pl60 and short_1 == true and short2 == true
and plus_mdi < minus_mdi and Condition_supertrend_short == true and low < close_4h and close < atrLow
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//تنظیمات استاپ سل پوزیشن شورت و لانگ بر اساس ATR
length_atr = 2 // input.int(title='Length', defval=2, minval=1, group = "StopLoss Setting=================================")
m = 0.9 // input.float(0.9,step = 0.1,title = 'Multiplier', group = "StopLoss Setting=================================")
show_atr = false // input.bool(false, group = "StopLoss Setting=================================")
src1_atr = high //input(high , title = "Stoploss Short")
src2_atr = low //input(low ,title = "Stoploss Long")
collong_atr = color.rgb(0,255,0,0)
colshort_atr = color.rgb(255,0,0,0)
a1 = (ta.sma(ta.tr(true), length_atr) * m) / 2 + (ta.wma(ta.tr(true), length_atr) * m) / 2
stop_loss_short = src1_atr + a1
stop_loss_long = src2_atr - a1
p1_atr1 = plot(show_atr ? stop_loss_long : na, title='ATR Short Stop Loss', color=colshort_atr, style=plot.style_circles)
p2_atr1 = plot(show_atr ? stop_loss_short : na, title='ATR Long Stop Loss', color=collong_atr, style=plot.style_circles)
/////////////////////////////////////////////////////////////////Start Stop Loss///////////////////////////////////////////////
/////////////////////////////////////////////////////////////////END Stop Loss///////////////////////////////////////////////
var total_long_trade = 0
var loss_long = 0
var profit_long = 0
var sood_pos_long = 0.00
var zarar_pos_long = 0.00
var kol_sood_long = 0.00
var total_short_trade = 0
var loss_short = 0
var profit_short = 0
var sood_pos_short = 0.00
var zarar_pos_short = 0.00
var kol_sood_short = 0.00
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ━━━━━━━━━━━━━━━━━━ تنظیمات ورودی ━━━━━━━━━━━━━━━━━━
var int candlesToWait = 12 // input.int(1, "تعداد کندلهای انتظار پس از معامله", minval=1)
// ━━━━━━━━━━━━━━━━━━ شناسایی آخرین معامله ━━━━━━━━━━━━━━━━━━
var int lastTradeCloseBar = na
var bool isCoolDownOver = true
// اگر معاملهای بسته شد، شماره کندل آن را ذخیره کن
if strategy.closedtrades > 0 and (na(lastTradeCloseBar) or strategy.closedtrades != strategy.closedtrades )
lastTradeCloseBar := bar_index
isCoolDownOver := false
// بررسی آیا تعداد کندلهای موردنظر گذشته است؟
if not na(lastTradeCloseBar) and (bar_index - lastTradeCloseBar) >= candlesToWait
isCoolDownOver := true
bgcolor(isCoolDownOver ? na : color.new(color.red, 90), title="Cooldown Status")
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// تنظیمات دستورات لازم برای ارسال به صرافی جهت پوزیشن لانگ
//ADD_quantity = 1.5 // input.float(2 , title = "در صورت واگرایی ماجین رو چند بابر کنم؟")
if position_type == "Buy" or position_type == "Buy_And_Sell"
if long_condition and isCoolDownOver
ent2 := close
sl3 :=stop_loss_long - (stop_loss_long * (0.5 / leverage) / 100 )
tp3 := ent2 + ((ent2 - sl3) * r_r_long)
number_coin = ((quantity * leverage * sl_manager) / ((ent2 - sl3) *100))
equity2 := math.round ((number_coin * close ) , 3)
if equity2 > quantity * leverage
equity2 := quantity * leverage
//////////////////////////////////////////////////////////////////////////////////
if show_qty
label.new(bar_index , low , str.tostring(equity2) + "$" , color = color.rgb(0, 255, 0,0) , size = size.normal , style = label.style_label_up)
strategy.entry(id="buy", direction = strategy.long , qty=(equity2/close) )
if close >= 10 and close < 500
qty2 := str.tostring(math.round(equity2/close , 2))
else
qty2 := str.tostring(math.round(equity2/close , 0))
if close > 500
qty2 := str.tostring(math.round(equity2/close , 3 ))
if symbol == "AAVEUSDT"
qty2 := str.tostring(math.round(equity2/close , 1))
// ================/ برای باز کردن پوزیشن از این مقدار استفاده میکند /======================
message1 = '{"symbol":"'+symbol+'","type":"MARKET", "side":"BUY", "positionSide": "LONG", "quantity":"'+qty2+'","leverage": "'+str.tostring(leverage)+'","marginMode": "Isolated","botmix-action":"open-market-order-v2"}'
// message1 = '{ "side":"Ask","symbol":"'+symbol+'","tradeType":"Market","entrustVolume":"'+qty1+'","action":"Open","marginMode":"Isolated","leverage":"'+str.tostring(leverage)+'", "takerProfitPrice":"'+str.tostring(tp1)+'","stopLossPrice":"'+str.tostring(sl1)+'","botmix-action":"open-market-order" }'
// message1 = '{ "batchOrders": ,"botmix-action":"open-multiple-order" }'
alert(message1 , alert.freq_once_per_bar)
message2 = '{"symbol":"'+symbol+'","type":"LIMIT","side":"SELL", "positionSide": "LONG","delay": 5 ,"quantity":"'+qty2+'","price": "'+str.tostring(tp3)+'", "botmix-action":"open-market-order-v2"}'
alert(message2 , alert.freq_once_per_bar)
message3 = '{"symbol":"'+symbol+'","type":"STOP_MARKET","side":"SELL","positionSide": "LONG","delay": 10 ,"quantity":"'+qty2+'","price": "'+str.tostring(sl3)+'", "stopPrice": "'+str.tostring(sl3)+'","botmix-action":"open-market-order-v2"}'
alert(message3 , alert.freq_once_per_bar)
long_is_open := true
if show_tp_sl_ent
line.new(bar_index, tp3, bar_index + 15, tp3, xloc= xloc.bar_index, color= color.rgb(0, 255, 0,0 ), width = 1)
box.new(bar_index , tp3 , bar_index + 15 , ent2 ,bgcolor = color.rgb(0, 255, 0 , 90) , border_color = color.rgb(0, 255, 0 , 80) )
line.new(bar_index, (tp3 - ((tp3 - ent2) /2)), bar_index + 15, (tp3 - ((tp3 - ent2) /2)), xloc= xloc.bar_index, color= color.rgb(0, 17, 255), width = 2 , style = line.style_dashed)
line.new(bar_index, sl3, bar_index + 15, sl3, xloc= xloc.bar_index, color= color.rgb(255, 0, 0,0), width = 1)
box.new(bar_index , sl3 , bar_index + 15 , ent2 ,bgcolor = color.rgb(255, 0, 0, 90) , border_color = color.rgb(255, 0, 0 , 80) )
line.new(bar_index , ent2 , bar_index + 15 , ent2 , color = color.rgb(255, 255, 0, 0))
/////////////////////////////////////////////////////////
total_long_trade := total_long_trade + 1
if low <= sl3 and long_is_open == true
loss_long := loss_long + 1
zarar_pos_long := zarar_pos_long + (((ent2 - sl3) / ent2) * equity2)
if high >= tp3 and long_is_open == true
profit_long := profit_long + 1
sood_pos_long := sood_pos_long +(((tp3 - ent2) / ent2) * equity2)
kol_sood_long := sood_pos_long - zarar_pos_long
/////////////////////////////////////////////////////////////
if (low <= sl3 or high >= tp3) and long_is_open == true
long_is_open := false
strategy.exit( id = "buy" , from_entry = "buy" , limit = tp3 , stop = sl3 , qty_percent = 100 , comment_profit = "tp" , comment_loss = "sl" )
color_kol_pos_long = kol_sood_long >0 ? color.rgb(0,255,0) : color.rgb(255,0,0)
// //////////////////////LONG___ENNNDD//////////////////////////////////////////////////////////
// تظیمات دستورات لازم برای ارسال به صرافی جهت پوزیشن شورت
if position_type == "Sell" or position_type == "Buy_And_Sell"
if short_condition and isCoolDownOver
ent1 := close
sl1 :=stop_loss_short + (stop_loss_short * (0.5 / leverage) / 100 )
tp1 := ent1 - ((sl1 - ent1 ) * r_r_short)
number_coin = ((quantity * leverage * sl_manager) / ((sl1 - ent1) *100))
equity1 := math.round ((number_coin * close ) , 3)
if equity1 > quantity * leverage
equity1 := quantity * leverage
/////////////////////////////////////////////////////////////////////////////////////////
if show_qty
label.new(bar_index , high , str.tostring(equity1) + "$" , color = color.rgb(255, 0, 0,0) , size = size.normal , style = label.style_label_down)
strategy.entry(id="sell", direction = strategy.short, qty=(equity1/close) )
if close >= 10 and close < 500
qty1 := str.tostring(math.round(equity1/close , 2))
else
qty1 := str.tostring(math.round(equity1/close , 0))
if close > 500
qty1 := str.tostring(math.round(equity1/close , 3))
if symbol == "AAVEUSDT"
qty1 := str.tostring(math.round(equity1/close , 1))
// ================/ برای باز کردن پوزیشن از این مقدار استفاده میکند /======================
message1 = '{"symbol":"'+symbol+'","type":"MARKET", "side":"SELL", "positionSide": "SHORT", "quantity":"'+qty1+'","leverage": "'+str.tostring(leverage)+'","marginMode": "Isolated","botmix-action":"open-market-order-v2"}'
// message1 = '{ "side":"Ask","symbol":"'+symbol+'","tradeType":"Market","entrustVolume":"'+qty1+'","action":"Open","marginMode":"Isolated","leverage":"'+str.tostring(leverage)+'", "takerProfitPrice":"'+str.tostring(tp1)+'","stopLossPrice":"'+str.tostring(sl1)+'","botmix-action":"open-market-order" }'
// message1 = '{ "batchOrders": ,"botmix-action":"open-multiple-order" }'
alert(message1 , alert.freq_once_per_bar)
message2 = '{"symbol":"'+symbol+'","type":"LIMIT","side":"BUY", "positionSide": "SHORT","delay": 5 ,"quantity":"'+qty1+'","price": "'+str.tostring(tp1)+'", "botmix-action":"open-market-order-v2"}'
alert(message2 , alert.freq_once_per_bar)
message3 = '{"symbol":"'+symbol+'","type":"STOP_MARKET","side":"BUY","positionSide": "SHORT","delay": 10 ,"quantity":"'+qty1+'","price": "'+str.tostring(sl1)+'", "stopPrice": "'+str.tostring(sl1)+'","botmix-action":"open-market-order-v2"}'
alert(message3 , alert.freq_once_per_bar)
short_is_open := true
if show_tp_sl_ent
line.new(bar_index, tp1, bar_index + 15, tp1, xloc= xloc.bar_index, color= color.rgb(0, 255, 0,0 ), width = 1)
box.new(bar_index , tp1 , bar_index + 15 , ent1 ,bgcolor = color.rgb(0, 255, 0 , 90) , border_color = color.rgb(0, 255, 0 , 80) )
line.new(bar_index, (tp1+((ent1 - tp1)/2)), bar_index + 15, (tp1+((ent1 - tp1)/2)), xloc= xloc.bar_index, color= color.rgb(4, 0, 255), width = 2 , style= line.style_dashed)
line.new(bar_index, sl1, bar_index + 15, sl1, xloc= xloc.bar_index, color= color.rgb(255, 0, 0,50), width = 1)
box.new(bar_index , sl1 , bar_index + 15 , ent1 ,bgcolor = color.rgb(255, 0, 0, 90) , border_color = color.rgb(255, 0, 0 , 80) )
line.new(bar_index , ent1 , bar_index + 15 , ent1 , color = color.rgb(255, 255, 0,0))
////////////////////////////////////////////////////////////////////////////////////
total_short_trade := total_short_trade + 1
if high >= sl1 and short_is_open == true
loss_short := loss_long + 1
zarar_pos_short := zarar_pos_short + (((sl1 - ent1) / ent1) * equity1)
if low <= tp1 and short_is_open == true
profit_short := profit_short + 1
sood_pos_short := sood_pos_short +(((ent1 - tp1) / ent1) * equity1)
kol_sood_short := sood_pos_short - zarar_pos_short
///////////////////////////////////////////////////////////////////////////////////
if (high >= sl1 or low <= tp1 ) and short_is_open == true
short_is_open := false
strategy.exit( id = "sellext1" , from_entry = "sell" , limit = tp1 , stop = sl1 , qty_percent = 100 , comment_profit = "tp" , comment_loss = "sl" )
color_kol_pos_short = kol_sood_short > 0 ? color.rgb(0,255,0) : color.rgb(255,0,0)
////////////////////////////////////////////////////////////////////////////////////////////
kol_trade = loss_short + loss_long + profit_long + profit_short
/////////////////////SHORT___ENNNDD//////////////////////////////////////////////////////
closed_trades = (loss_short + loss_long + profit_long + profit_short) // strategy.closedtrades
kolfee = (closed_trades * quantity * leverage * persent_fee) / 100
net_profit = math.round((kol_sood_short + kol_sood_long) , 2 ) - kolfee
net_percent = math.round((net_profit / quantity) * 100 , 2)
win_rate = math.round(((profit_long + profit_short) / kol_trade) * 100 , 2) //math.round((strategy.wintrades / strategy.closedtrades) * 100 , 2)
ending = math.round((quantity + net_profit) , 2)
profit_factor = math.round((sood_pos_long + sood_pos_short) / math.abs(zarar_pos_long + zarar_pos_short) , 2)
drow_down = math.round((strategy.max_drawdown / quantity) * 100, 2 )
show_reportTabel = input.bool(true)
if show_reportTabel
table_color = color.rgb(0, 0, 0)
var table result_table = table.new(position.top_right, 30, 40, bgcolor=color.rgb(255,255,255,0), frame_color=color.rgb(0, 0, 0,0), frame_width=1, border_width=2)
table.cell(result_table , column = 0 , row = 0 , text = "TEST BTC with breake out:\n" + str.tostring(kol_trade) , bgcolor = table_color , text_color = color.rgb(255,255,255,0))
table.cell(result_table , column = 1 , row = 0 , text = "starting:\n" + str.tostring(quantity) + "$" , bgcolor = table_color, text_color = color.rgb(255,255,255,0))
table.cell(result_table , column = 2 , row = 0 , text = "Net Profit:\n" + str.tostring(net_profit) + "$:\n" + " fee = " + str.tostring(kolfee) , bgcolor = table_color, text_color = net_profit > 0 ? color.rgb(0,255,0,0) : color.rgb(255,0,0,0))
table.cell(result_table , column = 0 , row = 1 , text = "Win Rate:\n" + str.tostring(win_rate) + "%" , bgcolor = table_color, text_color = color.rgb(255,255,255,0))
table.cell(result_table , column = 1 , row = 1 , text = "Ending:\n" + str.tostring(ending) + "$" , bgcolor = table_color, text_color = color.rgb(255,255,255,0))
table.cell(result_table , column = 2 , row = 1 , text = "Profit Factor:\n" + str.tostring(profit_factor) , bgcolor = table_color, text_color = color.rgb(255,255,255,0))
table.cell(result_table , column = 3 , row = 0 , text = "Net Percent:\n" + str.tostring(net_percent) + "%" , bgcolor = table_color, text_color = net_percent > 0 ? color.rgb(0,255,0,0) : color.rgb(255,0,0,0))
table.cell(result_table , column = 3 , row = 1 , text = "Draw Down:\n" + str.tostring(drow_down) + "%" , bgcolor = table_color, text_color = color.rgb(255,255,255,0))
table.cell(result_table , column = 4 , row = 0 , text = "Stop:\n" + "Short =" + str.tostring(loss_short)+ "\n" +"Long =" + str.tostring(loss_long) , bgcolor = table_color, text_color = color.rgb(255,0,0,0))
table.cell(result_table , column = 4 , row = 1 , text = "TP:\n" + "Short =" + str.tostring(profit_short)+ "\n" +"Long =" + str.tostring(profit_long) , bgcolor = table_color, text_color = color.rgb(0,255,0,0))
table.cell(result_table , column = 5 , row = 0 , text = "Short:\n" + "sood =" + str.tostring(math.round(sood_pos_short,2)) + "\n" + "Zarar =" + str.tostring(math.round(zarar_pos_short,2)) , bgcolor = table_color, text_color = color.rgb(0,255,0,0))
table.cell(result_table , column = 5 , row = 1 , text = "Long:\n" + "sood =" + str.tostring(math.round(sood_pos_long,2)) + "\n" + "Zarar =" + str.tostring(math.round(zarar_pos_long,2)) , bgcolor = table_color, text_color = color.rgb(0,255,0,0))
table.cell(result_table , column = 6 , row = 0 , text = "Kol Sood Short:\n" + "Short =" + str.tostring(math.round(kol_sood_short,2)) , bgcolor = table_color, text_color = color_kol_pos_short)
table.cell(result_table , column = 6 , row = 1 , text = "Kol Sood Long:\n" + "LONG =" + str.tostring(math.round(kol_sood_long,2)) , bgcolor = table_color, text_color = color_kol_pos_long)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////////////////////////////////
// // ********** تنظیمات **********
// show_monthly_Report = input.bool(false, "نمایش گزارش ماهیانه")
// exchange_fee_percent = 0.05 / 100 // input.float(0.05, "کارمزد صرافی (%)", step=0.01) / 100
// indicator_name = 'BTC with breake out' // input.string("تحلیلگر حرفه ای - گزارش ماهیانه", "عنوان اندیکاتور")
// show_total_row = true // input.bool(true, "نمایش سطر جمع کل")
// // ********** ایجاد جدول **********
// var table monthlyReport = table.new(position = position.top_right, columns = 6,rows = 21,bgcolor = color.rgb(33, 33, 33),
// border_width = 2,border_color = color.rgb(80, 80, 80),frame_width = 1,frame_color = color.rgb(50, 50, 50))
// // ********** متغیرهای ماهیانه **********
// var int currentMonth = na
// var int monthTrades = 0
// var int monthWinningTrades = 0
// var float totalFees = 0.0
// var float monthNetProfit = 0.0
// // ********** متغیرهای جمع کل **********
// var float totalAllTrades = 0.0
// var float totalAllFees = 0.0
// var float totalAllNetProfit = 0.0
// var int totalAllWinningTrades = 0
// var int totalAllMonths = 0
// // ********** تشخیص تغییر ماه **********
// isNewMonth = ta.change(month) or ta.change(year)
// // ********** محاسبات معاملات **********
// tradeClosed = strategy.closedtrades > strategy.closedtrades
// if tradeClosed
// lastTradeIndex = strategy.closedtrades - 1
// tradeSize = math.abs(strategy.closedtrades.size(lastTradeIndex) * strategy.closedtrades.exit_price(lastTradeIndex))
// tradeFee = tradeSize * exchange_fee_percent
// totalFees := totalFees + tradeFee
// tradeProfit = strategy.closedtrades.profit(lastTradeIndex)
// monthNetProfit := monthNetProfit + tradeProfit
// monthTrades := monthTrades + 1
// if tradeProfit > 0
// monthWinningTrades := monthWinningTrades + 1
// // ********** مدیریت گزارش ماهیانه **********
// if isNewMonth and show_monthly_Report and not na(currentMonth)
// // محاسبات ماهانه
// grossProfit = monthNetProfit
// netProfit = grossProfit - totalFees
// winRate = monthTrades > 0 ? (monthWinningTrades/monthTrades)*100 : 0
// // به روزرسانی جمع کل
// totalAllTrades := totalAllTrades + monthTrades
// totalAllFees := totalAllFees + totalFees
// totalAllNetProfit := totalAllNetProfit + netProfit
// totalAllWinningTrades := totalAllWinningTrades + monthWinningTrades
// totalAllMonths := totalAllMonths + 1
// // نمایش در جدول
// row = (month % 12 == 0 ? 12 : month % 12) + 2 // +2 برای جا دادن سطرهای عنوان
// monthName = str.tostring(year ) + "-" + str.tostring(month , "00")
// table.cell(monthlyReport, 0, row, monthName, text_color=color.white)
// table.cell(monthlyReport, 1, row, str.tostring(monthTrades), text_color=color.white)
// table.cell(monthlyReport, 2, row, str.tostring(grossProfit, "0.00") + " $")
// table.cell(monthlyReport, 3, row, str.tostring(totalFees, "0.00") + " $")
// table.cell(monthlyReport, 4, row, str.tostring(netProfit, "0.00") + " $")
// table.cell(monthlyReport, 5, row, str.tostring(winRate, "1.0") + "%")
// // رنگ آمیزی سود/زیان
// textColor = netProfit >= 0 ? color.rgb(0, 200, 0) : color.rgb(200, 0, 0)
// for i = 2 to 5
// table.cell_set_text_color(monthlyReport, i, row, textColor)
// // ********** سطر جمع کل **********
// if show_monthly_Report and show_total_row and totalAllMonths > 0
// totalWinRate = totalAllTrades > 0 ? (totalAllWinningTrades/totalAllTrades)*100 : 0
// table.cell(monthlyReport, 0, 15, "جمع کل (" + str.tostring(totalAllMonths) + " ماه)",
// text_color=color.yellow,
// bgcolor=color.rgb(50, 50, 50),
// width=6)
// table.cell(monthlyReport, 1, 15, str.tostring(totalAllTrades),
// text_color=color.yellow,
// bgcolor=color.rgb(50, 50, 50))
// table.cell(monthlyReport, 2, 15, str.tostring(totalAllNetProfit + totalAllFees, "0.00") + " $",
// text_color=color.yellow,
// bgcolor=color.rgb(50, 50, 50))
// table.cell(monthlyReport, 3, 15, str.tostring(totalAllFees, "0.00") + " $",
// text_color=color.yellow,
// bgcolor=color.rgb(50, 50, 50))
// table.cell(monthlyReport, 4, 15, str.tostring(totalAllNetProfit, "0.00") + " $",
// text_color = totalAllNetProfit >= 0 ? color.green : color.red,
// bgcolor=color.rgb(50, 50, 50))
// table.cell(monthlyReport, 5, 15, str.tostring(totalWinRate, "1.0") + "%",
// text_color=color.yellow,
// bgcolor=color.rgb(50, 50, 50))
// // ********** ریست ماهیانه **********
// if isNewMonth
// currentMonth := month
// monthTrades := 0
// monthWinningTrades := 0
// totalFees := 0.0
// monthNetProfit := 0.0
// // ********** عنوانهای جدول **********
// if barstate.isfirst and show_monthly_Report
// // عنوان اصلی (یکپارچه در سطر اول)
// table.cell(
// monthlyReport,
// column = 4, // ستون شروع (0 = اولین ستون)
// row = 0, // ردیف 0 (اولین ردیف)
// text = indicator_name,
// bgcolor = color.rgb(0, 0, 0),
// text_size = size.small,
// text_color = color.rgb(255,255,0),
// width = 12, // گسترش روی تمام 6 ستون
// height = 4 // ارتفاع بیشتر برای وضوح بهتر
// )
// // عنوان ستونها (در ردیف دوم)
// headers = array.from("ماه", "تعداد", "سود ناخالص", "کارمزد", "سود خالص", "نرخ برد")
// for i = 0 to 5
// table.cell(
// monthlyReport,
// column = i,
// row = 1, // ردیف بعد از عنوان اصلی
// text = array.get(headers, i),
// text_color = color.white,
// bgcolor = color.rgb(60, 60, 60),
// width = 1 // عرض معمولی برای هر ستون
// )
Quantum Reversal# 🧠 Quantum Reversal
## **Quantitative Mean Reversion Framework**
This algorithmic trading system employs **statistical mean reversion theory** combined with **adaptive volatility modeling** to capitalize on Bitcoin's inherent price oscillations around its statistical mean. The strategy integrates multiple technical indicators through a **multi-layered signal processing architecture**.
---
## ⚡ **Core Technical Architecture**
### 📊 **Statistical Foundation**
- **Bollinger Band Mean Reversion Model**: Utilizes 20-period moving average with 2.2 standard deviation bands for volatility-adjusted entry signals
- **Adaptive Volatility Threshold**: Dynamic standard deviation multiplier accounts for Bitcoin's heteroscedastic volatility patterns
- **Price Action Confluence**: Entry triggered when price breaches lower volatility band, indicating statistical oversold conditions
### 🔬 **Momentum Analysis Layer**
- **RSI Oscillator Integration**: 14-period Relative Strength Index with modified oversold threshold at 45
- **Signal Smoothing Algorithm**: 5-period simple moving average applied to RSI reduces noise and false signals
- **Momentum Divergence Detection**: Captures mean reversion opportunities when momentum indicators show oversold readings
### ⚙️ **Entry Logic Architecture**
```
Entry Condition = (Price ≤ Lower_BB) OR (Smoothed_RSI < 45)
```
- **Dual-Condition Framework**: Either statistical price deviation OR momentum oversold condition triggers entry
- **Boolean Logic Gate**: OR-based entry system increases signal frequency while maintaining statistical validity
- **Position Sizing**: Fixed 10% equity allocation per trade for consistent risk exposure
### 🎯 **Exit Strategy Optimization**
- **Profit-Lock Mechanism**: Positions only closed when showing positive unrealized P&L
- **Trend Continuation Logic**: Allows winning trades to run until momentum exhaustion
- **Dynamic Exit Timing**: No fixed profit targets - exits based on profitability state rather than arbitrary levels
---
## 📈 **Statistical Properties**
### **Risk Management Framework**
- **Long-Only Exposure**: Eliminates short-squeeze risk inherent in cryptocurrency markets
- **Mean Reversion Bias**: Exploits Bitcoin's tendency to revert to statistical mean after extreme moves
- **Position Management**: Single position limit prevents over-leveraging
### **Signal Processing Characteristics**
- **Noise Reduction**: SMA smoothing on RSI eliminates high-frequency oscillations
- **Volatility Adaptation**: Bollinger Bands automatically adjust to changing market volatility
- **Multi-Timeframe Coherence**: Indicators operate on consistent timeframe for signal alignment
---
## 🔧 **Parameter Configuration**
| Technical Parameter | Value | Statistical Significance |
|-------------------|-------|-------------------------|
| Bollinger Period | 20 | Standard statistical lookback for volatility calculation |
| Std Dev Multiplier | 2.2 | Optimized for Bitcoin's volatility distribution (95.4% confidence interval) |
| RSI Period | 14 | Traditional momentum oscillator period |
| RSI Threshold | 45 | Modified oversold level accounting for Bitcoin's momentum characteristics |
| Smoothing Period | 5 | Noise reduction filter for momentum signals |
---
## 📊 **Algorithmic Advantages**
✅ **Statistical Edge**: Exploits documented mean reversion tendency in Bitcoin markets
✅ **Volatility Adaptation**: Dynamic bands adjust to changing market conditions
✅ **Signal Confluence**: Multiple indicator confirmation reduces false positives
✅ **Momentum Integration**: RSI smoothing improves signal quality and timing
✅ **Risk-Controlled Exposure**: Systematic position sizing and long-only bias
---
## 🔬 **Mathematical Foundation**
The strategy leverages **Bollinger Band theory** (developed by John Bollinger) which assumes that prices tend to revert to the mean after extreme deviations. The RSI component adds **momentum confirmation** to the statistical price deviation signal.
**Statistical Basis:**
- Mean reversion follows the principle that extreme price deviations from the moving average are temporary
- The 2.2 standard deviation multiplier captures approximately 97.2% of price movements under normal distribution
- RSI momentum smoothing reduces noise inherent in oscillator calculations
---
## ⚠️ **Risk Considerations**
This algorithm is designed for traders with understanding of **quantitative finance principles** and **cryptocurrency market dynamics**. The strategy assumes mean-reverting behavior which may not persist during trending market phases. Proper risk management and position sizing are essential.
---
## 🎯 **Implementation Notes**
- **Market Regime Awareness**: Most effective in ranging/consolidating markets
- **Volatility Sensitivity**: Performance may vary during extreme volatility events
- **Backtesting Recommended**: Historical performance analysis advised before live implementation
- **Capital Allocation**: 10% per trade sizing assumes diversified portfolio approach
---
**Engineered for quantitative traders seeking systematic mean reversion exposure in Bitcoin markets through statistically-grounded technical analysis.**
Swing S/R Entry Indicator (5m)Overview: This is a swing trading Indictor works using support & resistance and market trend, it is designed for all type of markets (crypto, forex, stock etc.) and works on all commonly used timeframes (preferably on 1H, 4H Candles).
How it works:
Core logic behind this indicator is to finding the Support and Resistance, we find the Lower High (LH) and Higher Low (HL) to find the from where the price reversed(bounced back) and also we use a custom logic for figuring out the peak price in the last few candles (based on the input "Strength" ). Based on the multiple previous Support and Resistance (HH, HL, LL LH) we calculate a price level, this price level is used a major a factor for entering the trade. Once we have the price level we check if the current price crosses that price level, if it crossed then we consider that as a long/short entry (based on whether it crosses resistance or support line that we calculated). Once we have pre long/short signals we further filter it based on the market trend to prevent too early/late signals, this trend is calculated based on the value from the input field "Factor". Along with this if we don't see a clear trend we do the filtering by checking how many support or resistance level the price has bounced off.
Stop Loss and Take Profit: We have also added printing SL and TP levels on the chart to make the it easier for everyone to find the SL/TP values. Script calculates the SL value by checking the previous support level for LONG trade and previous resistance level for SHORT trades. Take profit are calculated in 1:1 ratio as of now. can you amek a same indicator for 5 mins chart
Adaptive Cycle Oscillator with EMADescription of the Adaptive Cycle Oscillator with EMA Pine Script
This Pine Script, titled "Adaptive Cycle Oscillator with EMA", is a custom technical indicator designed for TradingView to help traders analyze market cycles and identify potential buy or sell opportunities. It combines an Adaptive Cycle Oscillator (ACO) with multiple Exponential Moving Averages (EMAs), displayed as colorful, wavy lines, and includes features like buy/sell signals and divergence detection. Below is a beginner-friendly explanation of how the script works, adhering to TradingView's Script Publishing Rules.
What This Indicator Does
The Adaptive Cycle Oscillator with EMA helps you:
Visualize market cycles using an oscillator that adapts to price movements.
Track trends with seven EMAs of different lengths, plotted as a rainbow of wavy lines.
Identify potential buy or sell signals when the oscillator crosses predefined thresholds.
Spot divergences between the oscillator and price to anticipate reversals.
Use customizable settings to adjust the indicator to your trading style.
Note: This is a technical analysis tool and does not guarantee profits. Always combine it with other analysis methods and practice risk management.
Step-by-Step Explanation for New Users
1. Understanding the Indicator
Adaptive Cycle Oscillator (ACO): The ACO analyzes price data (based on high, low, and close prices, or HLC3) to detect market cycles. It smooths price movements to create an oscillator that swings between overbought and oversold levels.
EMAs: Seven EMAs of different lengths are applied to the ACO and scaled based on the market's dominant cycle. These EMAs are plotted as colorful, wavy lines to show trend direction.
Buy/Sell Signals: The script generates signals when the ACO crosses above or below user-defined thresholds, indicating potential entry or exit points.
Divergence Detection: The script identifies bullish or bearish divergences between the ACO and the fastest EMA, which may signal potential reversals.
Visual Style: The indicator uses a rainbow of seven colors (red, orange, yellow, green, blue, indigo, violet) for the EMAs, with wavy lines for a unique visual effect. Static levels (zero, overbought, oversold) are also wavy for consistency.
2. How to Add the Indicator to Your Chart
Open TradingView and load the chart of any asset (e.g., stock, forex, crypto).
Click on the Indicators button at the top of the chart.
Search for "Adaptive Cycle Oscillator with EMA" (or paste the script into TradingView’s Pine Editor if you have access to it).
Click to add the indicator to your chart. It will appear in a separate panel below the price chart.
3. Customizing the Indicator
The script offers several input options to tailor it to your needs:
Base Cycle Length (Default: 20): Sets the initial period for calculating the dominant cycle. Higher values make the indicator slower; lower values make it more sensitive.
Alpha Smoothing (Default: 0.07): Controls how much the ACO smooths price data. Smaller values produce smoother results.
Show Buy/Sell Signals (Default: True): Toggle to display green triangles (buy) and red triangles (sell) on the chart.
Threshold (Default: 0.0): Defines overbought (above threshold) and oversold (below threshold) levels. Adjust to widen or narrow signal zones.
EMA Base Length (Default: 10): Sets the starting length for the fastest EMA. Other EMAs are incrementally longer (12, 14, 16, etc.).
Divergence Lookback (Default: 14): Determines how far back the script looks to detect divergences.
To adjust these:
Right-click the indicator on your chart and select Settings.
Modify the inputs in the pop-up window.
Click OK to apply changes.
4. Reading the Indicator
Oscillator and EMAs: The ACO and seven EMAs are plotted in a separate panel. The EMAs (colored lines) move in a wavy pattern:
Red (fastest) to Violet (slowest) represent different response speeds.
When the faster EMAs (e.g., red, orange) are above slower ones (e.g., blue, violet), it suggests bullish momentum, and vice versa.
Zero Line: A gray wavy line at zero acts as a neutral level. The ACO above zero indicates bullish conditions; below zero indicates bearish conditions.
Overbought/Oversold Lines: Red (overbought) and green (oversold) wavy lines mark threshold levels. Extreme ACO values near these lines may suggest reversals.
Buy/Sell Signals:
Green Triangle (Bottom): Appears when the ACO crosses above the oversold threshold, suggesting a potential buy.
Red Triangle (Top): Appears when the ACO crosses below the overbought threshold, suggesting a potential sell.
Divergences:
Green Triangle (Bottom): Indicates a bullish divergence (price makes a lower low, but the EMA makes a higher low), hinting at a potential upward reversal.
Red Triangle (Top): Indicates a bearish divergence (price makes a higher high, but the EMA makes a lower high), hinting at a potential downward reversal.
5. Using Alerts
You can set alerts for key events:
Right-click the indicator and select Add Alert.
Choose a condition (e.g., "ACO Buy Signal", "Bullish Divergence").
Configure the alert settings (e.g., notify via email, app, or pop-up).
Click Create to activate the alert.
Available alert conditions:
ACO Buy Signal: When the ACO crosses above the oversold threshold.
ACO Sell Signal: When the ACO crosses below the overbought threshold.
Bullish Divergence: When a potential upward reversal is detected.
Bearish Divergence: When a potential downward reversal is detected.
6. Tips for Using the Indicator
Combine with Other Tools: Use the indicator alongside support/resistance levels, candlestick patterns, or other indicators (e.g., RSI, MACD) for confirmation.
Test on Different Timeframes: The indicator works on any timeframe (e.g., 1-minute, daily). Shorter timeframes may produce more signals but with more noise.
Practice Risk Management: Never rely solely on this indicator. Set stop-losses and position sizes to manage risk.
Backtest First: Use TradingView’s Strategy Tester (if you convert the script to a strategy) to evaluate performance on historical data.
Compliance with TradingView’s Script Publishing Rules
This description adheres to TradingView’s Script Publishing Rules (as outlined in the provided link):
No Performance Claims: The description avoids promising profits or specific results, emphasizing that the indicator is a tool for analysis.
Clear Instructions: It provides step-by-step guidance for adding, customizing, and using the indicator.
Risk Disclaimer: It notes that trading involves risks and the indicator should be used with other analysis methods.
No Misleading Terms: Terms like “buy” and “sell” are used to describe signals, not guaranteed actions.
Transparency: The description explains the indicator’s components (ACO, EMAs, signals, divergences) without exaggerating its capabilities.
No External Links: The description avoids linking to external resources or soliciting users.
Educational Tone: It focuses on educating users about the indicator’s functionality.
Limitations
Not a Standalone System: The indicator is not a complete trading strategy. It provides insights but requires additional analysis.
Lagging Nature: As with most oscillators and EMAs, signals may lag behind price movements, especially in fast markets.
False Signals: Signals and divergences may not always lead to successful trades, particularly in choppy markets.
Market Dependency: Performance varies across assets and market conditions (e.g., trending vs. ranging markets).
MACD-VWAP-BB IndicatorMACD-VWAP-BB Indicator Description
This Pine Script creates a technical analysis indicator called the "MACD-VWAP-BB Indicator" for use on TradingView. It combines three popular indicators—MACD (Moving Average Convergence Divergence), VWAP (Volume Weighted Average Price), and Bollinger Bands—to generate buy and sell signals on a chart. The indicator plots visual signals (triangles) to help traders identify potential entry points based on the combined signals from these indicators.
What This Indicator Does
Calculates MACD: Measures momentum by comparing two moving averages of the price.
Calculates VWAP: Tracks the average price weighted by volume to gauge whether the price is above or below a "fair" value.
Calculates Bollinger Bands: Identifies volatility and potential overbought or oversold conditions based on price deviation from a moving average.
Combines Signals: Merges the signals from MACD, VWAP, and Bollinger Bands to create a single oscillator.
Generates Buy/Sell Signals: Plots green triangles below the price for buy signals and red triangles above for sell signals when all indicators align.
How It Works
Inputs You Can Customize:
MACD Fast Length (Default: 6): The shorter moving average period for MACD.
MACD Slow Length (Default: 13): The longer moving average period for MACD.
MACD Signal Length (Default: 5): The period for the MACD signal line.
Bollinger Bands Length (Default: 10): The period for calculating the Bollinger Bands' moving average.
Bollinger Bands Multiplier (Default: 1.5): Controls the width of the Bollinger Bands.
VWAP Lookback (Default: 7): The period for calculating VWAP.
Signal Line Smoothing Period (Default: 5): Smooths the combined signal for clarity.
Signal Confirmation Delay (Default: 1): The number of bars to confirm a signal, reducing false signals.
Indicator Calculations:
MACD: Generates a +1 signal for bullish crossovers (MACD line above signal line) or -1 for bearish crossunders.
VWAP: Gives a +1 signal if the price is above VWAP (bullish) or -1 if below (bearish).
Bollinger Bands: Signals +1 if the price is above the upper band (overbought) or -1 if below the lower band (oversold).
Combined Signal: Adds the three signals (ranging from -3 to +3) and smooths them to create an oscillator.
Buy/Sell Signals: A buy signal occurs when the combined signal is +3 (all indicators bullish) and the oscillator crosses above its signal line. A sell signal occurs when the combined signal is -3 (all indicators bearish) and the oscillator crosses below its signal line. Signals are confirmed within the specified delay period.
Visual Output:
Buy Signals: Green triangles appear below the price bars when conditions for a buy are met.
Sell Signals: Red triangles appear above the price bars when conditions for a sell are met.
How to Use It
Add to Chart:
Copy the script into TradingView’s Pine Editor.
Click "Add to Chart" to apply it to your selected chart.
Adjust Inputs:
Go to the indicator’s settings to tweak parameters like MACD lengths, Bollinger Bands multiplier, or VWAP lookback to suit your trading style.
Interpret Signals:
Look for green triangles below bars for potential buy opportunities.
Look for red triangles above bars for potential sell opportunities.
Use in conjunction with other analysis tools, as no indicator guarantees profits.
Test First:
Backtest the indicator on historical data or use it in a demo account to understand its behavior before trading with real money.
Important Notes
Educational Purpose: This indicator is designed to assist with technical analysis and is not financial advice. Always conduct your own research before trading.
Risk Warning: Trading involves risks, and past performance does not guarantee future results. Use this indicator as part of a broader trading strategy.
Customization: Adjust the input settings to match your preferred timeframe or market (e.g., stocks, forex, crypto).
Limitations: The indicator may produce false signals in choppy or low-volatility markets. The confirmation delay helps reduce this but doesn’t eliminate it entirely.
Compliance with TradingView Rules
This script is shared under the Mozilla Public License 2.0, as noted in the code.
No proprietary claims are made, and the script is provided for educational purposes.
The description avoids promising specific trading results or profits, focusing on functionality and usage.
R&D v3 FixedPrecision Breakouts Pro is a trendline-based breakout strategy designed for intraday traders using 0DTE SPY options. The strategy dynamically identifies support and resistance using pivot highs/lows, then confirms breakouts with price action. Trades are executed only during optimal hours (9:30 AM–1:00 PM EST) to minimize theta decay in options contracts.
This script includes:
• Dynamic support & resistance trendlines
• Clean breakout entries with confirmation logic
• Real-time chart labels for entries and exits
• Smart take-profit scaling (1.5x, 2.5x, 3.5x R multiples)
• Automatic time-based exit after 120 bars (2 hours)
• On-screen session highlighting for valid trading hours
⸻
Why Open Source?
This strategy is being published open source to invite feedback from other traders, quants, and Pine Script developers. The goal is simple: collaborate to improve profitability and sharpen trade logic. If you see a better way to define entries, exits, or risk parameters — let’s build it together.
⸻
Wavelet-Trend ML Integration [Alpha Extract]Alpha-Extract Volatility Quality Indicator
The Alpha-Extract Volatility Quality (AVQ) Indicator provides traders with deep insights into market volatility by measuring the directional strength of price movements. This sophisticated momentum-based tool helps identify overbought and oversold conditions, offering actionable buy and sell signals based on volatility trends and standard deviation bands.
🔶 CALCULATION
The indicator processes volatility quality data through a series of analytical steps:
Bar Range Calculation: Measures true range (TR) to capture price volatility.
Directional Weighting: Applies directional bias (positive for bullish candles, negative for bearish) to the true range.
VQI Computation: Uses an exponential moving average (EMA) of weighted volatility to derive the Volatility Quality Index (VQI).
Smoothing: Applies an additional EMA to smooth the VQI for clearer signals.
Normalization: Optionally normalizes VQI to a -100/+100 scale based on historical highs and lows.
Standard Deviation Bands: Calculates three upper and lower bands using standard deviation multipliers for volatility thresholds.
Signal Generation: Produces overbought/oversold signals when VQI reaches extreme levels (±200 in normalized mode).
Formula:
Bar Range = True Range (TR)
Weighted Volatility = Bar Range × (Close > Open ? 1 : Close < Open ? -1 : 0)
VQI Raw = EMA(Weighted Volatility, VQI Length)
VQI Smoothed = EMA(VQI Raw, Smoothing Length)
VQI Normalized = ((VQI Smoothed - Lowest VQI) / (Highest VQI - Lowest VQI) - 0.5) × 200
Upper Band N = VQI Smoothed + (StdDev(VQI Smoothed, VQI Length) × Multiplier N)
Lower Band N = VQI Smoothed - (StdDev(VQI Smoothed, VQI Length) × Multiplier N)
🔶 DETAILS
Visual Features:
VQI Plot: Displays VQI as a line or histogram (lime for positive, red for negative).
Standard Deviation Bands: Plots three upper and lower bands (teal for upper, grayscale for lower) to indicate volatility thresholds.
Reference Levels: Horizontal lines at 0 (neutral), +100, and -100 (in normalized mode) for context.
Zone Highlighting: Overbought (⋎ above bars) and oversold (⋏ below bars) signals for extreme VQI levels (±200 in normalized mode).
Candle Coloring: Optional candle overlay colored by VQI direction (lime for positive, red for negative).
Interpretation:
VQI ≥ 200 (Normalized): Overbought condition, strong sell signal.
VQI 100–200: High volatility, potential selling opportunity.
VQI 0–100: Neutral bullish momentum.
VQI 0 to -100: Neutral bearish momentum.
VQI -100 to -200: High volatility, strong bearish momentum.
VQI ≤ -200 (Normalized): Oversold condition, strong buy signal.
🔶 EXAMPLES
Overbought Signal Detection: When VQI exceeds 200 (normalized), the indicator flags potential market tops with a red ⋎ symbol.
Example: During strong uptrends, VQI reaching 200 has historically preceded corrections, allowing traders to secure profits.
Oversold Signal Detection: When VQI falls below -200 (normalized), a lime ⋏ symbol highlights potential buying opportunities.
Example: In bearish markets, VQI dropping below -200 has marked reversal points for profitable long entries.
Volatility Trend Tracking: The VQI plot and bands help traders visualize shifts in market momentum.
Example: A rising VQI crossing above zero with widening bands indicates strengthening bullish momentum, guiding traders to hold or enter long positions.
Dynamic Support/Resistance: Standard deviation bands act as dynamic volatility thresholds during price movements.
Example: Price reversals often occur near the third standard deviation bands, providing reliable entry/exit points during volatile periods.
🔶 SETTINGS
Customization Options:
VQI Length: Adjust the EMA period for VQI calculation (default: 14, range: 1–50).
Smoothing Length: Set the EMA period for smoothing (default: 5, range: 1–50).
Standard Deviation Multipliers: Customize multipliers for bands (defaults: 1.0, 2.0, 3.0).
Normalization: Toggle normalization to -100/+100 scale and adjust lookback period (default: 200, min: 50).
Display Style: Switch between line or histogram plot for VQI.
Candle Overlay: Enable/disable VQI-colored candles (lime for positive, red for negative).
The Alpha-Extract Volatility Quality Indicator empowers traders with a robust tool to navigate market volatility. By combining directional price range analysis with smoothed volatility metrics, it identifies overbought and oversold conditions, offering clear buy and sell signals. The customizable standard deviation bands and optional normalization provide precise context for market conditions, enabling traders to make informed decisions across various market cycles.
Long/Short/Exit/Risk management Strategy # LongShortExit Strategy Documentation
## Overview
The LongShortExit strategy is a versatile trading system for TradingView that provides complete control over entry, exit, and risk management parameters. It features a sophisticated framework for managing long and short positions with customizable profit targets, stop-loss mechanisms, partial profit-taking, and trailing stops. The strategy can be enhanced with continuous position signals for visual feedback on the current trading state.
## Key Features
### General Settings
- **Trading Direction**: Choose to trade long positions only, short positions only, or both.
- **Max Trades Per Day**: Limit the number of trades per day to prevent overtrading.
- **Bars Between Trades**: Enforce a minimum number of bars between consecutive trades.
### Session Management
- **Session Control**: Restrict trading to specific times of the day.
- **Time Zone**: Specify the time zone for session calculations.
- **Expiration**: Optionally set a date when the strategy should stop executing.
### Contract Settings
- **Contract Type**: Select from common futures contracts (MNQ, MES, NQ, ES) or custom values.
- **Point Value**: Define the dollar value per point movement.
- **Tick Size**: Set the minimum price movement for accurate calculations.
### Visual Signals
- **Continuous Position Signals**: Implement 0 to 1 visual signals to track position states.
- **Signal Plotting**: Customize color and appearance of position signals.
- **Clear Visual Feedback**: Instantly see when entry conditions are triggered.
### Risk Management
#### Stop Loss and Take Profit
- **Risk Type**: Choose between percentage-based, ATR-based, or points-based risk management.
- **Percentage Mode**: Set SL/TP as a percentage of entry price.
- **ATR Mode**: Set SL/TP as a multiple of the Average True Range.
- **Points Mode**: Set SL/TP as a fixed number of points from entry.
#### Advanced Exit Features
- **Break-Even**: Automatically move stop-loss to break-even after reaching specified profit threshold.
- **Trailing Stop**: Implement a trailing stop-loss that follows price movement at a defined distance.
- **Partial Profit Taking**: Take partial profits at predetermined price levels:
- Set first partial exit point and percentage of position to close
- Set second partial exit point and percentage of position to close
- **Time-Based Exit**: Automatically exit a position after a specified number of bars.
#### Win/Loss Streak Management
- **Streak Cutoff**: Automatically pause trading after a series of consecutive wins or losses.
- **Daily Reset**: Option to reset streak counters at the start of each day.
### Entry Conditions
- **Source and Value**: Define the exact price source and value that triggers entries.
- **Equals Condition**: Entry signals occur when the source exactly matches the specified value.
### Performance Analytics
- **Real-Time Stats**: Track important performance metrics like win rate, P&L, and largest wins/losses.
- **Visual Feedback**: On-chart markers for entries, exits, and important events.
### External Integration
- **Webhook Support**: Compatible with TradingView's webhook alerts for automated trading.
- **Cross-Platform**: Connect to external trading systems and notification platforms.
- **Custom Order Execution**: Implement advanced order flows through external services.
## How to Use
### Setup Instructions
1. Add the script to your TradingView chart.
2. Configure the general settings based on your trading preferences.
3. Set session trading hours if you only want to trade specific times.
4. Select your contract specifications or customize for your instrument.
5. Configure risk parameters:
- Choose your preferred risk management approach
- Set appropriate stop-loss and take-profit levels
- Enable advanced features like break-even, trailing stops, or partial profit taking as needed
6. Define entry conditions:
- Select the price source (such as close, open, high, or an indicator)
- Set the specific value that should trigger entries
### Entry Condition Examples
- **Example 1**: To enter when price closes exactly at a whole number:
- Long Source: close
- Long Value: 4200 (for instance, to enter when price closes exactly at 4200)
- **Example 2**: To enter when an indicator reaches a specific value:
- Long Source: ta.rsi(close, 14)
- Long Value: 30 (triggers when RSI equals exactly 30)
### Best Practices
1. **Always backtest thoroughly** before using in live trading.
2. **Start with conservative risk settings**:
- Small position sizes
- Reasonable stop-loss distances
- Limited trades per day
3. **Monitor and adjust**:
- Use the performance table to track results
- Adjust parameters based on how the strategy performs
4. **Consider market volatility**:
- Use ATR-based stops during volatile periods
- Use fixed points during stable markets
## Continuous Position Signals Implementation
The LongShortExit strategy can be enhanced with continuous position signals to provide visual feedback about the current position state. These signals can help you track when the strategy is in a long or short position.
### Adding Continuous Position Signals
Add the following code to implement continuous position signals (0 to 1):
```pine
// Continuous position signals (0 to 1)
var float longSignal = 0.0
var float shortSignal = 0.0
// Update position signals based on your indicator's conditions
longSignal := longCondition ? 1.0 : 0.0
shortSignal := shortCondition ? 1.0 : 0.0
// Plot continuous signals
plot(longSignal, title="Long Signal", color=#00FF00, linewidth=2, transp=0, style=plot.style_line)
plot(shortSignal, title="Short Signal", color=#FF0000, linewidth=2, transp=0, style=plot.style_line)
```
### Benefits of Continuous Position Signals
- Provides clear visual feedback of current position state (long/short)
- Signal values stay consistent (0 or 1) until condition changes
- Can be used for additional calculations or alert conditions
- Makes it easier to track when entry conditions are triggered
### Using with Custom Indicators
You can adapt the continuous position signals to work with any custom indicator by replacing the condition with your indicator's logic:
```pine
// Example with moving average crossover
longSignal := fastMA > slowMA ? 1.0 : 0.0
shortSignal := fastMA < slowMA ? 1.0 : 0.0
```
## Webhook Integration
The LongShortExit strategy is fully compatible with TradingView's webhook alerts, allowing you to connect your strategy to external trading platforms, brokers, or custom applications for automated trading execution.
### Setting Up Webhooks
1. Create an alert on your chart with the LongShortExit strategy
2. Enable the "Webhook URL" option in the alert dialog
3. Enter your webhook endpoint URL (from your broker or custom trading system)
4. Customize the alert message with relevant information using TradingView variables
### Webhook Message Format Example
```json
{
"strategy": "LongShortExit",
"action": "{{strategy.order.action}}",
"price": "{{strategy.order.price}}",
"quantity": "{{strategy.position_size}}",
"time": "{{time}}",
"ticker": "{{ticker}}",
"position_size": "{{strategy.position_size}}",
"position_value": "{{strategy.position_value}}",
"order_id": "{{strategy.order.id}}",
"order_comment": "{{strategy.order.comment}}"
}
```
### TradingView Alert Condition Examples
For effective webhook automation, set up these alert conditions:
#### Entry Alert
```
{{strategy.position_size}} != {{strategy.position_size}}
```
#### Exit Alert
```
{{strategy.position_size}} < {{strategy.position_size}} or {{strategy.position_size}} > {{strategy.position_size}}
```
#### Partial Take Profit Alert
```
strategy.order.comment contains "Partial TP"
```
### Benefits of Webhook Integration
- **Automated Trading**: Execute trades automatically through supported brokers
- **Cross-Platform**: Connect to custom trading bots and applications
- **Real-Time Notifications**: Receive trade signals on external platforms
- **Data Collection**: Log trade data for further analysis
- **Custom Order Management**: Implement advanced order types not available in TradingView
### Compatible External Applications
- Trading bots and algorithmic trading software
- Custom order execution systems
- Discord, Telegram, or Slack notification systems
- Trade journaling applications
- Risk management platforms
### Implementation Recommendations
- Test webhook delivery using a free service like webhook.site before connecting to your actual trading system
- Include authentication tokens or API keys in your webhook URL or payload when required by your external service
- Consider implementing confirmation mechanisms to verify trade execution
- Log all webhook activities for troubleshooting and performance tracking
## Integrating with Confluence of Signals
The LongShortExit strategy can be enhanced by using it in conjunction with the "Confluence of Alerts" indicator to create more robust entry conditions based on multiple technical signals.
### What is Confluence of Signals?
The Confluence of Alerts indicator allows you to define up to 8 different technical conditions that must be met simultaneously to generate a trading signal. This approach helps filter out false signals and only enters trades when multiple technical factors align.
### Integration Approach
#### Method 1: Using Confluence as a Signal Source
1. Add the Confluence of Alerts indicator to your chart
2. Configure your desired technical conditions (RSI, moving averages, support/resistance, etc.)
3. In the LongShortExit strategy settings:
- Set Long Source to `plot("Long All")` from the Confluence indicator
- Set Long Value to `1` with "Equals" condition
- Similarly for Short Source using `plot("Short All")`
#### Method 2: Modifying the Strategy Code
For more advanced integration, you can incorporate the condition logic directly:
```pine
// Add to the top of your LongShortExit strategy
//@import TradersPost/Confluence_of_Alerts/1
// Replace simple entry conditions with confluence signals
longCondition = confluence_long_signal and longEntryCondition
shortCondition = confluence_short_signal and shortEntryCondition
```
### Confluence Configuration Examples
#### Trend-Following Configuration
1. **Condition 1**: When SMA(20) crossing up SMA(50)
2. **Condition 2**: When RSI(14) greater than 50
3. **Condition 3**: When close greater than VWAP
4. **Condition 4**: When ADX(14) greater than 25
#### Support/Resistance Configuration
1. **Condition 1**: When price crossing up pivot support
2. **Condition 2**: When Stochastic %K crossing up %D
3. **Condition 3**: When volume greater than average volume
4. **Condition 4**: When price greater than previous day's close
### Benefits of Using Confluence with LongShortExit
- **Reduced False Signals**: Enter trades only when multiple conditions confirm the signal
- **Higher Probability Trades**: Each additional confirming factor increases trade success probability
- **Customizable Filter**: Adapt the conditions to suit different market environments and trading styles
- **Visual Confirmation**: The Confluence indicator provides clear visual signals when all conditions are met
### Implementation Tips
1. Start with 2-3 conditions before adding more complexity
2. Ensure conditions aren't redundant (e.g., don't use multiple similar indicators)
3. Include conditions from different categories:
- Trend indicators (moving averages, ADX)
- Momentum indicators (RSI, MACD)
- Volume indicators
- Support/resistance levels
4. Test different timeframes for the conditions
5. Use the "on Bar Close" option for more reliable signals
## Strategy Customization Tips
### For Scalping
- Set smaller profit targets (1-3 points)
- Use tighter stop-losses
- Enable break-even feature after small profit
- Set higher max trades per day
### For Day Trading
- Use moderate profit targets
- Implement partial profit taking
- Enable trailing stops
- Set reasonable session trading hours
### For Swing Trading
- Use longer-term charts
- Set wider stops (ATR-based often works well)
- Use higher profit targets
- Disable daily streak reset
## Common Troubleshooting
### Low Win Rate
- Consider widening stop-losses
- Verify that entry conditions aren't triggering too frequently
- Check if the equals condition is too restrictive; consider small tolerances
### Missing Obvious Trades
- The equals condition is extremely precise. Price must exactly match the specified value.
- Consider using floating-point precision for more reliable triggers
### Frequent Stop-Outs
- Try ATR-based stops instead of fixed points
- Increase the stop-loss distance
- Enable break-even feature to protect profits
## Important Notes
- The exact equals condition is strict and may result in fewer trade signals compared to other conditions.
- For instruments with decimal prices, exact equality might be rare. Consider the precision of your value.
- Break-even and trailing stop calculations are based on points, not percentage.
- Partial take-profit levels are defined in points distance from entry.
- The continuous position signals (0 to 1) provide valuable visual feedback but don't affect the strategy's trading logic directly.
- When implementing continuous signals, ensure they're aligned with the actual entry conditions used by the strategy.
---
*This strategy is for educational and informational purposes only. Always test thoroughly before using with real funds.*
Long/Short/Exit/Risk management Strategy # LongShortExit Strategy Documentation
## Overview
The LongShortExit strategy is a versatile trading system for TradingView that provides complete control over entry, exit, and risk management parameters. It features a sophisticated framework for managing long and short positions with customizable profit targets, stop-loss mechanisms, partial profit-taking, and trailing stops. The strategy can be enhanced with continuous position signals for visual feedback on the current trading state.
## Key Features
### General Settings
- **Trading Direction**: Choose to trade long positions only, short positions only, or both.
- **Max Trades Per Day**: Limit the number of trades per day to prevent overtrading.
- **Bars Between Trades**: Enforce a minimum number of bars between consecutive trades.
### Session Management
- **Session Control**: Restrict trading to specific times of the day.
- **Time Zone**: Specify the time zone for session calculations.
- **Expiration**: Optionally set a date when the strategy should stop executing.
### Contract Settings
- **Contract Type**: Select from common futures contracts (MNQ, MES, NQ, ES) or custom values.
- **Point Value**: Define the dollar value per point movement.
- **Tick Size**: Set the minimum price movement for accurate calculations.
### Visual Signals
- **Continuous Position Signals**: Implement 0 to 1 visual signals to track position states.
- **Signal Plotting**: Customize color and appearance of position signals.
- **Clear Visual Feedback**: Instantly see when entry conditions are triggered.
### Risk Management
#### Stop Loss and Take Profit
- **Risk Type**: Choose between percentage-based, ATR-based, or points-based risk management.
- **Percentage Mode**: Set SL/TP as a percentage of entry price.
- **ATR Mode**: Set SL/TP as a multiple of the Average True Range.
- **Points Mode**: Set SL/TP as a fixed number of points from entry.
#### Advanced Exit Features
- **Break-Even**: Automatically move stop-loss to break-even after reaching specified profit threshold.
- **Trailing Stop**: Implement a trailing stop-loss that follows price movement at a defined distance.
- **Partial Profit Taking**: Take partial profits at predetermined price levels:
- Set first partial exit point and percentage of position to close
- Set second partial exit point and percentage of position to close
- **Time-Based Exit**: Automatically exit a position after a specified number of bars.
#### Win/Loss Streak Management
- **Streak Cutoff**: Automatically pause trading after a series of consecutive wins or losses.
- **Daily Reset**: Option to reset streak counters at the start of each day.
### Entry Conditions
- **Source and Value**: Define the exact price source and value that triggers entries.
- **Equals Condition**: Entry signals occur when the source exactly matches the specified value.
### Performance Analytics
- **Real-Time Stats**: Track important performance metrics like win rate, P&L, and largest wins/losses.
- **Visual Feedback**: On-chart markers for entries, exits, and important events.
### External Integration
- **Webhook Support**: Compatible with TradingView's webhook alerts for automated trading.
- **Cross-Platform**: Connect to external trading systems and notification platforms.
- **Custom Order Execution**: Implement advanced order flows through external services.
## How to Use
### Setup Instructions
1. Add the script to your TradingView chart.
2. Configure the general settings based on your trading preferences.
3. Set session trading hours if you only want to trade specific times.
4. Select your contract specifications or customize for your instrument.
5. Configure risk parameters:
- Choose your preferred risk management approach
- Set appropriate stop-loss and take-profit levels
- Enable advanced features like break-even, trailing stops, or partial profit taking as needed
6. Define entry conditions:
- Select the price source (such as close, open, high, or an indicator)
- Set the specific value that should trigger entries
### Entry Condition Examples
- **Example 1**: To enter when price closes exactly at a whole number:
- Long Source: close
- Long Value: 4200 (for instance, to enter when price closes exactly at 4200)
- **Example 2**: To enter when an indicator reaches a specific value:
- Long Source: ta.rsi(close, 14)
- Long Value: 30 (triggers when RSI equals exactly 30)
### Best Practices
1. **Always backtest thoroughly** before using in live trading.
2. **Start with conservative risk settings**:
- Small position sizes
- Reasonable stop-loss distances
- Limited trades per day
3. **Monitor and adjust**:
- Use the performance table to track results
- Adjust parameters based on how the strategy performs
4. **Consider market volatility**:
- Use ATR-based stops during volatile periods
- Use fixed points during stable markets
## Continuous Position Signals Implementation
The LongShortExit strategy can be enhanced with continuous position signals to provide visual feedback about the current position state. These signals can help you track when the strategy is in a long or short position.
### Adding Continuous Position Signals
Add the following code to implement continuous position signals (0 to 1):
```pine
// Continuous position signals (0 to 1)
var float longSignal = 0.0
var float shortSignal = 0.0
// Update position signals based on your indicator's conditions
longSignal := longCondition ? 1.0 : 0.0
shortSignal := shortCondition ? 1.0 : 0.0
// Plot continuous signals
plot(longSignal, title="Long Signal", color=#00FF00, linewidth=2, transp=0, style=plot.style_line)
plot(shortSignal, title="Short Signal", color=#FF0000, linewidth=2, transp=0, style=plot.style_line)
```
### Benefits of Continuous Position Signals
- Provides clear visual feedback of current position state (long/short)
- Signal values stay consistent (0 or 1) until condition changes
- Can be used for additional calculations or alert conditions
- Makes it easier to track when entry conditions are triggered
### Using with Custom Indicators
You can adapt the continuous position signals to work with any custom indicator by replacing the condition with your indicator's logic:
```pine
// Example with moving average crossover
longSignal := fastMA > slowMA ? 1.0 : 0.0
shortSignal := fastMA < slowMA ? 1.0 : 0.0
```
## Webhook Integration
The LongShortExit strategy is fully compatible with TradingView's webhook alerts, allowing you to connect your strategy to external trading platforms, brokers, or custom applications for automated trading execution.
### Setting Up Webhooks
1. Create an alert on your chart with the LongShortExit strategy
2. Enable the "Webhook URL" option in the alert dialog
3. Enter your webhook endpoint URL (from your broker or custom trading system)
4. Customize the alert message with relevant information using TradingView variables
### Webhook Message Format Example
```json
{
"strategy": "LongShortExit",
"action": "{{strategy.order.action}}",
"price": "{{strategy.order.price}}",
"quantity": "{{strategy.position_size}}",
"time": "{{time}}",
"ticker": "{{ticker}}",
"position_size": "{{strategy.position_size}}",
"position_value": "{{strategy.position_value}}",
"order_id": "{{strategy.order.id}}",
"order_comment": "{{strategy.order.comment}}"
}
```
### TradingView Alert Condition Examples
For effective webhook automation, set up these alert conditions:
#### Entry Alert
```
{{strategy.position_size}} != {{strategy.position_size}}
```
#### Exit Alert
```
{{strategy.position_size}} < {{strategy.position_size}} or {{strategy.position_size}} > {{strategy.position_size}}
```
#### Partial Take Profit Alert
```
strategy.order.comment contains "Partial TP"
```
### Benefits of Webhook Integration
- **Automated Trading**: Execute trades automatically through supported brokers
- **Cross-Platform**: Connect to custom trading bots and applications
- **Real-Time Notifications**: Receive trade signals on external platforms
- **Data Collection**: Log trade data for further analysis
- **Custom Order Management**: Implement advanced order types not available in TradingView
### Compatible External Applications
- Trading bots and algorithmic trading software
- Custom order execution systems
- Discord, Telegram, or Slack notification systems
- Trade journaling applications
- Risk management platforms
### Implementation Recommendations
- Test webhook delivery using a free service like webhook.site before connecting to your actual trading system
- Include authentication tokens or API keys in your webhook URL or payload when required by your external service
- Consider implementing confirmation mechanisms to verify trade execution
- Log all webhook activities for troubleshooting and performance tracking
## Strategy Customization Tips
### For Scalping
- Set smaller profit targets (1-3 points)
- Use tighter stop-losses
- Enable break-even feature after small profit
- Set higher max trades per day
### For Day Trading
- Use moderate profit targets
- Implement partial profit taking
- Enable trailing stops
- Set reasonable session trading hours
### For Swing Trading
- Use longer-term charts
- Set wider stops (ATR-based often works well)
- Use higher profit targets
- Disable daily streak reset
## Common Troubleshooting
### Low Win Rate
- Consider widening stop-losses
- Verify that entry conditions aren't triggering too frequently
- Check if the equals condition is too restrictive; consider small tolerances
### Missing Obvious Trades
- The equals condition is extremely precise. Price must exactly match the specified value.
- Consider using floating-point precision for more reliable triggers
### Frequent Stop-Outs
- Try ATR-based stops instead of fixed points
- Increase the stop-loss distance
- Enable break-even feature to protect profits
## Important Notes
- The exact equals condition is strict and may result in fewer trade signals compared to other conditions.
- For instruments with decimal prices, exact equality might be rare. Consider the precision of your value.
- Break-even and trailing stop calculations are based on points, not percentage.
- Partial take-profit levels are defined in points distance from entry.
- The continuous position signals (0 to 1) provide valuable visual feedback but don't affect the strategy's trading logic directly.
- When implementing continuous signals, ensure they're aligned with the actual entry conditions used by the strategy.
---
*This strategy is for educational and informational purposes only. Always test thoroughly before using with real funds.*
TradePlanner ProPlan smarter. Trade with precision.
TradePlanner Pro is a professional-grade overlay tool designed to streamline your trading decisions by visually organizing your trade plans directly on the chart. Built for traders who value preparation and clarity, this script enables precise entry planning, risk management, and target visualization—all tailored per symbol.
Core Purpose
TradePlanner Pro helps you map out potential trades using pre-defined symbol-based presets. It dynamically calculates position sizes based on your account size or fixed risk, then visualizes key trade levels (Entry, Take Profits, Stop Loss) with profit/loss metrics in both dollar and percentage terms. It's the perfect companion for traders who prepare their setups in advance and want their plans clearly represented on the chart.
Key Features
🔹 Per-Symbol Presets: Define entries, up to 3 take-profit levels, and stop-losses for each ticker.
🔹 Dynamic Risk Sizing: Choose between percentage-based risk or fixed dollar risk per trade.
🔹 Visual Trade Mapping: Automatically plots Entry, TP1–TP3, and SL lines on your chart.
🔹 Real-Time P&L Labels: Displays profit/loss amounts and percentages, with optional R/R ratios.
🔹 Custom Investment Display: Shows how much capital is allocated per trade.
🔹 Clean, Configurable UI: Adjust label positions, font sizes, opacity, and label visibility to match your style.
Whether you're swing trading or day trading, TradePlanner Pro helps you stay disciplined, organized, and confident in your execution.
How to Use TradePlanner Pro – Step-by-Step Guide
TradePlanner Pro is designed to be easy to set up while giving you full control over how your trades are visualized and calculated. Here’s how to get started:
1. Start with Default Settings
By default, the script assumes:
Account Size: $10,000
Max Money per Trade (%): 1.0%
Max Risk (USD): 0 (disabled; only percentage risk is used)
This means the script will size each trade to risk 1% of your account balance per trade unless you override it with a fixed USD risk amount.
2. Set Up Your Symbol Presets
The "Symbol Presets" input is a flexible text area where you define trade setups for each ticker.
Format (one per line):
SYMBOL:Entry,TP1 ,SL
Example:
AAPL:250,260,270,240
MSFT:100,110,90
TSLA:180,200,170
You can include 1 to 3 take-profit levels.
The script will only activate for the current chart’s symbol, matching what's listed.
3. Customize Risk Parameters
You can use:
Account % Risk – Based on account size and % risk.
Fixed USD Risk – When a dollar amount is entered (>0), it takes priority and calculates share size based on the risk per share.
There's also an option to round share quantities down to whole units, which is useful for stock or crypto trading platforms that only allow whole-number units.
4. Choose What to Display
Toggle on/off these elements as needed:
Show Entry/TP/SL Lines
Show P&L Labels – Profit/loss amounts at each target and SL.
Show Amount Invested – Includes total dollar value in the quantity label.
Show Percentages – Adds % gain/loss to each label.
Show Risk/Reward Ratios – Optionally displayed beside or below TP labels.
You can further adjust:
Font size and label opacity
Label position offset – In percent of price range, so they don’t overlap the actual levels.
5. Read the Visual Outputs
Once the preset matches the current chart symbol:
Lines will appear for Entry, TP1-TP3, and Stop Loss.
Labels will display your:
Trade quantity (and invested amount)
Dollar and % profit at each target
Total loss at stop loss
Optional R/R ratios
Everything updates dynamically and adjusts to your current chart scale and bar availabilit
X-Day Capital Efficiency ScoreThis indicator helps identify the Most Profitable Movers for Your fixed Capital (ie, which assets offer the best average intraday profit potential for a fixed capital).
Unlike traditional volatility indicators (like ATR or % change), this script calculates how much real dollar profit you could have made each day over a custom lookback period — assuming you deployed your full capital into that ticker daily.
How it works:
Calculates the daily intraday range (high − low)
Filters for clean candles (where body > 60% of the candle range)
Assumes you invested the full amount of capital ($100K set as default) on each valid day
Computes an average daily profit score based on price action over the selected period (default set to 20 days)
Plots the score in dollars — higher = more efficient use of capital
Why It’s Useful:
Compare tickers based on real dollar return potential — not just % volatility
Spot low-priced, high-volatility stocks that are better suited for intraday or momentum trading
Inputs:
Capital ($): Amount you're hypothetically deploying (e.g., 100,000)
Look Back Period: Number of past days to average over (e.g., 20)
Volatility Quality [Alpha Extract]The Alpha-Extract Volatility Quality (AVQ) Indicator provides traders with deep insights into market volatility by measuring the directional strength of price movements. This sophisticated momentum-based tool helps identify overbought and oversold conditions, offering actionable buy and sell signals based on volatility trends and standard deviation bands.
🔶 CALCULATION
The indicator processes volatility quality data through a series of analytical steps:
Bar Range Calculation: Measures true range (TR) to capture price volatility.
Directional Weighting: Applies directional bias (positive for bullish candles, negative for bearish) to the true range.
VQI Computation: Uses an exponential moving average (EMA) of weighted volatility to derive the Volatility Quality Index (VQI).
vqiRaw = ta.ema(weightedVol, vqiLen)
Smoothing: Applies an additional EMA to smooth the VQI for clearer signals.
Normalization: Optionally normalizes VQI to a -100/+100 scale based on historical highs and lows.
Standard Deviation Bands: Calculates three upper and lower bands using standard deviation multipliers for volatility thresholds.
vqiStdev = ta.stdev(vqiSmoothed, vqiLen)
upperBand1 = vqiSmoothed + (vqiStdev * stdevMultiplier1)
upperBand2 = vqiSmoothed + (vqiStdev * stdevMultiplier2)
upperBand3 = vqiSmoothed + (vqiStdev * stdevMultiplier3)
lowerBand1 = vqiSmoothed - (vqiStdev * stdevMultiplier1)
lowerBand2 = vqiSmoothed - (vqiStdev * stdevMultiplier2)
lowerBand3 = vqiSmoothed - (vqiStdev * stdevMultiplier3)
Signal Generation: Produces overbought/oversold signals when VQI reaches extreme levels (±200 in normalized mode).
Formula:
Bar Range = True Range (TR)
Weighted Volatility = Bar Range × (Close > Open ? 1 : Close < Open ? -1 : 0)
VQI Raw = EMA(Weighted Volatility, VQI Length)
VQI Smoothed = EMA(VQI Raw, Smoothing Length)
VQI Normalized = ((VQI Smoothed - Lowest VQI) / (Highest VQI - Lowest VQI) - 0.5) × 200
Upper Band N = VQI Smoothed + (StdDev(VQI Smoothed, VQI Length) × Multiplier N)
Lower Band N = VQI Smoothed - (StdDev(VQI Smoothed, VQI Length) × Multiplier N)
🔶 DETAILS
Visual Features:
VQI Plot: Displays VQI as a line or histogram (lime for positive, red for negative).
Standard Deviation Bands: Plots three upper and lower bands (teal for upper, grayscale for lower) to indicate volatility thresholds.
Reference Levels: Horizontal lines at 0 (neutral), +100, and -100 (in normalized mode) for context.
Zone Highlighting: Overbought (⋎ above bars) and oversold (⋏ below bars) signals for extreme VQI levels (±200 in normalized mode).
Candle Coloring: Optional candle overlay colored by VQI direction (lime for positive, red for negative).
Interpretation:
VQI ≥ 200 (Normalized): Overbought condition, strong sell signal.
VQI 100–200: High volatility, potential selling opportunity.
VQI 0–100: Neutral bullish momentum.
VQI 0 to -100: Neutral bearish momentum.
VQI -100 to -200: High volatility, strong bearish momentum.
VQI ≤ -200 (Normalized): Oversold condition, strong buy signal.
🔶 EXAMPLES
Overbought Signal Detection: When VQI exceeds 200 (normalized), the indicator flags potential market tops with a red ⋎ symbol.
Example: During strong uptrends, VQI reaching 200 has historically preceded corrections, allowing traders to secure profits.
Oversold Signal Detection: When VQI falls below -200 (normalized), a lime ⋏ symbol highlights potential buying opportunities.
Example: In bearish markets, VQI dropping below -200 has marked reversal points for profitable long entries.
Volatility Trend Tracking: The VQI plot and bands help traders visualize shifts in market momentum.
Example: A rising VQI crossing above zero with widening bands indicates strengthening bullish momentum, guiding traders to hold or enter long positions.
Dynamic Support/Resistance: Standard deviation bands act as dynamic volatility thresholds during price movements.
Example: Price reversals often occur near the third standard deviation bands, providing reliable entry/exit points during volatile periods.
🔶 SETTINGS
Customization Options:
VQI Length: Adjust the EMA period for VQI calculation (default: 14, range: 1–50).
Smoothing Length: Set the EMA period for smoothing (default: 5, range: 1–50).
Standard Deviation Multipliers: Customize multipliers for bands (defaults: 1.0, 2.0, 3.0).
Normalization: Toggle normalization to -100/+100 scale and adjust lookback period (default: 200, min: 50).
Display Style: Switch between line or histogram plot for VQI.
Candle Overlay: Enable/disable VQI-colored candles (lime for positive, red for negative).
The Alpha-Extract Volatility Quality Indicator empowers traders with a robust tool to navigate market volatility. By combining directional price range analysis with smoothed volatility metrics, it identifies overbought and oversold conditions, offering clear buy and sell signals. The customizable standard deviation bands and optional normalization provide precise context for market conditions, enabling traders to make informed decisions across various market cycles.
Zero Lag MACD + Kijun-sen + EOM StrategyThis strategy offers a robust approach to identifying high-probability trading opportunities in the fast-paced cryptocurrency markets, particularly on lower timeframes (e.g., 5-minute). It leverages the synergistic power of three distinct indicators to confirm entries, ensuring a disciplined approach to risk management.
Key Components:
Zero Lag MACD Enhanced Version 1.2: This core momentum indicator is used to identify precise shifts in trend and momentum, offering reduced lag compared to traditional MACD. Entry signals are filtered based on the histogram's position (below for buys, above for sells) to enhance signal reliability.
Kijun-sen (Ichimoku Cloud): Acting as a dynamic support/resistance and trend filter, the Kijun-sen line confirms the prevailing market direction. Long entries are confirmed when price is above Kijun-sen, and short entries when price is below.
Ease of Movement (EoM): This volume-based oscillator provides crucial confirmation of price movements by measuring the ease with which price changes. Positive EoM confirms buying pressure, while negative confirms selling pressure, adding an essential layer of validation to trade setups.
How it Works:
The strategy generates entry signals only when all three indicators align simultaneously:
For Long Entries: A Zero Lag MACD buy signal (crossover below histogram) must coincide with price trading above the Kijun-sen, and the Ease of Movement indicator being above its zero line.
For Short Entries: A Zero Lag MACD sell signal (crossover above histogram) must coincide with price trading below the Kijun-sen, and the Ease of Movement indicator being below its zero line.
Entries are executed at the open of the candle immediately following the signal confirmation.
Risk Management:
Disciplined risk management is paramount to this strategy:
Dynamic Stop-Loss: An Average True Range (ATR) based stop-loss is implemented, set at 2.5 times the current ATR. This adapts the stop-loss distance to market volatility, ensuring sensible risk sizing.
Fixed Take-Profit: A consistent Risk-to-Reward (R:R) ratio of 1:1.2 is applied for all trades, promoting stable profit realization.
Customization & Optimization:
The strategy is built with fully customizable input parameters for each indicator (MACD lengths, Kijun-sen period, ATR period, ATR multiplier, and Risk-to-Reward ratio). This allows users to fine-tune the strategy for different assets, timeframes, and market conditions, facilitating robust backtesting and optimization.
Disclaimer: Trading involves substantial risk and is not suitable for all investors. Past performance is not indicative of future results. This strategy is provided for educational and informational purposes only. Always use proper risk management and conduct your own due diligence.
Donchian x WMA Crossover (2025 Only, Adjustable TP, Real OHLC)Short Description:
Long-only breakout system that goes long when the Donchian Low crosses up through a Weighted Moving Average, and closes when it crosses back down (with an optional take-profit), restricted to calendar year 2025. All signals use the instrument’s true OHLC data (even on Heikin-Ashi charts), start with 1 000 AUD of capital, and deploy 100 % equity per trade.
Ideal parameters configured for Temple & Webster on ASX 30 minute candles. Adjust parameter to suit however best to download candle interval data and have GPT test the pine script for optimum parameters for your trading symbol.
Detailed Description
1. Strategy Concept
This strategy captures trend-driven breakouts off the bottom of a Donchian channel. By combining the Donchian Low with a WMA filter, it aims to:
Enter when volatility compresses and price breaks above the recent Donchian Low while the longer‐term WMA confirms upward momentum.
Exit when price falls back below that same WMA (i.e. when the Donchian Low crosses back down through WMA), but only if the WMA itself has stopped rising.
Optional Take-Profit: you can specify a profit target in decimal form (e.g. 0.01 = 1 %).
2. Timeframe & Universe
In-sample period: only bars stamped between Jan 1 2025 00:00 UTC and Dec 31 2025 23:59 UTC are considered.
Any resolution (e.g. 30 m, 1 h, D, etc.) is supported—just set your preferred timeframe in the TradingView UI.
3. True-Price Execution
All indicator calculations (Donchian Low, WMA, crossover checks, take-profit) are sourced from the chart’s underlying OHLC via request.security(). This guarantees that:
You can view Heikin-Ashi or other styled candles, but your strategy will execute on the real OHLC bars.
Chart styling never suppresses or distorts your backtest results.
4. Position Sizing & Equity
Initial capital: 1 000 AUD
Size per trade: 100 % of available equity
No pyramiding: one open position at a time
5. Inputs (all exposed in the “Inputs” tab):
Input Default Description
Donchian Length 7 Number of bars to calculate the Donchian channel low
WMA Length 62 Period of the Weighted Moving Average filter
Take Profit (decimal) 0.01 Exit when price ≥ entry × (1 + take_profit_perc)
6. How It Works
Donchian Low: ta.lowest(low, DonchianLength) over the specified look-back.
WMA: ta.wma(close, WMALength) applied to true closes.
Entry: ta.crossover(DonchianLow, WMA) AND barTime ∈ 2025.
Exit:
Cross-down exit: ta.crossunder(DonchianLow, WMA) and WMA is not rising (i.e. momentum has stalled).
Take-profit exit: price ≥ entry × (1 + take_profit_perc).
Calendar exit: barTime falls outside 2025.
7. Usage Notes
After adding to your chart, open the Strategy Tester tab to review performance metrics, list of trades, equity curve, etc.
You can toggle your chart to Heikin-Ashi for visual clarity without affecting execution, thanks to the real-OHLC calls.
Kaufman Trend Strategy# ✅ Kaufman Trend Strategy – Full Description (Script Publishing Version)
**Kaufman Trend Strategy** is a dynamic trend-following strategy based on Kaufman Filter theory.
It detects real-time trend momentum, reduces noise, and aims to enhance entry accuracy while optimizing risk.
⚠️ _For educational and research purposes only. Past performance does not guarantee future results._
---
## 🎯 Strategy Objective
- Smooth price noise using Kaufman Filter smoothing
- Detect the strength and direction of trends with a normalized oscillator
- Manage profits using multi-stage take-profits and adaptive ATR stop-loss logic
---
## ✨ Key Features
- **Kaufman Filter Trend Detection**
Extracts directional signal using a state space model.
- **Multi-Stage Profit-Taking**
Automatically takes partial profits based on color changes and zero-cross events.
- **ATR-Based Volatility Stops**
Stops adjust based on swing highs/lows and current market volatility.
---
## 📊 Entry & Exit Logic
**Long Entry**
- `trend_strength ≥ 60`
- Green trend signal
- Price above the Kaufman average
**Short Entry**
- `trend_strength ≤ -60`
- Red trend signal
- Price below the Kaufman average
**Exit (Long/Short)**
- Blue trend color → TP1 (50%)
- Oscillator crosses 0 → TP2 (25%)
- Trend weakens → Final exit (25%)
- ATR + swing-based stop loss
---
## 💰 Risk Management
- Initial capital: `$3,000`
- Order size: `$100` per trade (realistic, low-risk sizing)
- Commission: `0.002%`
- Slippage: `2 ticks`
- Pyramiding: `1` max position
- Estimated risk/trade: `~0.1–0.5%` of equity
> ⚠️ _No trade risks more than 5% of equity. This strategy follows TradingView script publishing rules._
---
## ⚙️ Default Parameters
- **1st Take Profit**: 50%
- **2nd Take Profit**: 25%
- **Final Exit**: 25%
- **ATR Period**: 14
- **Swing Lookback**: 10
- **Entry Threshold**: ±60
- **Exit Threshold**: ±40
---
## 📅 Backtest Summary
- **Symbol**: USD/JPY
- **Timeframe**: 1H
- **Date Range**: Jan 3, 2022 – Jun 4, 2025
- **Trades**: 924
- **Win Rate**: 41.67%
- **Profit Factor**: 1.108
- **Net Profit**: +$1,659.29 (+54.56%)
- **Max Drawdown**: -$1,419.73 (-31.87%)
---
## ✅ Summary
This strategy uses Kaufman filtering to detect market direction with reduced lag and increased smoothness.
It’s built with visual clarity and strong trade management, making it practical for both beginners and advanced users.
---
## 📌 Disclaimer
This script is for educational and informational purposes only and should not be considered financial advice.
Use with proper risk controls and always test in a demo environment before live trading.
Grid TLong V1The “Grid TLong V1” strategy is based on the classic Grid strategy, but in the mode of buying and selling in favor of the trend and only on Long. This allows to take advantage of large uptrend movements to maximize profits in bull markets. For this reason, excessively sideways or bearish markets may not be very conducive to this strategy.
Like our Grid strategies in favor of the trend, you can enter and exit with the balance with controlled risk, as the distance between each grid functions as a natural and adaptable stop loss and take profit. What differentiates it from bidirectional strategies is that Short uses a minimum amount of follow-through, so that the percentage distance between the grids is maintained.
In this version of the script the entries and exits can be chosen at market or limit , and are based on the profit or loss of the current position, not on the percentage change in price.
The user may also notice that the strategy setup is risk-controlled, because it risks 5% on each trade, has a fairly standard commission and modest initial capital, all in order to protect the strategy user from unrealistic results.
As with all strategies, it is strongly recommended to optimize the parameters for the strategy to be effective for each asset and for each time frame.
Crypto Long RSI Entry with AveragingIndicator Name:
04 - Crypto Long RSI Entry with Averaging + Info Table + Lines (03 style lines)
Description:
This indicator is designed for crypto trading on the long side only, using RSI-based entry signals combined with a multi-step averaging strategy and a visual information panel. It aims to capture price rebounds from oversold RSI levels and manage position entries with two staged averaging points, optimizing the average entry price and take-profit targets.
Key Features:
RSI-Based Entry: Enters a long position when the RSI crosses above a defined oversold level (default 25), with an optional faster entry if RSI crosses above 20 after being below it.
Two-Stage Averaging: Allows up to two averaging entries at user-defined price drop percentages (default 5% and 14%), increasing position size to improve average entry price.
Dynamic Take Profit: Adjusts take profit targets after each averaging stage, with customizable percentage levels.
Visual Signals: Marks entries, averaging points, and exits on the chart using colored labels and lines for easy tracking.
Info Table: Displays current trade status, averaging stages, total profit, number of wins, and maximum drawdown percentage in a table on the chart.
Graphical Lines: Shows horizontal lines for entry price, take profit, and averaging prices to visually track trade management.