MFI Strategy with Oversold Zone Exit and AveragingThis strategy is based on the Money Flow Index (MFI) and aims to enter a long position when the MFI exits an oversold zone, with specific rules for limit orders, stop-loss, and take-profit settings. Here's a detailed breakdown:
Key Components
1. **Money Flow Index (MFI)**: The strategy uses the MFI, a volume-weighted indicator, to gauge whether the market is in an oversold condition (default threshold of MFI < 20). Once the MFI rises above the oversold threshold, it signals a potential buying opportunity.
2. **Limit Order for Long Entry**: Instead of entering immediately after the oversold condition is cleared, the strategy places a limit order at a price slightly below the current price (by a user-defined percentage). This helps achieve a better entry price.
3. **Stop-Loss and Take-Profit**:
- **Stop-Loss**: A stop-loss is set to protect against significant losses, calculated as a percentage below the entry price.
- **Take-Profit**: A take-profit target is set as a percentage above the entry price to lock in gains.
4. **Order Cancellation**: If the limit order isn’t filled within a specific number of bars (default is 5 bars), it’s automatically canceled to avoid being filled at a potentially suboptimal price as market conditions change.
Strategy Workflow
1. **Identify Oversold Zone**: The strategy checks if the MFI falls below a defined oversold level (default is 20). Once this condition is met, the flag `inOversoldZone` is set to `true`.
2. **Wait for Exit from Oversold Zone**: When the MFI rises back above the oversold level, it’s considered a signal that the market is potentially recovering, and the strategy prepares to enter a position.
3. **Place Limit Order**: Upon exiting the oversold zone, the strategy places a limit order for a long position at a price below the current price, defined by the `Long Entry Percentage` parameter.
4. **Monitor Limit Order**: A counter (`barsSinceEntryOrder`) starts counting the bars since the limit order was placed. If the order isn’t filled within the specified number of bars, it’s canceled automatically.
5. **Set Stop-Loss and Take-Profit**: Once the order is filled, a stop-loss and take-profit are set based on user-defined percentages relative to the entry price.
6. **Exit Strategy**: The trade will close automatically when either the stop-loss or take-profit level is hit.
Advantages
- **Risk Management**: With configurable stop-loss and take-profit, the strategy ensures losses are limited while capturing profits at pre-defined levels.
- **Controlled Entry**: The use of a limit order below the current price helps secure a better entry point, enhancing risk-reward.
- **Oversold Exit Trigger**: Using the exit from an oversold zone as an entry condition can help catch reversals.
Disadvantages
- **Missed Entries**: If the limit order isn’t filled due to insufficient downward movement after the oversold signal, potential opportunities may be missed.
- **Dependency on MFI Sensitivity**: As the MFI is sensitive to both price and volume, its fluctuations might not always accurately represent oversold conditions.
Overall Purpose
The strategy is suited for traders who want to capture potential reversals after oversold conditions in the market, with a focus on precise entries, risk management, and an automated exit plan.
Pyramiding
Buy Below Prev_Low. Sell 100% Above Avg. Pyramiding.This is simple indicator script for long term investors. It will check if the low of today is less than low of yesterday (or any time frame candle) and if the condition is satisfied, then the alert will be triggerred and that particular stock will be bought.
Each time a unit is bought, the average price is calculated and also the trget selling price, which is set at 100% above the average buying price. So once the price reaches that selling price target, the entire holding is sold.
The code resets all the variables back to 0 once a sell signal is triggerred.
LowFinder_PyraMider_V2This strategy is a result of an exploration to experiment with other ways to detect lows / dips in the price movement, to try out alternative ways to exit and stop positions and a dive into risk management. It uses a combination of different indicators to detect and filter the potential lows and opens multiple positions to spread the risk and opportunities for unrealized losses or profits. This script combines code developed by fellow Tradingview community_members.
LowFinder
The lows in the price movement are detected by the Low finder script by RafaelZioni . It finds the potential lows based on the difference between RSI and EMA RSI. The MTF RSI formula is part of the MTFindicators library developed by Peter_O and is integrated in the Low finder code to give the option to use the RSI of higher timeframes. The sensitivity of the LowFinder is controlled by the MA length. When potential lows are detected, a Moving Average, a MTF Stochastic (based the the MTFindiicators by Peter_O) and the average price level filter out the weak lows. In the settings the minimal percentage needed for a low to be detected below the average price can be specified.
Order Sizing and Pyramiding
Pyramiding, or spreading multiple positions, is at the heart of this strategy and what makes it so powerful. The order size is calculated based on the max number of orders and portfolio percentage specified in the input settings. There are two order size modes. The ‘base’ mode uses the same base quantity for each order it opens, the ‘multiply’ mode multiplies the quantity with each order number. For example, when Long 3 is opened, the quantity is multiplied by 3. So, the more orders the bigger the consecutive order sizes. When using ‘multiply’ mode the sizes of the first orders are considerably lower to make up for the later bigger order sizes. There is an option to manually set a fixed order size but use this with caution as it bypasses all the risk calculations.
Stop Level, Take Profit, Trailing Stop
The one indicator that controls the exits is the Stop Level. When close crosses over the Stop Level, the complete position is closed and all orders are exited. The Stop Level is calculated based on the highest high given a specified candle lookback (settings). There is an option to deviate above this level with a specified percentage to tweak for better results. You can activate a Take Profit / Trailing Stop. When activated and close crosses the specified percentage, the Stop Level logic changes to a trailing stop to gain more profits. Another option is to use the percentage as a take profit, either when the stop level crosses over the take profit or close. With this option active, you can make this strategy more conservative. It is active by default.
And finally there is an option to Take Profit per open order. If hit, the separate orders close. In the current settings this option is not used as the percentage is 10%.
Stop Loss
I published an earlier version of this script a couple of weeks ago, but it got hidden by the moderators. Looking back, it makes sense because I didn’t pay any attention to risk management and save order sizing. This resulted in unrealistic results. So, in this script update I added a Stop Loss option. There are two modes. The ‘average price’ mode calculates the stop loss level based on a given percentage below the average price of the total position. The ‘equity’ mode calculates the stop loss level based on a given percentage of your equity you want to lose. By default, the ‘equity’ mode is active. By tweaking the percentage of the portfolio size and the stop loss equity mode, you can achieve a quite low risk strategy set up.
Variables in comments
To sent alerts to my exchange I use a webhook server. This works with a sending the information in the form of a comment. To be able to send messages with different quantities, a variable is added to the comment. This makes it possible to open different positions on the exchange with increasing quantities. To test this the quantities are printed in the comment and the quantities are switched off in the style settings.
This code is a result of a study and not intended for use as a worked out and full functioning strategy. Use it at your own risk. To make the code understandable for users that are not so much introduced into pine script (like me), every step in the code is commented to explain what it does. Hopefully it helps.
Enjoy!
Simple_RSI+PA+DCA StrategyThis strategy is a result of a study to understand better the workings of functions, for loops and the use of lines to visualize price levels. The strategy is a complete rewrite of the older RSI+PA+DCA Strategy with the goal to make it dynamic and to simplify the strategy settings to the bare minimum.
In case you are not familiar with the older RSI+PA+DCA Strategy, here is a short explanation of the idea behind the strategy:
The idea behind the strategy based on an RSI strategy of buying low. A position is entered when the RSI and moving average conditions are met. The position is closed when it reaches a specified take profit percentage. As soon as the first the position is opened multiple PA (price average) layers are setup based on a specified percentage of price drop. When the price hits the layer another position with the same position size is is opened. This causes the average cost price (the white line) to decrease. If the price drops more, another position is opened with another price average decrease as result. When the price starts rising again the different positions are separately closed when each reaches the specified take profit. The positions can be re-opened when the price drops again. And so on. When the price rises more and crosses over the average price and reached the specified Stop level (the red line) on top of it, it closes all the positions at once and cancels all orders. From that moment on it waits for another price dip before it opens a new position.
This is the old RSI+PA+DCA Strategy:
The reason to completely rewrite the code for this strategy is to create a more automated, adaptable and dynamic system. The old version is static and because of the linear use of code the amount of DCA levels were fixed to max 6 layers. If you want to add more DCA layers you manually need to change the script and add extra code. The big difference in the new version is that you can specify the amount of DCA layers in the strategy settings. The use of 'for loops' in the code gives the possibility to make this very dynamic and adaptable.
The RSI code is adapted, just like the old version, from the RSI Strategy - Buy The Dips by Coinrule and is used for study purpose. Any other low/dip finding indicator can be used as well
The distance between the DCA layers are calculated exponentially in a function. In the settings you can define the exponential scale to create the distance between the layers. The bigger the scale the bigger the distance. This calculation is not working perfectly yet and needs way more experimentation. Feel free to leave a comment if you have a better idea about this.
The idea behind generating DCA layers with a 'for loop' is inspired by the Backtesting 3commas DCA Bot v2 by rouxam .
The ideas for creating a dynamic position count and for opening and closing different positions separately based on a specified take profit are taken from the Simple_Pyramiding strategy I wrote previously.
This code is a result of a study and not intended for use as a full functioning strategy. To make the code understandable for users that are not so much introduced into pine script (like myself), every step in the code is commented to explain what it does. Hopefully it helps.
Enjoy!
1 minute crypto strategy (MTF ZigZag)Please read the following explanation and notes before using this strategy.
This strategy is based on pyramiding. It uses two trend indicators(zigzag) in two different timeframes. One can be used to identify trend in higher timeframe and the other can be used to identify trend in smaller time frame. You can change them according to your preference. The default timeframes are set the same so the strategy only opens the trades according to one timeframe (20min). You can change the timeframe of the trend indicators to any timeframe in the settings but first you should add that timeframe to your chart timeframe so you can see that timeframe in the settings.
The first timeframe is for lower timeframe trend identification and the second timeframe is for higher timeframe identification in the settings.
IMPORTANT NOTES:
1. This strategy works best with low cap high volatile Cryptos. It is riskier on big cap cryptos in long term since it takes longer for them to recover from a big drop.
2. This strategy works in any timeframe. The lower the TF the higher profit.
3. This strategy is LONG only (spot).
4. It is very important to run a deep backtest (for example 1 year) and change the settings accordingly on the cryptos you want to trade to see how it performs in longterm.
5. The default pyramiding value is 30 and 3.33% of the portfolio (100/30=3.33%) is used for each trade. It means the strategy opens maximum 30 trades before the TP is hit. If you change the pyramiding you should also change order size as well in order for the strategy to show the exact calculation (your portfolio amount percentage/pyramiding value=ordersize percentage). If you increase pyramiding value the strategy performs safer in long term.
6. The default TP is 1% and the default SL is 80%. You can change the settings according to the backtest on the coins you want to trade. But it is better not to increase the TP.
7. The indicators don't repaint.
8. Please make sure to backtest and fully understand the way this strategy works before using it.
Simple_PyramidingA simple Pyramiding / DCA Strategy. Everyday at a specified time a position is opened. The individual position is closed when a take profit is triggered. Optionally a stop loss can be activated, or the option to close the position at the and of the time frame. You can specify the max amount of open positions. The equity will be divided through the max amount of open positions.
This strategy is a result of an exploration into working with time sessions, pyramiding, for loops and possibilities to trigger individual take profits (profit) and stop loss levels (stop). This strategy is by no means a worked out and reliable strategy. Please feel free to experiment with the code in your indicators and strategies.
RSI+PA+PrTPHi everybody,
This strategy is a RSI, Price Averaging, Pyramiding Strategy based on the earlier RSI+PA+DCA strategy. See below.
For this slightly different strategy I left the DCA option out and instead focused on the Take Profit calculation. In the previous strategy the Take Profit was directly connected to the Average Price level with a specified take profit %. When the price reached the Take Profit all positions where exited. The strategy opened multiple position based on the PA price levels. The separate positions can close when they reach separately specified Take Profit Limit. Each time the prices crosses the PA layer again the position can be re-opened. This causes the average price to drop each time a separate position is opened and closed.
I thought it was an interesting way to minimize losses and in general it works fine. Only when the market goes bearish it can cause significant losses
For the lack of a better word, I dubbed it Progressive Take Profit. The PrTP works different and is less risky. It doesn't directly follow the average price development and is calculated for a part based on the estimated profits of the separate closed positions. Every time a separate position is closed, the profit of that position is deducted of the Take Profit Limit. This causes the Take Profit Limit to drop les drastically then the average price and the whole position will only be closed when the separately opened and closed positions made up for the biggest losses.
There are still some aspects in the puzzle that are not fully worked out yet and I am still working on it, but I wanted to share this idea already and maybe you have some thoughts about it.
The next step is to re-implement a better worked out DCA function.
To be continued.
QaSH Linear Regression + SuperTrendThis script uses linear regression and standard deviation measurements to trigger entries and calculate placement of TP and SL prices. A larger linear regression line will provide the market trend, while a smaller linear regression line will look for pullback entries within the larger trend. Up to 10 orders can run in parallel as a form of pyramiding in and out of a position. The supertrend is used as an additional filter for trend confirmation.
Trend following and mean reversion entries can be used per your preference. Several other entry filters are available for confirmation.
The stoplosses can be moved to breakeven during a trade, and an alert will be sent that includes the exact order ID that needs to be moved, and to what price. This is an advanced feature that is very powerful when used with a capable automation service.
QaSH Percentile BreakoutsThis script makes trades when price is trending past the x percentile ranked bar closing price. Entries can be made when price crosses the threshold, or when price pulls back and forms a pivot point. It can track up to 10 entries independently as a method of pyramiding, each with its own TP and SL price, and it provides a unique order ID to each one for your automation service to use. Several entry condition filters are provided for higher quality entries. Stoploss prices can be moved to breakeven when in profit.
Cyatophilum Accumulation StrategyAn indicator to backtest and automate accumulation/pyramiding custom strategies.
The goal of the strategy is to buy several times when the price is low and sell all when the position is in profit.
Configure your strategy using the entry options and entry filters, then set your Take Profit and StopLoss.
═════════════════════════════════════════════════════════════════════════
█ HOW IT WORKS
The strategy has pyramiding enabled, which means it can open several deals in a row.
It will keep buying until the Take Profit target is reached.
The indicator plots the Take Profit and Break Even line which are recalculated at each new deal.
The target corresponds to the average entry price plus a configurable percentage.
We can see the average entry price line drop lower at each Long Entry.
█ HOW TO USE
Choose a pair that you want to hold/invest in.
Pick a chart time frame that you like, according to how often you want the strategy to place orders. A benefit of this strategy is that it can work on low time frames as well as high time frames. Just keep in mind that the smaller the time frame, the bigger the impact of fees and slippage will be on the strategy results.
Configure your entry condition . You can combine several technical indicators to trigger an entry, such as Top & Bottom, Higher Lows and RSI divergences.
Example with double bottoms:
Filter your entry signal . Add filters to strengthen your entry signal.
Configure your profit target
Use the Take Profit feature to set a target in percentage of price. You can also make it trail.
There is a Trailing Stop Loss feature but the goal of the strategy is to never sell in loss, so it is turned off by default.
Check your backtest parameters
Make sure that the initial capital and order size make sense. Since it is a pyramiding strategy, the sum of all deals should not be bigger than the initial capital.
In this example: Initial capital is 10 k, max active deals is 10, so the max order size is 1 k.
If you use % equity as order size, please note that it will create compounding.
Check the fees, by default they are set to 0.1%.
I also recommend to set a slippage that corresponds to your exchange's spread.
Note: the pyramiding parameter has to be equal to the "Max Active deals" input.
█ FEATURES
• Entry settings
Configure wether to go long or short, or both.
Choose the Max Active deals : the maximum number of deals that you want to open at once.
The Minimum bar delay between deals parameter will help putting space between deals.
• Trend Filter
The trend filter will fitler off long deals when the trend is bearish, and short deals when it is bullish.
Choose a trend line from a list, or any external trend line you can find.
The Trend condition allows to choose wether the trend should switch from slope change or price cross.
• MTF Trend Filter
A secondary trend line, Multi Time Frame.
• Volume Filter
The volume filter will check the bar volume and prevent the entry if it is too low.
• Stop Loss and Take Profit
Configure your stop loss and take profit for long and short trades.
You can also make a trailing stoploss and a trailing take profit.
• Backtest Settings
Choose a backtest period, longs or shorts, wether to use limit orders or not.
An option to close open orders at the current bar if you have multiple open orders and are wondering what it would result to close them now.
Graphics
A Configuration panel with all the indicator settings, useful for sharing/saving a strategy.
A Backtest Results panel with additional information from the strategy tester.
█ ALERTS
The indicator is using the alert() calls: it only uses 1 alert slot to send order messages for each event. This means free TV plans can create 1 complete strategy.
To set your alert messages, open the indicator settings and scroll to the bottom of the "inputs" tab.
Create your alert after you set the messages in the indicator settings, and make sure "Any alert() function call" is set in the alert option.
█ LIMITATIONS
Things to keep in mind when using this strategy.
• No Stop loss
When trading without stop loss, your equity can drop without limit, and it can take a while until price recovers.
This is why when backtesting I recommend to keep an eye on the "Max # Days in trades" statistic which tells the maximum days a trade took to close in profit.
• Spot markets only
Obviously, trading without stop loss means no leverage.
█ BACKTEST RESULTS
The backtest settings used in this snapshot are the following:
Initial Capital: 10 000€
Order size: 1 000 €
Commission: 0.1€ per order
Slippage : 10 ticks
Please read the author instructions below for access and automation.
Argo IV - EXPERIMENTAL strategy for 3commas with alertsThis strategy lets users create BUY/SELL alerts for 3commas single bots in a simple way, based on a built in set of indicators that can be tweaked to work together or separately through the study settings. Indicators include Bollinger Bands , Williams %R , RSI , EMA , SMA , Market Cipher, Inverse Fisher Transform, RSI divergence.
It is based on the ARGO I study ( here ), with the following major differences:
- It uses pyramiding (see strategy "properties")
- It includes a lot of new options for deal start/close conditions for maximum control
- It doesn't require any external tool to backtest.
If the user choses to create both BUY and SELL signals from the study settings, the alert created will send both BUY and SELL signals for the selected pair. Note the script will only send alerts for the pair selected in the study settings, not for the current chart (if different).
Important : it is only an early experiment, I will only release the script when satisfied with performance. Until then, I advise not to use this for any real trading.
How to use:
- Add the script to the current chart
- Open the strategy settings , insert bot details. Pairs MUST be in capital letters or 3commas will not recognize them.
- Still in the settings, tweak the deal start/close conditions from various indicators until happy. The strategy will plot the entry / exit points on the chart
- When happy, right click on the "..." next to the study name, then "Add alert'".
- Under "Condition", on the second line, chose "Any alert () function call". Add the webhook from 3commas, give it a name, and "create".
(IK) Grid ScriptThis is my take on a grid trading strategy. From Investopedia:
"Grid trading is most commonly associated with the foreign exchange market. Overall the technique seeks to capitalize on normal price volatility in an asset by placing buy and sell orders at certain regular intervals above and below a predefined base price."
This strategy is best used on sideways markets, without a definitive up or down major trend. Because it doesn't rely on huge vertical movement, this strategy is great for small timeframes. It only goes long. I've set initial_capital to 100 USD. default_qty_value should be your initial capital divided by your amount of grid lines. I'm also assuming a 0.1% commission per trade.
Here's the basic algorithm:
- Create a grid based on an upper-bound (strong resistance) and a lower-bound (strong support)
- Grid lines are spaced evenly between these two bounds. (I recommend anywhere between 5-10 grid lines, but this script lets you use up to 15. More gridlines = more/smaller trades)
- Identify nearest gridline above and below current price (ignoring the very closest grid line)
- If price crosses under a near gridline, buy and recalculate near gridlines
- If price crosses over a near gridline, sell and recalculate near gridlines
- Trades are entered and exited based on a FIFO system. So if price falls 3 grid lines (buy-1, buy-2, buy-3), and subsequently crosses above one grid line, only the first trade will exit (sell-1). If it falls again, it will enter a new trade (buy-4), and if it crosses above again it will sell the original second trade (sell-2). The amount of trades you can be in at once are based on the amount of grid lines you have.
This strategy has no built-in stop loss! This is not a 'set-it-and-forget-it" script. Make sure that price remains within the bounds of your grid. If prices exits above the grid, you're in the money, but you won't be making any more trades. If price exits below the grid, you're 100% staked in whatever you happen to be trading.
This script is more complicated than my last one, but should be more user friendly. Make sure to correctly set your lower-bound and upper-bound based on strong support and resistance (the default values for these are probably going to be meaningless). If you change your "Grid Quantity" (amount of grid lines) make sure to also change your 'Order Size' property under settings for proper test results (or default_qty_value in the strategy() declaration).
Dankland Playground DCAing multi-strategy OPThis is essentially a script that I made for myself before deciding it may be good enough for you all as well.
How it works basically is this... you have 18 oscillators which can all be used as independently as you wish. That means there are 20 groups which they can be split amongst as you choose.
When in separate groups they should not be able to sell eachothers positions without triggering a stop loss. Every single oscillator has its own position sizing and exit sizing which can be stated as either a percent of balance or a flat amount of contracts. Each oscillator has a minimum amount of profit you can tell it to sell it, which is calculated from the average cost of your current position, which does include all groups. This works out to help you average out better entry and exit prices, essentially a method of DCAing.
You can set the minimum sale amount, which is to keep it from placing orders below your exchanges minimum dollar trade cost.
The included oscillators are as follows:
Chande Momentum cross
Moving Average Cross
MACD cross
%B Bollinger cross
Stochastic cross + region filter
Stochastic RSI cross + region filter
SMII cross and region
Three RMIs
Standard RSI
LSMA-smoothed RSI
Know Sure Thing
RSI of KST
Coppock Curve
RSI of Curve
PPO
RSI of PPO
Trix
RSI of Trix
So the idea is that this is essentially multiple strategies combined into one backtestable house. Balance is calculated for all position sizes in order to try to prevent false entries that plague so many scripts (IE, you set pyramiding to 2, each buy $1000, initial balance $1000, and yet it buys two orders off the bat for $2000 total and nets 400% profit because the second was considered free)/
You tune each side and position size them so that they work together as well as you can and in doing so you are able to create a single backtest that is capable of running a bot, essentially, between multiple strategies - you can run a slower Moving Average cross, a faster SMI cross or MACD, or Bollinger that grabs big moves only, all the while having MACD trade small bonuses along the way. This way you can weight the Risk to Reward of each against eachother.
I will not try to claim this is something you can open and with no work have the best bot on the planet. This scripts intention is to take a lot of relatively common trading strategies and combine them under on roof with some risk management and the ability to weigh each against eachother.
If you are looking for a super advanced singular algorithm that tries to capture every peak and valley exactly on the dot, this is not for you. If you are looking for a tool with a high level of customizability, with a publisher who intends to update it to the best of his ability in accordance to seeking to make the best product that I personally can make for both myself and the community (because I will be using this myself of course!) that was specifically designed with the intention of performing well in spot markets by averaging low entry costs and high exit costs, this is for you! That is the exact intention here.
I do not trade margin currently, I trade spot. I am sure this script can be tuned to work on margin but this is not my intention or area so if this is you and there is something you need for margin specifically implemented, ask, because I likely don't know what you need yet.
The current backtest shown is hand-optimized by myself for BTC/USD 1hr market with NO stop loss enabled and all sales weighed to be around 0% minimum profit from the total average entry cost.
I chose to run it myself with no stop losses because Bitcoin is so bullish to me. The stop losses can still be very profitable, but not 1495% net profit. This style of automation is not for everyone as when running with no stop loss and the requirement every sale is somewhat profitable, or at least no very noticeable loss, you wind up relying on yourself to manually stop out if things crash too much and the bot has to stop trading to wait for market to go back up. The thing to do here if you are playing without a stop loss is to have your own alerts set at your fear level, a % drop in a period of time or something like that, and when you reach that point I would consider resetting the bot so it continues to take trades. I personally will accept a temporary drop in USD as long as I can keep my BTC holdings up overall as the goal should always be to have as many BTC as possible by the start and end of the bull run.
Pyramiding Entries On Early Trends (by Coinrule)Pyramiding the entries in a trading strategy may be risky but at the same time very profitable with a proper risk management approach. This strategy seeks to spot early signs of uptrends and increase the position's size while the right conditions persist.
Each trade comes with its stop-loss and take-profit to enforce a proportional risk/reward profile.
The strategy uses a mix of Moving Average based setups to define the buy-signal.
The Moving Average (200) is above the Moving Average (100), which prevents from buying when the uptrend is already in its late stages
The Moving Average (9) is above the Moving Average (100), indicating that the coin is not in a downtrend.
The price crossing above the Moving Average (9) confirms the potential upside used to fire the buy order.
Each entry comes with a stop-loss and a take-profit in a ratio of 1-to-1. After over 400 backtests, we opted for a 3% TP and 3% SL, which provides the best results.
The strategy is optimized on a 1-hour time frame.
The Advantages of this strategy are:
It offers the possibility of adjusting the size of the position proportionally to the confidence in the possibilities that an uptrend will eventually form.
Low drawdowns. On average, the percentage of trades in profit is above 60%, and the stop-loss equal to the take-profit reduces the overall risk.
This strategy returned good returns both with trading pairs with Fiat/stable coins and with BTC. Considering the mixed trends that cryptocurrencies experienced during 2020 vs BTC, this strengthens the strategy's reliability.
The strategy assumes each order to trade 20% of the available capital and pyramids the entries up to 7 times.
A trading fee of 0.1% is taken into account. The fee is aligned to the base fee applied on Binance, which is the largest cryptocurrency exchange.
The Strategy - Ichimoku Kinko Hyo and moreThe purpose of this strategy is to make the signals from my scripts available for verification by backtests. Different signal and filter combinations can be created and specific manual parameter optimization can be carried out.
In detail, this strategy includes:
23 entry signals
two entry filters with each 9 filters
two exit filters with each 9 filters
take profit and stop loss
time period for backtesting
Pyramiding Strategy To Study [mcristianrios]This script simulates what goes behind scenes in a Strategy and it serves to know in Study mode how many positions are running at the same time.
Madmex Trading Suite + FiltersA goodie for my trading groups and friends. A suite of different MAs with Filters with multiple Long/Short Alerts, works as well for pyramiding.
Using fixed TP/SL is advised. I might add TP/SL Alerts later on...
Good luck!
Feedback is appreciated!
Strategy PyramiCoverStrategy for pyramidization and coverage. (Indicator PyramiCover)
Recommended time frame 60 min.
Incremental Order size +This is an old and incomplete script that is being pulled up and dusted off as per request.
The sole purpose of this script was to provide code snippets allowing one to easily convert their own script/strategy to include incremental order sizes. More control over your pyramiding orders.
**It may repaint, and was not intended for trading but more as an attempt to provide examples for more control with pyramiding.
All Instrument Swing Trader with Pyramids, DCA and Leverage
Introduction
This is my most advanced Pine 4 script so far. It combines my range trader algorithms with my trend following pyramids all on a single interval. This script includes my beta tested DCA feature along with simulated leverage and buying power calculations. It has a twin study with several alerts. The features in this script allow you to experiment with different risk strategies and evaluate the approximate impact on your account capital. The script is flexible enough to run on instruments from different markets and at various bar intervals. This strategy can be run in three different modes: long, short and bidirectional. The bidirectional mode has two split modes (Ping Pong and BiDir). It also generates a summary report label with information not available in the TradingView Performance report such as Rate Of Return Standard Deviation and other Sharpe Ratio input values. Notable features include the following:
- Swing Trading Paradigm
- Uni or Bidirectional trading modes
- Calculation presets for Crypto, Stocks and Forex
- Conditional Minimum Profit
- Hard stop loss field
- Two types of DCA (Positive and Negative)
- Discretionary Pyramid levels with threshold adjustment and limiter
- Consecutive loss counter with preset and label
- Reentry loss limiter and trade entry caution fields
- Simulated Leverage and margin call warning label (approximation only)
- Buying power report labels (approximation only)
- Rate Of Return report with input values for Sharpe Ratio, Sortino and others
- Summary report label with real-time status indicators
- Trend follow bias modes (Its still range trading)
- Six anti-chop settings
- Single interval strategy to reduce repaint occurrence
This is a swing trading strategy so the behavior of this script is to buy on weakness and sell on strength. As such trade orders are placed in a counter direction to price pressure. What you will see on the chart is a short position on peaks and a long position on valleys. Just to be clear, the range as well as trends are merely illusions as the chart only receives prices. However, this script attempts to calculate pivot points from the price stream. Rising pivots are shorts and falling pivots are longs. I refer to pivots as a vertex in this script which adds structural components to the chart formation (point, sides and a base). When trading in “Ping Pong” mode long and short positions are intermingled continuously as long as there exists a detectable vertex. Unfortunately, this can work against your backtest profitability on long duration trends where prices continue in a single direction without pullback. I have designed various features in the script to compensate for this event. A well configured script should perform in a range bound market and minimize losses in a trend. For a range trader the trend is most certainly not your friend. I also have a trend following version of this script for those not interested in trading the range.
This script makes use of the TradingView pyramid feature accessible from the properties tab. Additional trades can be placed in the draw-down space increasing the position size and thereby increasing the profit or loss when the position finally closes. Each individual add on trade increases its order size as a multiple of its pyramid level. This makes it easy to comply with NFA FIFO Rule 2-43(b) if the trades are executed here in America. The inputs dialog box contains various settings to adjust where the add on trades show up, under what circumstances and how frequent if at all. Please be advised that pyramiding is an advanced feature and can wipe out your account capital if your not careful. You can use the “Performance Bond Leverage” feature to stress test your account capital with varying pyramid levels during the backtest. Use modest settings with realistic capital until you discover what you think you can handle. See the“Performance Bond Leverage” description for more information.
In addition to pyramiding this script employs DCA which enables users to experiment with loss recovery techniques. This is another advanced feature which can increase the order size on new trades in response to stopped out or winning streak trades. The script keeps track of debt incurred from losing trades. When the debt is recovered the order size returns to the base amount specified in the TV properties tab. The inputs for this feature include a limiter to prevent your account from depleting capital during runaway markets. The main difference between DCA and pyramids is that this implementation of DCA applies to new trades while pyramids affect open positions. DCA is a popular feature in crypto trading but can leave you with large “bags” if your not careful. In other markets, especially margin trading, you’ll need a well funded account and much experience.
To be sure pyramiding and dollar cost averaging is as close to gambling as you can get in respectable trading exchanges. However, if you are looking to compete in a Forex contest or want to add excitement to your trading life style those features could find a place in your strategies. Although your backtest may show spectacular gains don’t expect your live trading account to do the same. Every backtest has some measure to data mining bias. Please remember that.
This script is equipped with a consecutive loss counter. A limit field is provided in the report section of the input dialog box. This is a whole number value that, when specified, will generate a label on the chart when consecutive losses exceed the threshold. Every stop hit beyond this limit will be reported on a version 4 label above the bar where the stop is hit. Use the location of the labels along with the summary report tally to improve the adaptability of system. Don’t simply fit the chart. A good trading system should adapt to ever changing market conditions. On the study version the consecutive loss limit can be used to halt live trading on the broker side (managed manually).
This script can simulate leverage applied to your account capital. Basically, you want to know if the account capital you specified in the properties tab is sufficient to trade this script with the order size, pyramid and DCA parameters needed. TradingView does not halt trading when the account capital is depleted nor do you receive notification of such an event. Input the leverage you intend to trade with and simulate the stress on your account capital. When the check box labeled “Report Margin Call” is enabled a marker will plot on the chart at the location where the threshold was breached. Additionally, the Summary Report will indicated such a breach has occurred during the backtest. Please note that the margin calculation uses a performance bond contract model which is the same type of leverage applied to Forex accounts. This is not the same leverage as stock margin accounts since shares are not actually borrowed. It is also not applicable to futures contracts since we do not calculate maintenance margin. Also note that the account margin and buying power are calculated using the U.S. Dollar as a funding currency. Margin rules across the globe vary considerably so use this feature as an approximation. The “Report Margin Call” plot only appears on negative buying power which is well beyond the NFA enforced margin closeout price. Vary the order size and account capital and activate the buying power plot to get as close as you can to the desired margin call threshold. Also keep in mind that rollover fees, commissions, spreads, etc affect the margin call in actual live trading. This feature does not include any of those costs.
Inputs
The script input dialog box is divided into five sections. The last section, Section 5, contains all of the script reporting options. Notable reporting options are the inputs which provide support for calculating actual Sharpe Ratios and other risk / performance metrics. The TradingView performance report does not produce a scalable Sharpe Ratio which is unfortunate considering the limited data supplied to the backtest. Three report fields made available in this section are intended to enable users to measure the performance of this script using various industry standard risk metrics. In particular, The Sharpe Ratio, Sortino Ratio, Alpha Calculation, Beta Calculation, R-Squared and Monthly Standard Deviation. The following fields are dedicated to this effort:
– ROR Sample Period - Integer number which specifies the rate of return period. This number is a component of the Sharpe Ratio and determines the number of sample periods divisible in the chart data. The number specified here is the length of the period measured in bar intervals. Since the quantity of TradingView historical data is limited this number should reflect the scalar value applied to your Sharpe calculation. When the checkbox “Report Period ROR” is enabled red boxes plot on the dates corresponding to the ROR sample period. The red boxes display information useful in calculating various risk and performance models. Ongoing buying power is included in the period report which is especially useful in assessing the DCA stress on account capital. Important: When the “ROR Sample Period” is specified the script computes the ROR mean value and displays the result in the summary report label on the live end of the chart. Use this number to calculate the historical standard deviation of period returns.
– Return Mean Value - This is the ROR mean value which is displayed in the summary report field “ROR Mean”. Enter the value shown in the summary report here in order to calculate the standard deviation of returns. Once calculated the result is displayed in the summary report field “Standard Dev”. Please note that ROR and standard deviation are calculated on the quote currency of the chart and not the account currency. If you intend to calculate risk metrics based on other denominated returns use the period calculations in a spreadsheet. Important: Do not change the account denomination on the properties tab simply to force a dollar calculation. It will alter the backtest itself since the minimum profit, stop-loss and other variables are always measured in the quote currency of the chart.
– Report Period ROR - This checkbox is used to display the ROR period report which plots a red label above the bars corresponding to the ROR sample period. The sample period is defined by the value entered into the “ROR Sample Period” field. This checkbox only determines if the period labels plot on the chart. It does not enable or disable the ROR calculation itself. Please see input description“ROR Sample Period” for a detailed description of this feature.
Design
This script uses twelve indicators on a single time frame. The original trading algorithms are a port from a much larger program on another trading platform. I’ve converted some of the statistical functions to use standard indicators available on TradingView. The setups make heavy use of the Hull Moving Average in conjunction with EMAs that form the Bill Williams Alligator as described in his book “New Trading Dimensions” Chapter 3. Lag between the Hull and the EMAs form the basis of the entry and exit points. The vertices are calculated using one of five featured indicators. Each indicator is actually a composite of calculations which produce a distinct mean. This mathematical distinction enables the script to be useful on various instruments which belong to entirely different markets. In other words, at least one of these indicators should be able generate pivots on an arbitrarily selected instrument. Try each one to find the best fit.
The entire script is around 2200 lines of Pine code which pushes the limits of what can be created on this platform given the TradingView maximums for: local scopes, run-time duration and compile time. This script incorporates code from both my range trader and trend following published programs. Both have been in development for nearly two years and have been in beta test for the last several months. During the beta test of the range trading script it was discovered that by widening the stop and delaying the entry, add on trading opportunities appeared on the chart. I determined that by sacrificing a few minor features code space could be made available for pyramiding capability in the range trader. The module has been through several refactoring passes and makes extensive use of ternary statements. As such, It takes a full three minutes to compile after adding it to a chart. Please wait for the hovering dots to disappear before attempting to bring up the input dialog box. For the most part the same configuration settings for the range script can be applied to this script.
Inputs to the script use cone centric measurements in effort to avoid exposing adjustments to the various internal indicators. The goal was to keep the inputs relevant to the actual trade entry and exit locations as opposed to a series of MA input values and the like. As a result the strategy exposes over 70 inputs grouped into long or short sections. Inputs are available for the usual minimum profit and stop-loss as well as safeguards, trade frequency, pyramids, DCA, modes, presets, reports and lots of calibrations. The inputs are numerous, I know. Unfortunately, at this time, TradingView does not offer any other method to get data in the script. The usual initialization files such as cnf, cfg, ini, json and xml files are currently unsupported.
I have several example configuration settings that I use for my own trading. They include cryptocurrencies and forex instruments on various time frames.
Indicator Repainting and Anomalies
Indicator repainting is an industry wide problem which mainly occurs when you mix backtest data with real-time data. It doesn't matter which platform you use some form of this condition will manifest itself on your chart over time. The critical aspect being whether live trades on your broker’s account continue to match your TradingView study.
Based on my experience with Pine, most of the problems stem from TradingView’s implementation of multiple interval access. Whereas most platforms provide a separate bar series for each interval requested, the Pine language interleaves higher time frames with the primary chart interval. The problem is exacerbated by allowing a look-ahead parameter to the Security function. The goal of my repaint prevention is simply to ensure that my signal trading bias remains consistent between the strategy, study and broker. That being said this is what I’ve done address this issue in this script:
1. This script uses only 1 time frame. The chart interval.
2. Every entry and exit condition is evaluated on closed bars only.
3. No security functions are called to avoid a look-ahead possibility.
4. Every contributing factor specified in the TradingView wiki regarding this issue has been addressed.
5. Entry and exit setups are not reliant on crossover conditions.
6. I’ve run a 10 minute chart live for a week and compared it to the same chart periodically reloaded. The two charts were highly correlated with no instances of completely opposite real-time signals. I do have to say that there were differences in the location of some trades between the backtest and the study. But, I think mostly those differences are attributable to trading off closed bars in the study and the use of strategy functions in the backtest.
The study does indeed bring up the TV warning dialog. The only reason for this is because the script uses an EMA indicator which according to TradingView is due to “peculiarities of the algorithm”. I use the EMA for the Bill Williams Alligator so there is no way to remove it.
One issue that comes up when comparing the strategy with the study is that the strategy trades show on the chart one bar later than the study. This problem is due to the fact that “strategy.entry()” and “strategy_exit()” do not execute on the same bar called. The study, on the other hand, has no such limitation since there are no position routines.
Please be aware that the data source matters. Cryptocurrency has no central tick repository so each exchange supplies TradingView its feed. Even though it is the same symbol the quality of the data and subsequently the bars that are supplied to the chart varies with the exchange. This script will absolutely produce different results on different data feeds of the same symbol. Be sure to backtest this script on the same data you intend to receive alerts for. Any example settings I share with you will always have the exchange name used to generate the test results.
Usage
The following steps provide a very brief set of instructions that will get you started but will most certainly not produce the best backtest. A trading system that you are willing to risk your hard earned capital will require a well crafted configuration that involves time, expertise and clearly defined goals. As previously mentioned, I have several example configs that I use for my own trading that I can share with you. To get hands on experience in setting up your own symbol from scratch please follow the steps below.
The input dialog box contains over 70 inputs separated into five sections. Each section is identified as such with a makeshift separator input. There are three main areas that must to be configured: long side, short side and settings that apply to both. The rest of the inputs apply to pyramids, DCA, reporting and calibrations. The following steps address these three main areas only. You will need to get your backtest in the black before moving on to the more advanced features.
Step 1. Setup the Base currency and order size in the properties tab.
Step 2. Select the calculation presets in the Instrument Type field.
Step 3. Select “No Trade” in the Trading Mode field.
Step 4. Select the Histogram indicator from Section 2. You will be experimenting with different ones so it doesn’t matter which one you try first.
Step 5. Turn on Show Markers in Section 2.
Step 6. Go to the chart and checkout where the markers show up. Blue is up and red is down. Long trades show up along the red markers and short trades on the blue.
Step 7. Make adjustments to “Base To Vertex” and “Vertex To Base” net change and roc in Section 3. Use these fields to move the markers to where you want trades to be.
Step 8. Try a different indicator from Section 2 and repeat Step 7 until you find the best match for this instrument on this interval. This step is complete when the Vertex settings and indicator combination produce the most favorable results.
Step 9. Go to Section 3 and enable “Apply Red Base To Base Margin”.
Step 10. Go to Section 4 and enable “Apply Blue Base To Base Margin”.
Step 11. Go to Section 2 and adjust “Minimum Base To Base Blue” and “Minimum Base To Base Red”. Observe the chart and note where the markers move relative to each other. Markers further apart will produce less trades but will reduce cutoffs in “Ping Pong” mode.
Step 12. Return to Section 3 and 4 and turn off “Base To Base Margin” which was enabled in steps 9 and 10.
Step 13. Turn off Show Markers in Section 2.
Step 14. Put in your Minimum Profit and Stop Loss in the first section. This is in pips or currency basis points (chart right side scale). Percentage is not currently supported. This is a fixed value minimum profit and stop loss. Also note that the profit is taken as a conditional exit on a market order not a fixed limit. The actual profit taken will almost always be greater than the amount specified (due to the exit condition). The stop loss, on the other hand, is indeed a hard number which is executed by the TradingView broker simulator when the threshold is breached. On the study version, the stop is executed at the close of the bar.
Step 15. Return to step 3 and select a Trading Mode (Long, Short, BiDir, Ping Pong). If you are planning to trade bidirectionally its best to configure long first then short. Combine them with “BiDir” or “Ping Pong” after setting up both sides of the trade individually. The difference between “BiDir” and “Ping Pong” is that “Ping Pong” uses position reversal and can cut off opposing trades less than the specified minimum profit. As a result “Ping Pong” mode produces the greatest number of trades.
Step 16. Take a look at the chart. Trades should be showing along the markers plotted earlier.
Step 17. Make adjustments to the Vertex fields in Section 2 until the TradingView performance report is showing a profit. This includes the “Minimum Base To Base” fields. If a profit cannot be achieved move on to Step 18. Other adjustments may make a crucial difference.
Step 18. Improve the backtest profitability by adjusting the “Entry Net Change” and “Entry ROC” in Section 3 and 4.
Step 19. Enable the “Mandatory Snap” checkbox in Section 3 and 4 and adjust the “Snap Candle Delta” and “Snap Fractal Delta” in Section 2. This should reduce some chop producing unprofitable reversals.
Step 20. Increase the distance between opposing trades by adding an “Interleave Delta” in Sections 3 and 4. This is a floating point value which starts at 0.01 and typically does not exceed 2.0.
Step 21. Increase the distance between opposing trades even further by adding a “Decay Minimum Span” in Sections 3 and 4. This is an absolute value specified in the symbol’s quote currency (right side scale of the chart). This value is similar to the minimum profit and stop loss fields in Section 1.
Step 22. Improve the backtest profitability by adjusting the “Sparse Delta” in Section 3 and 4.
Step 23. Improve the backtest profitability by adjusting the “Chase Delta” in Section 3 and 4.
Step 24. Improve the backtest profitability by adjusting the “Adherence Delta” in Section 3 and 4. This field requires the “Adhere to Rising Trend” checkbox to be enabled.
Step 25. Try each checkbox in Section 3 and 4. See if it improves the backtest profitability. The “Caution Lackluster” checkbox only works when “Caution Mode” is enabled.
Step 26. Enable the reporting conditions in Section 5. Look for long runs of consecutive losses or high debt sequences. These are indications that your trading system cannot withstand sudden changes in market sentiment.
Step 27. Examine the chart and see that trades are being placed in accordance with your desired trading goals. This is an important step. If your desired model requires multiple trades per day then you should be seeing hundreds of trades on the chart. Alternatively, you may be looking to trade fewer steep peaks and deep valleys in which case you should see trades at major turning points. Don’t simply settle for what the backtest serves you. Work your configuration until the system aligns with your desired model. Try changing indicators and even intervals if you cannot reach your simulation goals. Generally speaking, the histogram and Candle indicators produce the most trades. The Macro indicator captures the tallest peaks and valleys.
Step 28. Apply the backtest settings to the study version and perform forward testing.
This script is open for beta testing. After successful beta test it will become a commercial application available by subscription only. I’ve invested quite a lot of time and effort into making this the best possible signal generator for all of the instruments I intend to trade. I certainly welcome any suggestions for improvements. Thank you all in advance.
One final note. I'm not a fan of having the Performance Overview (blue wedge) automatically show up at the end of the publish page since it could be misleading. On the EUR/USD backtest showing here I used a minimum profit of 65 pips, a stop of 120 pips, the candle indicator and a 5 pyramid max value. Also Mark Pyramid Levels (blue triangles) are enabled along with a 720 ROR Sample Period (red labels).
Depth Multiple Time FrameThe price always returns to the average !!!
An important separation of the price with respect to an average, indicates a depth and generally generates a reversion or correction in the trend. Depth detection is a simple and very powerful technique, it is widely used for scalping and pyramid operations, this indicator detects depth in 7 time frames, everything is configurable independently, simultaneous detection of depth in several time frames increases The chances of success in the operation. I personally like pyramidization and it is one of the tools I use to detect depth to average the price of my operations.
thumbs up!!
StrategyTOstudy LongGorila [CODE WITHOUT PYRAMIDING]This code is fofr you to change it and transform a strategy into a study and avoid pyramiding just by editting this lines
longcondition= buy_entry and buy_zone
shortcondition= sell_entry and sell_zone
like this
longcondition= 'YOUR CONDITION HERE'
shortcondition= 'YOUR CONDITION HERE'
and using your own conditions
This particular strategy is only as example and not for actual trading, this code is only to be edited an used to transform your strategies into studies to get alerts