True Price XRPArbitrage is the simultaneous purchase and sale of an asset to profit from a difference in the price. It is a trade that profits by exploiting the price differences of identical or similar financial instruments on different markets or in different forms.
In cryptocurrencies, arbitrage is difficult - if not impossible to profit from due to the large transaction costs of buying and sell on the different exchanges.
Some exchanges have fees in excess of 3%. This means that the difference in price between exchanges would have to be greater than the transaction cost in order to profit.
This also does not take into account the risk of price movement in the time it would take to transfer funds between exchanges, making the ability to profit from arbitrage impossible for the retail investor.
While "arbitrage" may be intuitively associated with "sabotage" to the uninformed, the occurence is not a result of greedy price manipulation. The difference in price between exchanges can be simply justified by the separation of market depth creating an indipendantly operating order book.
Essentially, this is an individually performing market with a unique price spread.
In order to determine the most visually accurate price, I have averaged the asking price of these six exchanges:
1. KRAKEN
2. BITSTAMP
3. BITFINEX
4. BITTREX
5. POLONIEX
6. BITSO
This plotted line can be overlayed on top of any XRP/USD price from any given exchange in order to view the variance from the average in real-time, or you can hide the underlying chart to view only the average of the six exchanges as demonstrated in the chart above.
Find this in the public indicator library!
Like and follow for more great scripts.
在腳本中搜尋"profit"
MACDouble + RSI (rec. 15min-2hr intrv) Uses two sets of MACD plus an RSI to either long or short. All three indicators trigger buy/sell as one (ie it's not 'IF MACD1 OR MACD2 OR RSI > 1 = buy", its more like "IF 1 AND 2 AND RSI=buy", all 3 match required for trigger)
The MACD inputs should be tweaked depending on timeframe and what you are trading. If you are doing 1, 3, 5 min or real frequent trading then 21/44/20 and 32/66/29 or other high value MACDs should be considered. If you are doing longer intervals like 2, 3, 4hr then consider 9/19/9 and 21/44/20 for MACDs (experiment! I picked these example #s randomly).
Ideal usage for the MACD sets is to have MACD2 inputs at around 1.5x, 2x, or 3x MACD1's inputs.
Other settings to consider: try having fastlength1=macdlength1 and then (fastlength2 = macdlength2 - 2). Like 10/26/10 and 23/48/20. This seems to increase net profit since it is more likely to trigger before major price moves, but may decrease profitable trade %. Conversely, consider FL1=MCDL1 and FL2 = MCDL2 + (FL2 * 0.5). Example: 10/26/10 and 22/48/30 this can increase profitable trade %, though may cost some net profit.
Feel free to message me with suggestions or questions.
MACD, backtest 2015+ only, cut in half and doubledThis is only a slight modification to the existing "MACD Strategy" strategy plugin!
found the default MACD strategy to be lacking, although impressive for its simplicity. I added "year>2014" to the IF buy/sell conditions so it will only backtest from 2015 and beyond ** .
I also had a problem with the standard MACD trading late, per se. To that end I modified the inputs for fast/slow/signal to double. Example: my defaults are 10, 21, 10 so I put 20, 42, 20 in. This has the effect of making a 30min interval the same as 1 hour at 10,21,10. So if you want to backtest at 4hr, you would set your time interval to 2hr on the main chart. This is a handy way to make shorter time periods more useful even regardless of strategy/testing, since you can view 15min with alot less noise but a better response.
Used on BTCCNY OKcoin, with the chart set at 45 min (so really 90min in the strategy) this gave me a percent profitable of 42% and a profit factor of 1.998 on 189 trades.
Personally, I like to set the length/signals to 30,63,30. Meaning you need to triple the time, it allows for much better use of shorter time periods and the backtests are remarkably profitable. (i.e. 15min chart view = 45min on script, 30min= 1.5hr on script)
** If you want more specific time periods you need to try plugging in different bar values: replace "year" with "n" and "2014" with "5500". The bars are based on unix time I believe so you will need to play around with the number for n, with n being the numbers of bars.
Outsidebar vs Insidebar, Illusion Strategy (by ChartArt)WARNING: This strategy does not work! Please don't trade with this strategy
I'm sharing this strategy for the following three educational reasons:
1. You can easily find 100% strategies, but if they only seem to work 100% on one asset, they actually don't work at all. Therefore never backtest your strategy only on one asset, especially forward testing is useless, because it tends to repeat the old patterns. Your strategy has to work on as many different assets as possible.
2. The pyramiding of orders can have an impact on the strategy. In this case if you manually change the strategy settings by increasing it from 1 to 100 pyramiding orders changes the percent profitable on "UKOIL" monthly from 100% to 90% profitable. On other assets you can see very different results. Allowing much more pyramiding orders in this case results in opening orders where the background color highlights appear.
3. The Tradingview backtest beta version currently does not close the last open trade during the backtest. In this case going long on "UKOIL" near the top in 2011 as this strategy did would result in a big loss in 2015. But since the trade is still open and not canceled out by a new short order it still appears as if this strategy works 100% profitable. Which it doesn't.
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.
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
CLMM Vault策略回测 (专业版) v5Explanation of the CLMM (Concentrated Liquidity - Market Maker) Strategy Backtesting Model Developed for the Sui Chain Vaults Protocol
Why Are We Doing This?
Conducting strategy backtesting is a crucial step for us to make data-driven decisions, validate the feasibility of strategies, and manage potential risks before committing real funds and significant development resources. A strategy that appears to have a high APY may perform entirely differently once real-world frictional costs (such as rebalancing fees and slippage) are deducted. The goal of this backtesting model is to quickly and cost-effectively identify which strategy parameter combinations have the potential to be profitable and which ones pose risks before formal development, thereby avoiding significant losses and providing data support for the project's direction.
Core Features of the Backtesting Model
We have built a "pro version" (v5) strategy simulator using TradingView's Pine Script. It can quickly simulate the core performance of our auto-compounding and rebalancing Vaults on historical price data, with the following main features:
Auto-Compounding: Continuously adds the generated fee income to the principal based on the set profit range (e.g., 0.01%).
Auto-Rebalancing: Simulates automatic rebalancing actions when the price exceeds the preset profit range and deducts the corresponding costs.
Smart Filtering Mechanism: To make the simulation closer to our ideal "smart" decision-making, it integrates three freely combinable filtering mechanisms:
Buffer Zone: Tolerates minor and temporary breaches of the profit range to avoid unnecessary rebalancing.
Breakout Confirmation: Requires the price to be in the trigger zone for N consecutive candles to confirm a breakout, filtering out market noise from "false breakouts."
Time Cooldown: Enforces a minimum time interval between two rebalances to prevent value-destroying high-frequency trading in extreme market conditions.
Important: Simplifications and Assumptions of the Model
To quickly prototype and iterate on the TradingView platform, we have made some key simplifications to the model.
A fully accurate backtest would require a deep simulation of on-chain liquidity pools (Pool Pair), calculating the price impact (Slippage) and impermanent loss (IL) caused by each rebalance on the pool. Since TradingView cannot access real-time on-chain liquidity data, we have made the following simplifications:
Simplified Rebalancing Costs: Instead of simulating real transaction slippage, we use a unified input parameter of single rebalance cost (%) to "bundle" and approximate the total of Gas fees, slippage, and realized impermanent loss.
Simplified Fee Income: Instead of calculating fees based on real-time trading volume, we directly input an average fee annualized return (%) as the core income assumption for our strategy.
How to Use and Test
Team members can load this script and test different strategies by adjusting the input parameters on the panel. The most critical parameters include: position profit range, average fee annualized return, single rebalance cost, and the switches and corresponding values of the above three smart filters.
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).
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
## 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.