Buy The Dip - Does It Work?Buying the dip has become a meme in crypto, but does it actually work?
Using this script you can find out.
The dip is defined here as the average true range multiplied by a number of your choosing (dipness input) and subtracted from the low.
When price crosses under the dip level, a long is initiated. The long is then closed using a timestop (default value 20 bars), no fancy exits here.
A general rule for buying the dip should be to be more passive in a bull market and aggressive in a bear market.
Same goes for all counter trend trading.
Heres a few other examples of dip buying statistics using the H4 timeframe:
50% profitable, 1.692 Profit Factor
BINANCE:PIVXBTC
56.52% profitable, 1.254 Profit Factor
BINANCE:KMDBTC
27.27% Profitable, 0.257 Profit Factor... yikes!
BINANCE:BTSBTC
73.33% Profitable, 13.627 Profit Factor... o.O
BINANCE:MANABTC
Cerca negli script per "profit"
-- Ultimate Crypto Trading Strategy -- Backtesting version** This is the backtesting (strategy) version of the ~ Ultimate Crypto Trading Strategy ~ script in TradingView. **
~ Ultimate Crypto Trading Strategy ~
֎ Trading system script on @tradingview that brings the easiest approach to trading with a high profitability rate
֎ Optimized for crypto markets, to catch trend movements as soon as possible and maximize profitability
֎ Sell & Buy alerts, Safeguard mode, Take Profits alerts, auto resistance-support and always adding new features!
֎ Customizable settings.
֎ Users Discord community for learning, sharing and direct support
֎ Ultimate Crypto Trading Strategy Tutorial Video: www.youtube.com www.youtube.com
֎ Safeguard feature (match multiple timeframes signals) explained: youtu.be youtu.be
If you’d like to test the trading script in TradingView, I can give you access to a 10 days trial.
Please send me a message in tradingview and I’ll activate it right away.
Thank you!
Megalodon Pro Automated Trader BackTester
Why Megalodon?
We believe that enlightening others is an incredible way to make this world a better place. That's why we created the tools you need to stop worrying about your investments and focus on what really matters in your life.
What is Megalodon?
Megalodon uses Artificial Intelligence that combines 574 back-tested indicators and 2674 back-tested setups, simultaneously.
Megalodon works with any kind of asset , market state and time frame .
What is the win rate?
Megalodon is extremely accurate and offers insane profits as long as the fundamental analysis is done right .
Backtesting results can be found on our social media or down below .
How to use Megalodon Pro Automated Trader?
Simply, orange rectangles are buy signals and purple rectangles are sell signals .
Green clouds show buy signals and red clouds show sell signals.
Yellow line shows the difference between buy and sell counts.
How to set alarms on Megalodon Pro Automated Trader?
Click on Alert, select Megalodon Pro Automated Trader and click on Buy-Signal or Sell-Signal. More details can be found on our social media.
You may also watch our Megalodon Investing Tutorials on Youtube for more information.
How to purchase?
Megalodon is totally FREE .
You may upgrade to Megalodon Pro for the most important features , including automizing your trading on any asset profitably, setting up alarms to get notified , joining to our VIP telegram channel to get daily updates and our VIP telegram group to interact with the community. Simply go to our website on our TradingView page for learning more and joining us for free.
Some of the backtesting results are:
BTC/USD for longer time frame trading in the bear market for the last year.
APPLE for longer time frame trading in the bull market for the last 10 years.
EURO/USD for day trading in the neutral market for the last month.
BTC/USD for day trading in the bull market for the last 15 days.
APPLE for day trading in the neutral market for the last 2 days and 6 hours.
Stochastic & MACD Strategy Ver 1.0This strategy is inspired by ChartArt and jasonluk28.
The following input changes from the initial ChartArt version to achieve higher stability and profit:
Fast MA Len:11
Slow MA len: 24
Stoch Len: 20
No difference is found in minor changes (+-10) lv. of overbought/oversold
It works above 40% winning rate in Heng Heng Index, Shanghai Composite, Dow Jones Industrial Averge, S&P 500 NASDAQ, VT (World Total Market) and in 15 mins chart
Profit: above ~10 to 30% in less than 1year backtest for most major indice of China and US and ~62% in Heng Seng Index (Hong Kong) & 40.5% in SZSE Composite (Shen Zhen)
P.S. Profit: 700 (Tencent) +150.5%, 939 (CCB) +66.5%, 1299 (AIA) +45%, 2628 (CLIC) +41%, 1 (CK Hutchison) +31%
NFLX +82.5%, BABA +55.5%, AMZN +44%, GOOG +38%, MCD +24.5%
However, Loss in FB -19% , AMD -38.5%
Not suitable for stocks with great influences in News or Events ???
TEMA Strategy 1 (Updated)This is just a test strategy using TEMA ( Triple Exponential Moving Average ).
Test Detail
Symbol: BTCUSD
Interval: 1H
Initial Capital: $1000
Investment: 100% Equity
Results (on BTCUSD -2.31% - Bitfinex)
I had to chunk the months because of the order limit (1000)
(all months start at 1st, 00:00 AND finish at last date, 23:59 )
Timeframe: 2017 August - 2017 Nov
Profit: 21.9%
Max Drawdown: 83.94%
Timeframe: 2017 Dec - 2018 Feb
Profit: 446.32%
Max Drawdown: 46.54%
Timeframe: 2018 Mar - 2018 Jul
Profit: 288.87%
Max Drawdown: 51.49%
To fix:
Too many orders, potentially reduce order counts by increasing max loss (100~200 orders/month) \u2028
High Max Drawdown, need to fix that
Looks like orders are created and terminated very quickly, need to look into that
Still figuring things out
PPSignal MTFSystem Algorithm Ppsignal Versin MTF. based on historical price probabilities . We recommend use financial stock, bond, crypts, indices, futures and Forex market ( GBPUSD -0.09% , EURUSD -0.02% , USDJPY 0.28% , USDCAD 0.09% , AUDUSD -0.02% , USOIL -0.05% , XAUUSD -0.06% , SOYUSD -1.22% , DXY 0.07% , SPY 0.12% , SP1! 0.40% , bitcoin -0.02% ) with defined trends above 50 or 100 and 200 simple moving averages idem if you want trade downtrend financial assets.
Use projections and retracements Fibonacci, MACD and RSI or Stoch oscillator and figures charters Head and shoulder, triangles and double bottom , double top , etc.
This system will notify you of the probability of success. The profit will be defined for yourself and according to your investor profile.
There are stocks and other assets with high returns but the system does not know exactly. Check in the Strategy tester section and then net profit.
We have other tools that support to PPsignal system, we will publish them shortly.
Define system parameters
As it is a system that is based on past data we recommend using the most historical data weekly (W) but you an use day historical data or 3 o 2 hs.
Candle color: you can choose if you want a trend color for candles or not, in the chart propieties menu detach the border option.
PPsignal it's a very simple system with which you will have a great support when it is a good time for enter in the marker and out.
we await your comments.
With this new version you can change the period and time and find a better percent profitable.
Eng. Oscar Alejandro Peruchena
Quants Mathematical and Market Analyst
RSI Buy/sell signal with TP_SL_TL_15min by rajistaRSI Buy/sell signal with TakeProfit_Stop loss_Trailing_SL script -can be used on any altcoin/btc pair on the 15min chart .
This script can be used for backtesting pupose and also to give buy/sell signals based on the settings provided by you.
Benefits of the script:
1> Fully customizable script according to your trade setups.
2> The script incorporates Take-profit, Stop-loss & Trailing SL.
3> Cuts your losses significantly, in comparision to a script without TP, SL & TL strategies.
4> Based on RSI Overbought/Oversold levels, which can also be customizable.
5> Doesn't take too many trades in a day, thereby decreasing commission paid to exchanges & hence enhances the overall profit.
Here's how, you can fully customize the script, according to your strategy, once you have been provided access:
( To gain access to the script just hit the like/comment in the #tradingview published article & i'll grant access based on your tradingview userid )
You can add this script to your charts in 15min timeframe, like adding any other simple indicator.
Once you have added the script, just hit the settings button to fully customize the script according to your strategy and plan, that you have, for your trade setup.
Take profit, Stop loss, Trailing Stop loss values can be entered in satoshis from the setting panel.
RSI Overbought & Oversold values can also be entered according to your trading setup.
Like in below example , i have put the following values as default
Test date is set as 1 May 2018
Take profit=1000, stop loss=5, Trailing SL=40
RSI Overbought=70, Oversold=20
" Above mentioned values are default values and may not be profitable in every condition, you have to backtest the strategy by changing these values and then see the results of given values under the Strategy tester tab- located at bottom of your #tradingview chart. "
Lets see how the scipt is able to make these awesome gains:
Suppose your script enters a trade(buys Verge) when #Verge is at 800sats
Then the bot will close the trade(sell Verge) when either of these things happen:
a> Verge surges to 1800 sats, then the script will close trade by Taking profit
b>Verge increases to 850 only, but the RSI value in 15min chart has gone above 70 (Overbought-default value) then scipt will close trade.
c>Verge decreases to 995 sats, then script will close trade by Stop loss hit.
d>Verge surges to 840 but then again drops slightly to 835, script will again close trade by Trailing SL hit.
Initial capital is set to 10 btc
Make sure to check the performance summary tab below and overview of the script running on #XVGBTC since 1 May 2018-Till date
Profit -11.6% while running script
Where Buy and hold return for verge in the same period is:
- to get an instant notification, once i publish a script or a trading analysis/trade-setup , which will always be available for free for everyone!!!
XPloRR MA-Buy ATR-Trailing-Stop Long Term Strategy Beating B&HXPloRR MA-Buy ATR-MA-Trailing-Stop Strategy
Long term MA Trailing Stop strategy to beat Buy&Hold strategy
None of the strategies that I tested can beat the long term Buy&Hold strategy. That's the reason why I wrote this strategy.
Purpose: beat Buy&Hold strategy with around 10 trades. 100% capitalize sold trade into new trade.
My buy strategy is triggered by the EMA(blue) crossing over the SMA curve(orange).
My sell strategy is triggered by another EMA(lime) of the close value crossing the trailing stop(green) value.
The trailing stop value(green) is set to a multiple of the ATR(15) value.
ATR(15) is the SMA(15) value of the difference between high and low values.
Every stock has it's own "DNA", so first thing to do is find the right parameters to get the best strategy values voor EMA, SMA and Trailing Stop.
Then keep using these parameter for future buy/sell signals only for that particular stock.
Do the same for other stocks.
Here are the parameters:
Exponential MA: buy trigger when crossing over the SMA value (use values between 11-50)
Simple MA: buy trigger when EMA crosses over the SMA value (use values between 20 and 200)
Stop EMA: sell trigger when Stop EMA of close value crosses under the trailing stop value (use values between 8 and 16)
Trailing Stop #ATR: defines the trailing stop value as a multiple of the ATR(15) value
Example parameters for different stocks (Start capital: 1000, Order=100% of equity, Period 1/1/2005 to now):
BAR(Barco): EMA=11, SMA=82, StopEMA=12, Stop#ATR=9
Buy&HoldProfit: 45.82%, NetProfit: 294.7%, #Trades:8, %Profit:62.5%, ProfitFactor: 12.539
AAPL(Apple): EMA=12, SMA=45, StopEMA=12, Stop#ATR=6
Buy&HoldProfit: 2925.86%, NetProfit: 4035.92%, #Trades:10, %Profit:60%, ProfitFactor: 6.36
BEKB(Bekaert): EMA=12, SMA=42, StopEMA=12, Stop#ATR=7
Buy&HoldProfit: 81.11%, NetProfit: 521.37%, #Trades:10, %Profit:60%, ProfitFactor: 2.617
SOLB(Solvay): EMA=12, SMA=63, StopEMA=11, Stop#ATR=8
Buy&HoldProfit: 43.61%, NetProfit: 151.4%, #Trades:8, %Profit:75%, ProfitFactor: 3.794
PHIA(Philips): EMA=11, SMA=80, StopEMA=8, Stop#ATR=10
Buy&HoldProfit: 56.79%, NetProfit: 198.46%, #Trades:6, %Profit:83.33%, ProfitFactor: 23.07
I am very curious to see the parameters for your stocks and please make suggestions to improve this strategy.
Aurum15 - http://tvautotrader.comAurum15 - tvautotrader.com
Initial version of strategy, basing on market condition and price movement according to MA's, closing on RSI overbought value.
Exit position are configurable by RSI (default rsi(open,29) > 70), designed for 15 minutes charts
It creates very long trades (above 300 bars per trade) but is very profitable.
Tested at:
USOIL - 66% profitable, 15 trades since 2017-09-04
LTCUSD - 75% profitable, 20 trades since 2017-10-02
XRPUSD - 87.5% profitable, 8 trades since 2017-10-02
IOTUSD - 77% profitable, 9 trades since 2017-10-02
This strat is not for sale yet, I need to make futher tests in more sideways market.
Upgraded XAUUSD 30m only Strategy V2.0So i've been fiddling around with this once more
The result is increased net profit, same time frame as previous strategy, more drawdown, but that comes with the net profit.
1 pip = 1$
Pyramiding of 3 orders.
Commission included.
More trades
Profitability rate is about the same.
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..
Baseline TrendBaseline Trend Strategy Overview
Baseline Trend is a crypto-only trading strategy built on straightforward price-based logic: market direction is determined solely by the price’s position relative to a selected baseline open price. No technical indicators like RSI, MACD, or volume are used—this approach is purely focused on price action and position size manipulation.
This strategy is a genuine concept, developed from my own market analysis and logical theory, refined through extensive observation of crypto market behaviour.
While the strategy offers structure and adaptability, it’s important to recognise that no single trading system or indicator fits all market conditions. This tool is meant to support decision-making, not replace it—encouraging traders to stay flexible, informed, and in control of their risk.
Important Usage Note:
This system is intended for crypto markets only.
– When used as an indicator guide, it can be applied to both spot and futures markets.
– However, when used with web-hook automation, it is designed only for futures contracts.
Ensure compatibility with your trading setup before using automation features.
Core Logic: The Baseline
The strategy revolves around the concept of a “Baseline”, with three types available:
Main Baseline: Defines the primary trend direction. If the price is above, go long; if below, go short.
Second Baseline and Third Baseline: Used to measure buying/selling pressure and are key to certain take-profit logic options.
Baselines are customisable to different timeframes—Year, Month, Week, and more—based on available input settings. Structurally, the Main Baseline is the highest-level trend reference, followed by the Second, then Third.
Users can mix and match these baselines across timeframes to backtest crypto symbols and understand behaviour patterns, particularly when used with standard candlestick charts.
Entry & Exit Logic
Entry Signal: Triggered when price crosses over/under a defined distance (percentage) from the Main Baseline. This distance is the Trade Line, calculated based on the close price.
Exit Signal / Stop Loss: If price moves un-favorable and crosses over/under the Stop Loss Line (a defined distance from the Main Baseline), the open position will be force-closed according to user-defined settings.
LiqC (Liquidation Cut)
LiqC is a secondary stop-loss that activates when a leveraged position’s loss equals or exceeds the user-defined liquidation threshold. It forcefully closes the position to help prevent full liquidation before stop-loss, providing an extra layer of protection.
This LiqC is directly tied to the leverage level set by the user. Please ensure you understand how leverage affects liquidation risk, as different broker exchanges may use different liquidation ratio models. Using incorrect assumptions or mismatched leverage values may result in unexpected behaviour.
Position Sizing & Block Units
This strategy features a block-based position sizing system designed for flexibility and precision in trade management:
Block Range: Customisable from 1 to 10 blocks
Risk Allocation: Controlled through a user-defined ROE (Risk of Equity) value
For example, setting an ROE of 0.1% with 10 blocks allocates a total of 1% of account equity to the position. This structure supports both conservative and aggressive risk approaches, depending on user preference.
Block sizes are automatically calculated in alignment with exchange requirements, using Minimum Notional Value (MNV) and Minimum Trade Amount (MTA). These values are dynamically calculated based on the live market price, and scaled relative to the trader’s balance and selected risk percentage. This ensures accurate sizing with built-in adaptability for any account level and current market conditions.
Scalping Meets Trend Holding
This system blends short-term scalping with longer-term trend holding, offering a flexible and adaptive trading style.
Example:
Enter 10 blocks → take quick profits on 5 blocks → let the remaining 5 ride the trend.
This dual-layered approach allows traders to secure early gains while staying positioned for larger market moves. Think of it as:
5 Blocks to Protect: Capture quick wins and manage exposure.
5 Blocks to Pursue: Let profits run by following the broader trend.
By combining both protection and pursuit, the strategy supports risk control without sacrificing the potential for extended returns.
Flexible Take-Profit Logic
The strategy supports multiple, customisable take-profit mechanisms:
TP1–4 (Profit Percentage)
Triggers take profit of 1 block unit when unrealised gains reach defined percentage thresholds (TP1, TP2, TP3, TP4).
Buying/Selling Pressure-Based Take Profit
D1 – Pressure 1
Measures pressure between Second and Third Baselines.
If the distance between them exceeds a user-defined DPT (Decrease Post Threshold) and the price moves far enough from the Third Baseline, D1 activates to take profit or scale out one block.
D2 – Pressure 2
Measures pressure between the Main and Second Baselines.
Works similarly to D1, using a separate distance and pressure trigger.
Note: Both D1 and D2 deactivate in reversal or even trend conditions.
D3–5: High-High / Low-Low Logic
Based on bar index tracking after position entry:
For Long Positions: If after D3 bars the price doesn't exceed the previous bar's high, the system executes a take profit or scale-out.
For Short Positions: If the price doesn't drop below the previous low, the same logic applies.
This approach adds time-based and momentum-aware exit flexibility.
Leverage & Liquidation Risk
When backtesting with leverage enabled, the system checks whether historical candles exceed the liquidation range, calculated based on the average entry price and the leverage input. If the Liquidation Risk Count exceeds 1, profit and loss accuracy may be affected. Traders are encouraged to monitor this count closely to ensure realistic backtesting results.
Since the system cannot directly control or sync with your broker exchange’s actual leverage setting, it’s important to manually match the system’s leverage input with your broker’s configured leverage.
For example: If the system leverage input is set to 10, your exchange leverage setting must also be set to 10. Any mismatch will lead to inaccurate liquidation risk and PnL calculations.
Backtesting and Customisation
All TP1–4 and D1–5 functions are fully optional and customisable. Users are encouraged to backtest different crypto symbols to observe how price behaviour aligns with baseline structures and pressure metrics.
Each of the TP1–4 and D1–5 triggers is designed to execute only once per open position, ensuring controlled and predictable behaviour within each trade cycle.
Since backtesting is based on available historical bar data, please note that data availability varies depending on your TradingView subscription plan. For more reliable insights, it’s recommended to backtest across multiple time ranges, not just the full dataset, to assess the stability and consistency of the strategy’s performance over time.
Additionally, the time frame resolution interval in TradingView is customisable. For best results, use commonly supported time frames such as 30 minutes, 1 hour, 4 hours, 1 day, or 1 week. While the system is designed to support a broad range of intervals, non-standard resolutions may still cause calculation errors.
Currently, the system supports the following resolution ranges:
Intraday: from 1 minute to 720 minutes
(e.g., 60 minutes = 1 hour, 240 minutes = 4 hours, 720 minutes = 12 hours)
Daily: from 1 day to 6 days
Weekly: from 1 week to 3 weeks
Monthly: from 1 month to 4 months
Although the script is built to adapt to various resolutions, users should still monitor output behaviour closely, especially when testing less common or edge-case time frames.
System Usage Notice:
This system can be used as a standalone trading indicator or integrated with an exchange that supports web-hook signal execution. If you choose to automate trades via web-hook, please ensure you fully understand how to configure the setup properly. Web-hook integration methods vary between exchanges, and incorrect setup may lead to unintended trades. Users are responsible for ensuring proper configuration and monitoring of their automation.
Note on Lower Time Frame Usage
When using lower time frames (e.g., 1-minute charts) as the trading time frame, please be aware that available historical data may be limited depending on your subscription plan. This can affect the depth and reliability of backtesting, making it harder to establish a trustworthy probability model for a symbol’s behaviour over time.
Additionally, when pairing a high-level Main Baseline (MBL) time line (such as "1 Month") with low time frame resolutions (like 1-minute), you may encounter order execution limits or calculation overloads during backtesting. This is due to the large number of historical bars required, which can strain the system's capacity.
That said, if a user intentionally chooses to work with lower time frames, that decision is fully respected—but it should be done with awareness and at the user’s own risk.
Things to Be Aware Of (Web-hook Usage Only)
The following points apply if you're using web-hook automation to send signals from the system to an exchange:
Alert Signal Reliability
During extreme market volatility, some broker exchanges may fail to respond to web-hook signals due to traffic overload. While rare, this has occurred in the past and should be considered when relying on automation.
Alert Expiration (TradingView)
If you're on a Basic plan, TradingView alerts are only active for a limited time—typically around 1.5 months. Once expired, signals will no longer be sent out.
To keep your system active, reset the alert before expiration. For uninterrupted alerts, consider upgrading to a Premium plan, which supports permanent alert activation.
TradingView Alert Maintenance
TradingView may occasionally perform system maintenance, during which alerts may temporarily stop functioning. It’s recommended to monitor TradingView’s status if you’re relying on real-time automation.
Repainting
As of the current version, no repainting behaviour has been observed. Signal stability and consistency have been maintained across real-time and historical bars.
Order Execution Type and Fill Logic
All signals use Limit orders by default, except for MBL Exit and Fallback execution, which use Market orders.
Since Limit orders are not guaranteed to fill, the system includes logic to cancel unfilled orders and resend them. If necessary, a Fallback Market order is used to avoid conflict with new incoming trades.
This has only happened once, and is considered rare, but users should always monitor execution status to ensure accuracy and alignment with system behaviour.
Feedback
If you encounter any errors, bugs, or unexpected behaviour while using the system, please don’t hesitate to let me know. Your input is invaluable for helping improve the strategy in future updates.
Likewise, if you have any suggestions or ideas for enhancing the system—whether it’s a new feature, adjustment, or usability improvement—please feel free to share. Together, we can continue refining the tool to make it more robust and beneficial for everyone.
Disclaimer
All trading involves risk, particularly in the crypto market where conditions can be highly volatile. Past performance does not guarantee future outcomes, and market behaviour may evolve over time. This strategy is offered as a tool to support trading decisions and should not be considered financial or investment advice. Each user is responsible for their own actions and accepts full responsibility for any results that may arise from using this system.
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.**
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.
⸻
Golden Arrow Strategy [LuciTech]The "Golden Arrow Strategy " is a sophisticated trading system built to pinpoint Fair Value Gaps (FVGs) and harness immediate rebalance patterns—termed "Golden Arrows"—for accurate trade setups. This strategy version is packed with advanced tools like dynamic risk management, customizable stop-loss methods, and an exceptional alert ecosystem featuring Telegram and webhook integration, ensuring traders stay connected to opportunities wherever they are.
Key Features
Precision FVG Detection:
Detects single or dual consecutive FVGs with customizable width settings (points, percentages, or ATR-based) for robust signal validation.
Versatile Stop-Loss Options:
Offers ATR-based, candle-based, FVG-based, or second FVG-based stop-loss calculations, giving traders ultimate flexibility.
Comprehensive Risk Management:
Features position sizing based on risk percentage, adjustable risk-reward ratios, and breakeven adjustments to safeguard profits effortlessly.
Time-Based Precision: Includes standard time filters plus a unique 2:30 PM filter, complete with visual cues like colored candles, perfect for traders targeting specific market windows.
Visual Clarity: Plots FVG boxes, second FVG boxes, and trade levels (entry, stop-loss, take-profit) with customizable colors and extension options.
Next-Level Alert System:
Webhook Alerts: Delivers detailed trade data in JSON format, enabling seamless automation or integration with external platforms.
Telegram Alerts: Sends real-time, formatted notifications straight to your Telegram chat—choose between standard or concise, emoji-rich messages for instant, actionable insights on the go.
Backtesting Ready: Fully equipped with strategy functions to test performance across various assets and timeframes with ease.
How It Works
FVG Identification: Detects FVGs based on user-defined width criteria, with an optional requirement for two consecutive FVGs to enhance signal strength.
Golden Arrow Signals: Triggers when price fills the FVG and rebalances, confirmed by wick penetration and closing conditions.
Automated Trade Execution: Enters long or short positions with position sizes calculated to match your risk tolerance.
Dynamic Exits: Sets stop-loss and take-profit levels using your preferred method, with optional breakeven shifts as profits grow.
Visual Feedback:
Displays bullish/bearish FVG boxes and second FVG boxes with distinct colors.
Plots entry, stop-loss, and take-profit levels for active trades
Alert Powerhouse:
Webhook Alerts: Pushes trade details in JSON format for external use—perfect for automation enthusiasts.
Telegram Alerts: Sends beautifully formatted messages to your Telegram chat, including trade direction, entry price, stop-loss, and take-profit, in either detailed or concise formats. Stay in the loop, no matter where you are.
Why This Strategy Shines
Adaptable and Precise: Whether you prefer single FVG signals or the added confirmation of dual FVGs, paired with multiple stop-loss options, this strategy molds to your trading style and market conditions.
Unmatched Alert Experience: The Telegram alerts are a game-changer—imagine getting a crisp, emoji-enhanced message with all trade details delivered instantly to your phone. Combined with webhook alerts, you’re always connected, whether you’re automating trades or just staying informed.
Risk Management Made Simple: Automated position sizing and breakeven features take the guesswork out of protecting your capital and securing gains.
CE + TSI Reversal Strategy🔁 CE + TSI Reversal Strategy (Optimized)
This strategy combines:
✅ Chandelier Exit flips (trend reversal detection)
✅ True Strength Index (TSI) crossover (momentum confirmation)
✅ Rejection candle filter (strong entry signal)
Key Features:
📈 Long-only entries to avoid poor-performing shorts
🔒 Rejection candle filter: entry only on strong price conviction
🎯 Fixed Stop Loss: $6, Take Profit: $9 (can be adjusted)
📊 Backtested with Pepperstone XAUUSD 5M data
Results (1-year backtest):
✅ Win rate: 52%
✅ Profit factor: 1.65
✅ Zero margin calls
🧠 Clean, consistent equity curve with fewer but higher quality trades
Perfect for traders focused on precision reversals with minimal risk exposure.
Long/Short/Exit/Risk management Strategy # LongShortExit Strategy Documentation
## Overview
The LongShortExit strategy is a versatile trading system for TradingView that provides complete control over entry, exit, and risk management parameters. It features a sophisticated framework for managing long and short positions with customizable profit targets, stop-loss mechanisms, partial profit-taking, and trailing stops. The strategy can be enhanced with continuous position signals for visual feedback on the current trading state.
## Key Features
### General Settings
- **Trading Direction**: Choose to trade long positions only, short positions only, or both.
- **Max Trades Per Day**: Limit the number of trades per day to prevent overtrading.
- **Bars Between Trades**: Enforce a minimum number of bars between consecutive trades.
### Session Management
- **Session Control**: Restrict trading to specific times of the day.
- **Time Zone**: Specify the time zone for session calculations.
- **Expiration**: Optionally set a date when the strategy should stop executing.
### Contract Settings
- **Contract Type**: Select from common futures contracts (MNQ, MES, NQ, ES) or custom values.
- **Point Value**: Define the dollar value per point movement.
- **Tick Size**: Set the minimum price movement for accurate calculations.
### Visual Signals
- **Continuous Position Signals**: Implement 0 to 1 visual signals to track position states.
- **Signal Plotting**: Customize color and appearance of position signals.
- **Clear Visual Feedback**: Instantly see when entry conditions are triggered.
### Risk Management
#### Stop Loss and Take Profit
- **Risk Type**: Choose between percentage-based, ATR-based, or points-based risk management.
- **Percentage Mode**: Set SL/TP as a percentage of entry price.
- **ATR Mode**: Set SL/TP as a multiple of the Average True Range.
- **Points Mode**: Set SL/TP as a fixed number of points from entry.
#### Advanced Exit Features
- **Break-Even**: Automatically move stop-loss to break-even after reaching specified profit threshold.
- **Trailing Stop**: Implement a trailing stop-loss that follows price movement at a defined distance.
- **Partial Profit Taking**: Take partial profits at predetermined price levels:
- Set first partial exit point and percentage of position to close
- Set second partial exit point and percentage of position to close
- **Time-Based Exit**: Automatically exit a position after a specified number of bars.
#### Win/Loss Streak Management
- **Streak Cutoff**: Automatically pause trading after a series of consecutive wins or losses.
- **Daily Reset**: Option to reset streak counters at the start of each day.
### Entry Conditions
- **Source and Value**: Define the exact price source and value that triggers entries.
- **Equals Condition**: Entry signals occur when the source exactly matches the specified value.
### Performance Analytics
- **Real-Time Stats**: Track important performance metrics like win rate, P&L, and largest wins/losses.
- **Visual Feedback**: On-chart markers for entries, exits, and important events.
### External Integration
- **Webhook Support**: Compatible with TradingView's webhook alerts for automated trading.
- **Cross-Platform**: Connect to external trading systems and notification platforms.
- **Custom Order Execution**: Implement advanced order flows through external services.
## How to Use
### Setup Instructions
1. Add the script to your TradingView chart.
2. Configure the general settings based on your trading preferences.
3. Set session trading hours if you only want to trade specific times.
4. Select your contract specifications or customize for your instrument.
5. Configure risk parameters:
- Choose your preferred risk management approach
- Set appropriate stop-loss and take-profit levels
- Enable advanced features like break-even, trailing stops, or partial profit taking as needed
6. Define entry conditions:
- Select the price source (such as close, open, high, or an indicator)
- Set the specific value that should trigger entries
### Entry Condition Examples
- **Example 1**: To enter when price closes exactly at a whole number:
- Long Source: close
- Long Value: 4200 (for instance, to enter when price closes exactly at 4200)
- **Example 2**: To enter when an indicator reaches a specific value:
- Long Source: ta.rsi(close, 14)
- Long Value: 30 (triggers when RSI equals exactly 30)
### Best Practices
1. **Always backtest thoroughly** before using in live trading.
2. **Start with conservative risk settings**:
- Small position sizes
- Reasonable stop-loss distances
- Limited trades per day
3. **Monitor and adjust**:
- Use the performance table to track results
- Adjust parameters based on how the strategy performs
4. **Consider market volatility**:
- Use ATR-based stops during volatile periods
- Use fixed points during stable markets
## Continuous Position Signals Implementation
The LongShortExit strategy can be enhanced with continuous position signals to provide visual feedback about the current position state. These signals can help you track when the strategy is in a long or short position.
### Adding Continuous Position Signals
Add the following code to implement continuous position signals (0 to 1):
```pine
// Continuous position signals (0 to 1)
var float longSignal = 0.0
var float shortSignal = 0.0
// Update position signals based on your indicator's conditions
longSignal := longCondition ? 1.0 : 0.0
shortSignal := shortCondition ? 1.0 : 0.0
// Plot continuous signals
plot(longSignal, title="Long Signal", color=#00FF00, linewidth=2, transp=0, style=plot.style_line)
plot(shortSignal, title="Short Signal", color=#FF0000, linewidth=2, transp=0, style=plot.style_line)
```
### Benefits of Continuous Position Signals
- Provides clear visual feedback of current position state (long/short)
- Signal values stay consistent (0 or 1) until condition changes
- Can be used for additional calculations or alert conditions
- Makes it easier to track when entry conditions are triggered
### Using with Custom Indicators
You can adapt the continuous position signals to work with any custom indicator by replacing the condition with your indicator's logic:
```pine
// Example with moving average crossover
longSignal := fastMA > slowMA ? 1.0 : 0.0
shortSignal := fastMA < slowMA ? 1.0 : 0.0
```
## Webhook Integration
The LongShortExit strategy is fully compatible with TradingView's webhook alerts, allowing you to connect your strategy to external trading platforms, brokers, or custom applications for automated trading execution.
### Setting Up Webhooks
1. Create an alert on your chart with the LongShortExit strategy
2. Enable the "Webhook URL" option in the alert dialog
3. Enter your webhook endpoint URL (from your broker or custom trading system)
4. Customize the alert message with relevant information using TradingView variables
### Webhook Message Format Example
```json
{
"strategy": "LongShortExit",
"action": "{{strategy.order.action}}",
"price": "{{strategy.order.price}}",
"quantity": "{{strategy.position_size}}",
"time": "{{time}}",
"ticker": "{{ticker}}",
"position_size": "{{strategy.position_size}}",
"position_value": "{{strategy.position_value}}",
"order_id": "{{strategy.order.id}}",
"order_comment": "{{strategy.order.comment}}"
}
```
### TradingView Alert Condition Examples
For effective webhook automation, set up these alert conditions:
#### Entry Alert
```
{{strategy.position_size}} != {{strategy.position_size}}
```
#### Exit Alert
```
{{strategy.position_size}} < {{strategy.position_size}} or {{strategy.position_size}} > {{strategy.position_size}}
```
#### Partial Take Profit Alert
```
strategy.order.comment contains "Partial TP"
```
### Benefits of Webhook Integration
- **Automated Trading**: Execute trades automatically through supported brokers
- **Cross-Platform**: Connect to custom trading bots and applications
- **Real-Time Notifications**: Receive trade signals on external platforms
- **Data Collection**: Log trade data for further analysis
- **Custom Order Management**: Implement advanced order types not available in TradingView
### Compatible External Applications
- Trading bots and algorithmic trading software
- Custom order execution systems
- Discord, Telegram, or Slack notification systems
- Trade journaling applications
- Risk management platforms
### Implementation Recommendations
- Test webhook delivery using a free service like webhook.site before connecting to your actual trading system
- Include authentication tokens or API keys in your webhook URL or payload when required by your external service
- Consider implementing confirmation mechanisms to verify trade execution
- Log all webhook activities for troubleshooting and performance tracking
## Integrating with Confluence of Signals
The LongShortExit strategy can be enhanced by using it in conjunction with the "Confluence of Alerts" indicator to create more robust entry conditions based on multiple technical signals.
### What is Confluence of Signals?
The Confluence of Alerts indicator allows you to define up to 8 different technical conditions that must be met simultaneously to generate a trading signal. This approach helps filter out false signals and only enters trades when multiple technical factors align.
### Integration Approach
#### Method 1: Using Confluence as a Signal Source
1. Add the Confluence of Alerts indicator to your chart
2. Configure your desired technical conditions (RSI, moving averages, support/resistance, etc.)
3. In the LongShortExit strategy settings:
- Set Long Source to `plot("Long All")` from the Confluence indicator
- Set Long Value to `1` with "Equals" condition
- Similarly for Short Source using `plot("Short All")`
#### Method 2: Modifying the Strategy Code
For more advanced integration, you can incorporate the condition logic directly:
```pine
// Add to the top of your LongShortExit strategy
//@import TradersPost/Confluence_of_Alerts/1
// Replace simple entry conditions with confluence signals
longCondition = confluence_long_signal and longEntryCondition
shortCondition = confluence_short_signal and shortEntryCondition
```
### Confluence Configuration Examples
#### Trend-Following Configuration
1. **Condition 1**: When SMA(20) crossing up SMA(50)
2. **Condition 2**: When RSI(14) greater than 50
3. **Condition 3**: When close greater than VWAP
4. **Condition 4**: When ADX(14) greater than 25
#### Support/Resistance Configuration
1. **Condition 1**: When price crossing up pivot support
2. **Condition 2**: When Stochastic %K crossing up %D
3. **Condition 3**: When volume greater than average volume
4. **Condition 4**: When price greater than previous day's close
### Benefits of Using Confluence with LongShortExit
- **Reduced False Signals**: Enter trades only when multiple conditions confirm the signal
- **Higher Probability Trades**: Each additional confirming factor increases trade success probability
- **Customizable Filter**: Adapt the conditions to suit different market environments and trading styles
- **Visual Confirmation**: The Confluence indicator provides clear visual signals when all conditions are met
### Implementation Tips
1. Start with 2-3 conditions before adding more complexity
2. Ensure conditions aren't redundant (e.g., don't use multiple similar indicators)
3. Include conditions from different categories:
- Trend indicators (moving averages, ADX)
- Momentum indicators (RSI, MACD)
- Volume indicators
- Support/resistance levels
4. Test different timeframes for the conditions
5. Use the "on Bar Close" option for more reliable signals
## Strategy Customization Tips
### For Scalping
- Set smaller profit targets (1-3 points)
- Use tighter stop-losses
- Enable break-even feature after small profit
- Set higher max trades per day
### For Day Trading
- Use moderate profit targets
- Implement partial profit taking
- Enable trailing stops
- Set reasonable session trading hours
### For Swing Trading
- Use longer-term charts
- Set wider stops (ATR-based often works well)
- Use higher profit targets
- Disable daily streak reset
## Common Troubleshooting
### Low Win Rate
- Consider widening stop-losses
- Verify that entry conditions aren't triggering too frequently
- Check if the equals condition is too restrictive; consider small tolerances
### Missing Obvious Trades
- The equals condition is extremely precise. Price must exactly match the specified value.
- Consider using floating-point precision for more reliable triggers
### Frequent Stop-Outs
- Try ATR-based stops instead of fixed points
- Increase the stop-loss distance
- Enable break-even feature to protect profits
## Important Notes
- The exact equals condition is strict and may result in fewer trade signals compared to other conditions.
- For instruments with decimal prices, exact equality might be rare. Consider the precision of your value.
- Break-even and trailing stop calculations are based on points, not percentage.
- Partial take-profit levels are defined in points distance from entry.
- The continuous position signals (0 to 1) provide valuable visual feedback but don't affect the strategy's trading logic directly.
- When implementing continuous signals, ensure they're aligned with the actual entry conditions used by the strategy.
---
*This strategy is for educational and informational purposes only. Always test thoroughly before using with real funds.*