MPF EMA Cross Strategy (8~13~21) by Market Pip FactoryThis script is for a complete strategy to win maximum profit on trades whilst keeping losses at a minimum, using sound risk management at no greater than 1.5%
The 3x EMA Strategy uses the following parameters for trade activation and closure.
1/ Daily Time Frame for trend confirmation
2/ 4 Hourly Time Frame for trend confirmation
3/ 1 Hourly Time Frame for trend confirmation AND trade execution
4/ 3x EMAs (Exponential Moving Averages)
* EMA#1 = 8 EMA (Red Color)
* EMA#2 = 13 EMA (Blue Color)
* EMA#3 = 21 EMA (Orange Color)
5/ Fanning of all 3x EMAs and CrossOver/CrossUnder for Trend Confirmation
6/ Price Action touching an 8 EMA for trade activation
7/ Price Action touching a 21 EMA for trade cancellation BEFORE activation
* For LONG trades: 8 EMA would be ABOVE 21 EMA
* For SHORT trades: 8 EMA would be BELOW 21 EMA
* For trade Cancellation, price action would touch the 21 EMA before trade is activated
* For trade Entry, price action would touch 8 EMA
Once trigger parameter is identified, entry is found by:
a) Price action touches 8 EMA (Candle must Close for confirmed Trade preparation)
b) Trade preparation can be cancelled before trade is activated if price action touches 21 EMA
c) Trailing Stop Loss can be used (optional) by counting back 5 candles from current candle
CLOSURE of a Trade is identified by:
e) 8 EMA crossing the 21 EMA, then close trade, no matter LONG or SHORT
f) Trail Stop Loss
IMPORTANT:
g) No more than ONE activated trade per EMA crossover
h) No more than ONE active trade per pair
NOTE: This strategy is to be used in conjunction with Cipher Twister (my other indicator) to reduce trades on
sideways price action and market trends for super high win ratio.
NOTE: Enabling of LONGs and SHORTs Via Cipher Twister is done by using the previous
green or red dot made. Additionally, when the trend changes, so do the dot's validity based
on being above or below the 0 centerline.
----------------------------
Strategy and Bot Logic
----------------------------
.....::: FOR SHORT TRADES ONLY :::.....
The Robot must use the following logic to enable and activate the SHORT trades:
Parameters:
$(crossunder)=8EMA,21EMA=Bearish $(crossover)=8EMA,21EMA=Bullish $entry=SELL STOP ORDER (Short)
$EMA#1 = 8 EMA (Red Color) $EMA#2 = 13 EMA (Blue Color) $EMA#3 = 21 EMA (Orange Color)
Strategy Logic:
1/ Check Daily Time Frame for trend confirmation if:
(look back up to 50 candles - find last cross of EMAs)
$(chart)=daily and trend=$(crossunder) then goto 2/ *Means: crossunder = ema21 > ema8
$(chart)=daily and trend=$(crossover) then stop (No trades) *Means: crossover = ema8 > ema21
NOTE: This function is switchable. 0=off and 1=on(active). Default = 1 (on)
2/ Check 4 Hourly Time Frame for trend confirmation if:
(look back up to 50 candles - find last cross of EMAs)
$(chart)=4H and trend=$(crossunder) then goto 3/ *Means: crossunder = ema21 > ema8
$(chart)=4H and trend=$(crossover) then stop (No trades) *Means: crossover = ema8 > ema21
NOTE: This function is switchable. 0=off and 1=on(active). Default = 1 (on)
3/ 1 Hourly Time Frame for trend confirmation AND trade execution if:
(look back up to 50 candles - find last cross of EMAs)
$(chart)=1H and trend=$(crossunder) then goto 4/ *Means: crossunder = ema21 > ema8
$(chart)=1H and trend=$(crossover) then stop (No trades) *Means: crossover = ema8 > ema21
4/ Trade preparation:
* if Next (subsequent) candle touches 8EMA, then set STOP LOSS and ENTRY
* $stoploss=3 pips ABOVE current candle HIGH
* $entry=3 pips BELOW current candle LOW
5/ Trade waiting (ONLY BEFORE entry is hit and trade activated):
* if price action touches 21 EMA then cancel trade and goto 1/
Note: Once trade is active this function does not apply !
6/ Trade Activation:
* if price activates/hits ENTRY price, then bot activates trade SHORTs market
7/ Optional Trailing stop:
* if active, then trailing stop 3 pips ABOVE previous HIGH of previous 5th candle
or * Move Stop Loss to Break Even after $X number of pips
NOTE: This means count back and apply accordingly to the 5th previous candle from current candle.
NOTE: This function is switchable. 0=off and 1=on(active). Default = 0 (off)
8/ Trade Close ~ Take Profit:
* Only TP when
$(chart)=1H and trend=$(crossover) then close trade ~ Or obviously if Stop Loss is hit if 7/ is activated.
----------END FOR SHORT TRADES LOGIC----------
.....::: FOR LONG TRADES ONLY :::.....
The Robot must use the following logic to enable and activate the LONG trades:
Parameters:
$(crossunder)=8EMA,21EMA=Bearish $(crossover)=8EMA,21EMA=Bullish $entry=BUY STOP ORDER (Long)
$EMA#1 = 8 EMA (Red Color) $EMA#2 = 13 EMA (Blue Color) $EMA#3 = 21 EMA (Orange Color)
Strategy Logic:
1/ Check Daily Time Frame for trend confirmation if:
(look back up to 50 candles - find last cross of EMAs)
$(chart)=daily and trend=$(crossover) then goto 2/ *Means: crossover = ema8 > ema21
$(chart)=daily and trend=$(crossunder) then stop (No trades) *Means: crossunder = ema21 > ema8
NOTE: This function is switchable. 0=off and 1=on(active). Default = 1 (on)
2/ Check 4 Hourly Time Frame for trend confirmation if:
(look back up to 50 candles - find last cross of EMAs)
$(chart)=4H and trend=$(crossover) then goto 3/ *Means: crossover = ema8 > ema21
$(chart)=4H and trend=$(crossunder) then stop (No trades) *Means: crossunder = ema21 > ema8
NOTE: This function is switchable. 0=off and 1=on(active). Default = 1 (on)
3/ 1 Hourly Time Frame for trend confirmation AND trade execution if:
(look back up to 50 candles - find last cross of EMAs)
$(chart)=1H and trend=$(crossover) then goto 4/ *Means: crossover = ema8 > ema21
$(chart)=1H and trend=$(crossunder) then stop (No trades) *Means: crossunder = ema21 > ema8
4/ Trade preparation:
* if Next (subsequent) candle touches 8EMA, then set STOP LOSS and ENTRY
* $stoploss=3 pips BELOW current candle LOW
* $entry=3 pips ABOVE current candle HIGH
5/ Trade waiting (ONLY BEFORE entry is hit and trade activated):
* if price action touches 21 EMA then cancel trade and goto 1/
Note: Once trade is active this function does not apply !
6/ Trade Activation:
* if price activates/hits ENTRY price, then bot activates trade LONGs market
7/ Optional Trailing stop:
* if active, then trailing stop 3 pips BELOW previous LOW of previous 5th candle
or * Move Stop Loss to Break Even after $X number of pips
NOTE: This means count back and apply accordingly to the 5th previous candle from current candle.
NOTE: This function is switchable. 0=off and 1=on(active). Default = 0 (off)
8/ Trade Close ~ Take Profit:
* Only TP when
$(chart)=1H and trend=$(crossunder) then close trade ~ Or obviously if Stop Loss is hit if 7/ is activated.
----------END FOR LONG TRADES LOGIC----------
IMPORTANT:
* If an existing trade is already open for that same pair, & price action touches 8EMA, do NOT open a new trade..
* bot must continuously check if a trade is currently open on the pair that triggers
* New trades are to be only opened if there is no active trade opened on current pair.
* Only 1 trade per pair rule !
* 5 simultaneous open trades (not same pairs) default = 5 but value can be changed accordingly.
* Maximum risk management must not exceed 1.5% on lot size
*** Some features are not yet available autoated, they will be added in due course in subsequent version updates ***
Search in scripts for "bot"
Dual Fibonacci Zone & Ranged Vol DCA Strategy - R3c0nTraderWhat does this do?
This is for educational purposes and allows one to backtest two Fibonacci Zones simultaneously. This also includes an option for Ranged Volume as a parameter.
Pre-requisites:
First off, this is a Long only strategy as I wrote it with DCA in mind. It cannot be used for shorting. Shorting defeats the purpose of a DCA bot which has a goal that is Long a position not Short a position. If you want to short, there are plenty of free scripts out there that do this.
You must have some base knowledge or experience with Fibonacci trading, understanding what is ADX, +DI (and -DI), etc.
You can use this script without a 3Commas account and see how 3Commas DCA Bot would perform. However, I highly recommend inexperienced uses get a free account and going through the tutorials, FAQ's and knowledgebase. This would give you a base understanding of the settings you will see in this strategy and why you will need to know them. Only then should you try testing this strategy with a paper bot.
Background
After I had created and released "Fibonacci Zone DCA Strategy", I began expanding and testing other ideas.
The first idea was to add Ranged Volume to the Fibonacci Zone DCA strategy which I wanted for providing further confirmation before entering a trade. The second idea was to add a second Fibonacci Zone that was just as configurable as the first Fibonacci Zone. I managed to add both and they can be easily enabled or disabled via the strategy settings menu.
Things Got Real Interesting
Things got real interesting when I started testing strategies with two Fibonacci zones. Here's a quick list of what I found I was able to do:
Mix and match exit strategies. I could set the Fib-1 zone strategy to exit with a take profit % and separately set the Fib-2 zone strategy to exit when the price crosses the top-high fib border
Trade the trend. A common phrase amongst traders is "the Trend is your friend" and with the help of an additional Fib Zone, I was able to trade the trend more often by using two different Fib Zone strategies which if configured properly can shorten time to re-deploy capital, increase number of closed trades, and in some cases increase net profit.
Trade both bull market uptrends and bear market downtrends in the same strategy. I found I could configure one Fib Zone strategy to be really good in uptrends and another Fib Zone strategy to be really good in downtrends. In some cases, with both Fib Zone strategies enabled together in a single strategy I got better results than if the strategies were backtested separately.
There are many other trade strategies I am finding with this. One could be to trade a convergence or divergence of the two different Fib Zones. This could possibly be achieved by setting one strategy to have different Fibonacci length.
Credits:
Thank you "EvoCrypto" for granting me permission to use "Ranged Volume" to create this strategy
Thank you "eykpunter" for granting me permission to use "Fibonacci Zones" to create this strategy
Thank you "junyou0424" for granting me permission to use "DCA Bot with SuperTrend Emulator" which I used for adding bot inputs, calculations, and strategy
Fibonacci Zone DCA Strategy - R3c0nTraderCredits:
Thank you "eykpunter" for granting me permission to use "Fibonacci Zones" to create this strategy
Thank you "junyou0424" for granting me permission to use "DCA Bot with SuperTrend Emulator" which I used for adding bot inputs, calculations, and strategy
Pre-requisites:
You can use this script without a 3Commas account and see how 3Commas DCA Bot would perform. However, I highly recommend signing up for their free account, going through their training, and testing this strategy with a paper bot. This would give you a base understanding of the settings you will see in this strategy and why you will need to know them.
What can this do?
First off, this is a Long only strategy as I wrote it with DCA in mind. It cannot be used for shorting. Shorting defeats the purpose of a DCA bot which has a goal that is Long a position not Short a position. If you want to short, there are plenty of free scripts out there that do this.
I created this script out of curiosity and I wanted to see how a strategy based on “Fibonacci” levels would work with a 3Commas DCA bot. I came across "eykpunter’s" "Fibonacci Zones" study and in TradingView and I found it to be a very interesting concept. The "Fib Zones" in his study are basically a "Donchian Channel" of 4 Fibonacci lines. These are the High @ 0.236, Center High @ 0.382, Center Low @ 0.618, and Low @ 0.764.
The Fib Zones in this strategy can be used as conditions to open a trade as well as closing a trade. There is also the option to close a trade based on a Target Take Profit (%).
Advanced Fibonacci trading is also supported by specifying additional parameters for Trade Entry and Exit.
For example, for order entry, you can increase the minimum trend strength to open an order via the "minimum ADX value" option. You can also further limit order entry by selecting the option to "Only open trades on bullish +DI" (Positive Directional Index).
Or you can play the contrarian. For example, I would look for "buying the dip" opportunities by doing the following under "Trade Entry Settings":
Set the "Min ADX value to open trade" to zero
Set the option "Open a trade when the price moves" to "1-To the bottom of Downtrend Fib zone" or "2-Higher than the top of the Downtrend Fib zone"
Uncheck option "Only open trades on bullish +DI"
Set the 'Min ADX value to open trade' to Zero
Set the 'Max +DI value to open trade' to a value between 10-20.
For Trade Exit settings, I can use a "Target Take Profit (%)" or one of the High Fib levels to close the trade.
Here's an example result when using a Contrarian-Fibonacci-Zone-DCA strategy:
Explanation of Chart lines and colors on chart
Six Options for Entering a Fibonacci Trade
Open a trade when the price moves:
1-To the bottom of Downtrend Fib zone
2-Higher than the top of the Downtrend Fib zone
3-Higher than the bottom of Ranging Fib Zone
4-Higher than the top of Ranging Fib Zone
5-Higher than the bottom of Uptrend Fib Zone
6-To the top of Uptrend Fib Zone
Three Options for Exiting a Fibonacci Trade
Take profit using:
"Target Take Profit (%)"
"High Fibonacci Border-1"
"High Fibonacci Border-2"
Backtesting & Trading Engine [PineCoders]The PineCoders Backtesting and Trading Engine is a sophisticated framework with hybrid code that can run as a study to generate alerts for automated or discretionary trading while simultaneously providing backtest results. It can also easily be converted to a TradingView strategy in order to run TV backtesting. The Engine comes with many built-in strats for entries, filters, stops and exits, but you can also add you own.
If, like any self-respecting strategy modeler should, you spend a reasonable amount of time constantly researching new strategies and tinkering, our hope is that the Engine will become your inseparable go-to tool to test the validity of your creations, as once your tests are conclusive, you will be able to run this code as a study to generate the alerts required to put it in real-world use, whether for discretionary trading or to interface with an execution bot/app. You may also find the backtesting results the Engine produces in study mode enough for your needs and spend most of your time there, only occasionally converting to strategy mode in order to backtest using TV backtesting.
As you will quickly grasp when you bring up this script’s Settings, this is a complex tool. While you will be able to see results very quickly by just putting it on a chart and using its built-in strategies, in order to reap the full benefits of the PineCoders Engine, you will need to invest the time required to understand the subtleties involved in putting all its potential into play.
Disclaimer: use the Engine at your own risk.
Before we delve in more detail, here’s a bird’s eye view of the Engine’s features:
More than 40 built-in strategies,
Customizable components,
Coupling with your own external indicator,
Simple conversion from Study to Strategy modes,
Post-Exit analysis to search for alternate trade outcomes,
Use of the Data Window to show detailed bar by bar trade information and global statistics, including some not provided by TV backtesting,
Plotting of reminders and generation of alerts on in-trade events.
By combining your own strats to the built-in strats supplied with the Engine, and then tuning the numerous options and parameters in the Inputs dialog box, you will be able to play what-if scenarios from an infinite number of permutations.
USE CASES
You have written an indicator that provides an entry strat but it’s missing other components like a filter and a stop strategy. You add a plot in your indicator that respects the Engine’s External Signal Protocol, connect it to the Engine by simply selecting your indicator’s plot name in the Engine’s Settings/Inputs and then run tests on different combinations of entry stops, in-trade stops and profit taking strats to find out which one produces the best results with your entry strat.
You are building a complex strategy that you will want to run as an indicator generating alerts to be sent to a third-party execution bot. You insert your code in the Engine’s modules and leverage its trade management code to quickly move your strategy into production.
You have many different filters and want to explore results using them separately or in combination. Integrate the filter code in the Engine and run through different permutations or hook up your filtering through the external input and control your filter combos from your indicator.
You are tweaking the parameters of your entry, filter or stop strat. You integrate it in the Engine and evaluate its performance using the Engine’s statistics.
You always wondered what results a random entry strat would yield on your markets. You use the Engine’s built-in random entry strat and test it using different combinations of filters, stop and exit strats.
You want to evaluate the impact of fees and slippage on your strategy. You use the Engine’s inputs to play with different values and get immediate feedback in the detailed numbers provided in the Data Window.
You just want to inspect the individual trades your strategy generates. You include it in the Engine and then inspect trades visually on your charts, looking at the numbers in the Data Window as you move your cursor around.
You have never written a production-grade strategy and you want to learn how. Inspect the code in the Engine; you will find essential components typical of what is being used in actual trading systems.
You have run your system for a while and have compiled actual slippage information and your broker/exchange has updated his fees schedule. You enter the information in the Engine and run it on your markets to see the impact this has on your results.
FEATURES
Before going into the detail of the Inputs and the Data Window numbers, here’s a more detailed overview of the Engine’s features.
Built-in strats
The engine comes with more than 40 pre-coded strategies for the following standard system components:
Entries,
Filters,
Entry stops,
2 stage in-trade stops with kick-in rules,
Pyramiding rules,
Hard exits.
While some of the filter and stop strats provided may be useful in production-quality systems, you will not devise crazy profit-generating systems using only the entry strats supplied; that part is still up to you, as will be finding the elusive combination of components that makes winning systems. The Engine will, however, provide you with a solid foundation where all the trade management nitty-gritty is handled for you. By binding your custom strats to the Engine, you will be able to build reliable systems of the best quality currently allowed on the TV platform.
On-chart trade information
As you move over the bars in a trade, you will see trade numbers in the Data Window change at each bar. The engine calculates the P&L at every bar, including slippage and fees that would be incurred were the trade exited at that bar’s close. If the trade includes pyramided entries, those will be taken into account as well, although for those, final fees and slippage are only calculated at the trade’s exit.
You can also see on-chart markers for the entry level, stop positions, in-trade special events and entries/exits (you will want to disable these when using the Engine in strategy mode to see TV backtesting results).
Customization
You can couple your own strats to the Engine in two ways:
1. By inserting your own code in the Engine’s different modules. The modular design should enable you to do so with minimal effort by following the instructions in the code.
2. By linking an external indicator to the engine. After making the proper selections in the engine’s Settings and providing values respecting the engine’s protocol, your external indicator can, when the Engine is used in Indicator mode only:
Tell the engine when to enter long or short trades, but let the engine’s in-trade stop and exit strats manage the exits,
Signal both entries and exits,
Provide an entry stop along with your entry signal,
Filter other entry signals generated by any of the engine’s entry strats.
Conversion from strategy to study
TradingView strategies are required to backtest using the TradingView backtesting feature, but if you want to generate alerts with your script, whether for automated trading or just to trigger alerts that you will use in discretionary trading, your code has to run as a study since, for the time being, strategies can’t generate alerts. From hereon we will use indicator as a synonym for study.
Unless you want to maintain two code bases, you will need hybrid code that easily flips between strategy and indicator modes, and your code will need to restrict its use of strategy() calls and their arguments if it’s going to be able to run both as an indicator and a strategy using the same trade logic. That’s one of the benefits of using this Engine. Once you will have entered your own strats in the Engine, it will be a matter of commenting/uncommenting only four lines of code to flip between indicator and strategy modes in a matter of seconds.
Additionally, even when running in Indicator mode, the Engine will still provide you with precious numbers on your individual trades and global results, some of which are not available with normal TradingView backtesting.
Post-Exit Analysis for alternate outcomes (PEA)
While typical backtesting shows results of trade outcomes, PEA focuses on what could have happened after the exit. The intention is to help traders get an idea of the opportunity/risk in the bars following the trade in order to evaluate if their exit strategies are too aggressive or conservative.
After a trade is exited, the Engine’s PEA module continues analyzing outcomes for a user-defined quantity of bars. It identifies the maximum opportunity and risk available in that space, and calculates the drawdown required to reach the highest opportunity level post-exit, while recording the number of bars to that point.
Typically, if you can’t find opportunity greater than 1X past your trade using a few different reasonable lengths of PEA, your strategy is doing pretty good at capturing opportunity. Remember that 100% of opportunity is never capturable. If, however, PEA was finding post-trade maximum opportunity of 3 or 4X with average drawdowns of 0.3 to those areas, this could be a clue revealing your system is exiting trades prematurely. To analyze PEA numbers, you can uncomment complete sets of plots in the Plot module to reveal detailed global and individual PEA numbers.
Statistics
The Engine provides stats on your trades that TV backtesting does not provide, such as:
Average Profitability Per Trade (APPT), aka statistical expectancy, a crucial value.
APPT per bar,
Average stop size,
Traded volume .
It also shows you on a trade-by-trade basis, on-going individual trade results and data.
In-trade events
In-trade events can plot reminders and trigger alerts when they occur. The built-in events are:
Price approaching stop,
Possible tops/bottoms,
Large stop movement (for discretionary trading where stop is moved manually),
Large price movements.
Slippage and Fees
Even when running in indicator mode, the Engine allows for slippage and fees to be included in the logic and test results.
Alerts
The alert creation mechanism allows you to configure alerts on any combination of the normal or pyramided entries, exits and in-trade events.
Backtesting results
A few words on the numbers calculated in the Engine. Priority is given to numbers not shown in TV backtesting, as you can readily convert the script to a strategy if you need them.
We have chosen to focus on numbers expressing results relative to X (the trade’s risk) rather than in absolute currency numbers or in other more conventional but less useful ways. For example, most of the individual trade results are not shown in percentages, as this unit of measure is often less meaningful than those expressed in units of risk (X). A trade that closes with a +25% result, for example, is a poor outcome if it was entered with a -50% stop. Expressed in X, this trade’s P&L becomes 0.5, which provides much better insight into the trade’s outcome. A trade that closes with a P&L of +2X has earned twice the risk incurred upon entry, which would represent a pre-trade risk:reward ratio of 2.
The way to go about it when you think in X’s and that you adopt the sound risk management policy to risk a fixed percentage of your account on each trade is to equate a currency value to a unit of X. E.g. your account is 10K USD and you decide you will risk a maximum of 1% of it on each trade. That means your unit of X for each trade is worth 100 USD. If your APPT is 2X, this means every time you risk 100 USD in a trade, you can expect to make, on average, 200 USD.
By presenting results this way, we hope that the Engine’s statistics will appeal to those cognisant of sound risk management strategies, while gently leading traders who aren’t, towards them.
We trade to turn in tangible profits of course, so at some point currency must come into play. Accordingly, some values such as equity, P&L, slippage and fees are expressed in currency.
Many of the usual numbers shown in TV backtests are nonetheless available, but they have been commented out in the Engine’s Plot module.
Position sizing and risk management
All good system designers understand that optimal risk management is at the very heart of all winning strategies. The risk in a trade is defined by the fraction of current equity represented by the amplitude of the stop, so in order to manage risk optimally on each trade, position size should adjust to the stop’s amplitude. Systems that enter trades with a fixed stop amplitude can get away with calculating position size as a fixed percentage of current equity. In the context of a test run where equity varies, what represents a fixed amount of risk translates into different currency values.
Dynamically adjusting position size throughout a system’s life is optimal in many ways. First, as position sizing will vary with current equity, it reproduces a behavioral pattern common to experienced traders, who will dial down risk when confronted to poor performance and increase it when performance improves. Second, limiting risk confers more predictability to statistical test results. Third, position sizing isn’t just about managing risk, it’s also about maximizing opportunity. By using the maximum leverage (no reference to trading on margin here) into the trade that your risk management strategy allows, a dynamic position size allows you to capture maximal opportunity.
To calculate position sizes using the fixed risk method, we use the following formula: Position = Account * MaxRisk% / Stop% [, which calculates a position size taking into account the trade’s entry stop so that if the trade is stopped out, 100 USD will be lost. For someone who manages risk this way, common instructions to invest a certain percentage of your account in a position are simply worthless, as they do not take into account the risk incurred in the trade.
The Engine lets you select either the fixed risk or fixed percentage of equity position sizing methods. The closest thing to dynamic position sizing that can currently be done with alerts is to use a bot that allows syntax to specify position size as a percentage of equity which, while being dynamic in the sense that it will adapt to current equity when the trade is entered, does not allow us to modulate position size using the stop’s amplitude. Changes to alerts are on the way which should solve this problem.
In order for you to simulate performance with the constraint of fixed position sizing, the Engine also offers a third, less preferable option, where position size is defined as a fixed percentage of initial capital so that it is constant throughout the test and will thus represent a varying proportion of current equity.
Let’s recap. The three position sizing methods the Engine offers are:
1. By specifying the maximum percentage of risk to incur on your remaining equity, so the Engine will dynamically adjust position size for each trade so that, combining the stop’s amplitude with position size will yield a fixed percentage of risk incurred on current equity,
2. By specifying a fixed percentage of remaining equity. Note that unless your system has a fixed stop at entry, this method will not provide maximal risk control, as risk will vary with the amplitude of the stop for every trade. This method, as the first, does however have the advantage of automatically adjusting position size to equity. It is the Engine’s default method because it has an equivalent in TV backtesting, so when flipping between indicator and strategy mode, test results will more or less correspond.
3. By specifying a fixed percentage of the Initial Capital. While this is the least preferable method, it nonetheless reflects the reality confronted by most system designers on TradingView today. In this case, risk varies both because the fixed position size in initial capital currency represents a varying percentage of remaining equity, and because the trade’s stop amplitude may vary, adding another variability vector to risk.
Note that the Engine cannot display equity results for strategies entering trades for a fixed amount of shares/contracts at a variable price.
SETTINGS/INPUTS
Because the initial text first published with a script cannot be edited later and because there are just too many options, the Engine’s Inputs will not be covered in minute detail, as they will most certainly evolve. We will go over them with broad strokes; you should be able to figure the rest out. If you have questions, just ask them here or in the PineCoders Telegram group.
Display
The display header’s checkbox does nothing.
For the moment, only one exit strategy uses a take profit level, so only that one will show information when checking “Show Take Profit Level”.
Entries
You can activate two simultaneous entry strats, each selected from the same set of strats contained in the Engine. If you select two and they fire simultaneously, the main strat’s signal will be used.
The random strat in each list uses a different seed, so you will get different results from each.
The “Filter transitions” and “Filter states” strats delegate signal generation to the selected filter(s). “Filter transitions” signals will only fire when the filter transitions into bull/bear state, so after a trade is stopped out, the next entry may take some time to trigger if the filter’s state does not change quickly. When you choose “Filter states”, then a new trade will be entered immediately after an exit in the direction the filter allows.
If you select “External Indicator”, your indicator will need to generate a +2/-2 (or a positive/negative stop value) to enter a long/short position, providing the selected filters allow for it. If you wish to use the Engine’s capacity to also derive the entry stop level from your indicator’s signal, then you must explicitly choose this option in the Entry Stops section.
Filters
You can activate as many filters as you wish; they are additive. The “Maximum stop allowed on entry” is an important component of proper risk management. If your system has an average 3% stop size and you need to trade using fixed position sizes because of alert/execution bot limitations, you must use this filter because if your system was to enter a trade with a 15% stop, that trade would incur 5 times the normal risk, and its result would account for an abnormally high proportion in your system’s performance.
Remember that any filter can also be used as an entry signal, either when it changes states, or whenever no trade is active and the filter is in a bull or bear mode.
Entry Stops
An entry stop must be selected in the Engine, as it requires a stop level before the in-trade stop is calculated. Until the selected in-trade stop strat generates a stop that comes closer to price than the entry stop (or respects another one of the in-trade stops kick in strats), the entry stop level is used.
It is here that you must select “External Indicator” if your indicator supplies a +price/-price value to be used as the entry stop. A +price is expected for a long entry and a -price value will enter a short with a stop at price. Note that the price is the absolute price, not an offset to the current price level.
In-Trade Stops
The Engine comes with many built-in in-trade stop strats. Note that some of them share the “Length” and “Multiple” field, so when you swap between them, be sure that the length and multiple in use correspond to what you want for that stop strat. Suggested defaults appear with the name of each strat in the dropdown.
In addition to the strat you wish to use, you must also determine when it kicks in to replace the initial entry’s stop, which is determined using different strats. For strats where you can define a positive or negative multiple of X, percentage or fixed value for a kick-in strat, a positive value is above the trade’s entry fill and a negative one below. A value of zero represents breakeven.
Pyramiding
What you specify in this section are the rules that allow pyramiding to happen. By themselves, these rules will not generate pyramiding entries. For those to happen, entry signals must be issued by one of the active entry strats, and conform to the pyramiding rules which act as a filter for them. The “Filter must allow entry” selection must be chosen if you want the usual system’s filters to act as additional filtering criteria for your pyramided entries.
Hard Exits
You can choose from a variety of hard exit strats. Hard exits are exit strategies which signal trade exits on specific events, as opposed to price breaching a stop level in In-Trade Stops strategies. They are self-explanatory. The last one labelled When Take Profit Level (multiple of X) is reached is the only one that uses a level, but contrary to stops, it is above price and while it is relative because it is expressed as a multiple of X, it does not move during the trade. This is the level called Take Profit that is show when the “Show Take Profit Level” checkbox is checked in the Display section.
While stops focus on managing risk, hard exit strategies try to put the emphasis on capturing opportunity.
Slippage
You can define it as a percentage or a fixed value, with different settings for entries and exits. The entry and exit markers on the chart show the impact of slippage on the entry price (the fill).
Fees
Fees, whether expressed as a percentage of position size in and out of the trade or as a fixed value per in and out, are in the same units of currency as the capital defined in the Position Sizing section. Fees being deducted from your Capital, they do not have an impact on the chart marker positions.
In-Trade Events
These events will only trigger during trades. They can be helpful to act as reminders for traders using the Engine as assistance to discretionary trading.
Post-Exit Analysis
It is normally on. Some of its results will show in the Global Numbers section of the Data Window. Only a few of the statistics generated are shown; many more are available, but commented out in the Plot module.
Date Range Filtering
Note that you don’t have to change the dates to enable/diable filtering. When you are done with a specific date range, just uncheck “Date Range Filtering” to disable date filtering.
Alert Triggers
Each selection corresponds to one condition. Conditions can be combined into a single alert as you please. Just be sure you have selected the ones you want to trigger the alert before you create the alert. For example, if you trade in both directions and you want a single alert to trigger on both types of exits, you must select both “Long Exit” and “Short Exit” before creating your alert.
Once the alert is triggered, these settings no longer have relevance as they have been saved with the alert.
When viewing charts where an alert has just triggered, if your alert triggers on more than one condition, you will need the appropriate markers active on your chart to figure out which condition triggered the alert, since plotting of markers is independent of alert management.
Position sizing
You have 3 options to determine position size:
1. Proportional to Stop -> Variable, with a cap on size.
2. Percentage of equity -> Variable.
3. Percentage of Initial Capital -> Fixed.
External Indicator
This is where you connect your indicator’s plot that will generate the signals the Engine will act upon. Remember this only works in Indicator mode.
DATA WINDOW INFORMATION
The top part of the window contains global numbers while the individual trade information appears in the bottom part. The different types of units used to express values are:
curr: denotes the currency used in the Position Sizing section of Inputs for the Initial Capital value.
quote: denotes quote currency, i.e. the value the instrument is expressed in, or the right side of the market pair (USD in EURUSD ).
X: the stop’s amplitude, itself expressed in quote currency, which we use to express a trade’s P&L, so that a trade with P&L=2X has made twice the stop’s amplitude in profit. This is sometimes referred to as R, since it represents one unit of risk. It is also the unit of measure used in the APPT, which denotes expected reward per unit of risk.
X%: is also the stop’s amplitude, but expressed as a percentage of the Entry Fill.
The numbers appearing in the Data Window are all prefixed:
“ALL:” the number is the average for all first entries and pyramided entries.
”1ST:” the number is for first entries only.
”PYR:” the number is for pyramided entries only.
”PEA:” the number is for Post-Exit Analyses
Global Numbers
Numbers in this section represent the results of all trades up to the cursor on the chart.
Average Profitability Per Trade (X): This value is the most important gauge of your strat’s worthiness. It represents the returns that can be expected from your strat for each unit of risk incurred. E.g.: your APPT is 2.0, thus for every unit of currency you invest in a trade, you can on average expect to obtain 2 after the trade. APPT is also referred to as “statistical expectancy”. If it is negative, your strategy is losing, even if your win rate is very good (it means your winning trades aren’t winning enough, or your losing trades lose too much, or both). Its counterpart in currency is also shown, as is the APPT/bar, which can be a useful gauge in deciding between rivalling systems.
Profit Factor: Gross of winning trades/Gross of losing trades. Strategy is profitable when >1. Not as useful as the APPT because it doesn’t take into account the win rate and the average win/loss per trade. It is calculated from the total winning/losing results of this particular backtest and has less predictive value than the APPT. A good profit factor together with a poor APPT means you just found a chart where your system outperformed. Relying too much on the profit factor is a bit like a poker player who would think going all in with two’s against aces is optimal because he just won a hand that way.
Win Rate: Percentage of winning trades out of all trades. Taken alone, it doesn’t have much to do with strategy profitability. You can have a win rate of 99% but if that one trade in 100 ruins you because of poor risk management, 99% doesn’t look so good anymore. This number speaks more of the system’s profile than its worthiness. Still, it can be useful to gauge if the system fits your personality. It can also be useful to traders intending to sell their systems, as low win rate systems are more difficult to sell and require more handholding of worried customers.
Equity (curr): This the sum of initial capital and the P&L of your system’s trades, including fees and slippage.
Return on Capital is the equivalent of TV’s Net Profit figure, i.e. the variation on your initial capital.
Maximum drawdown is the maximal drawdown from the highest equity point until the drop . There is also a close to close (meaning it doesn’t take into account in-trade variations) maximum drawdown value commented out in the code.
The next values are self-explanatory, until:
PYR: Avg Profitability Per Entry (X): this is the APPT for all pyramided entries.
PEA: Avg Max Opp . Available (X): the average maximal opportunity found in the Post-Exit Analyses.
PEA: Avg Drawdown to Max Opp . (X): this represents the maximum drawdown (incurred from the close at the beginning of the PEA analysis) required to reach the maximal opportunity point.
Trade Information
Numbers in this section concern only the current trade under the cursor. Most of them are self-explanatory. Use the description’s prefix to determine what the values applies to.
PYR: Avg Profitability Per Entry (X): While this value includes the impact of all current pyramided entries (and only those) and updates when you move your cursor around, P&L only reflects fees at the trade’s last bar.
PEA: Max Opp . Available (X): It’s the most profitable close reached post-trade, measured from the trade’s Exit Fill, expressed in the X value of the trade the PEA follows.
PEA: Drawdown to Max Opp . (X): This is the maximum drawdown from the trade’s Exit Fill that needs to be sustained in order to reach the maximum opportunity point, also expressed in X. Note that PEA numbers do not include slippage and fees.
EXTERNAL SIGNAL PROTOCOL
Only one external indicator can be connected to a script; in order to leverage its use to the fullest, the engine provides options to use it as either an entry signal, an entry/exit signal or a filter. When used as an entry signal, you can also use the signal to provide the entry’s stop. Here’s how this works:
For filter state: supply +1 for bull (long entries allowed), -1 for bear (short entries allowed).
For entry signals: supply +2 for long, -2 for short.
For exit signals: supply +3 for exit from long, -3 for exit from short.
To send an entry stop level with an entry signal: Send positive stop level for long entry (e.g. 103.33 to enter a long with a stop at 103.33), negative stop level for short entry (e.g. -103.33 to enter a short with a stop at 103.33). If you use this feature, your indicator will have to check for exact stop levels of 1.0, 2.0 or 3.0 and their negative counterparts, and fudge them with a tick in order to avoid confusion with other signals in the protocol.
Remember that mere generation of the values by your indicator will have no effect until you explicitly allow their use in the appropriate sections of the Engine’s Settings/Inputs.
An example of a script issuing a signal for the Engine is published by PineCoders.
RECOMMENDATIONS TO ASPIRING SYSTEM DESIGNERS
Stick to higher timeframes. On progressively lower timeframes, margins decrease and fees and slippage take a proportionally larger portion of profits, to the point where they can very easily turn a profitable strategy into a losing one. Additionally, your margin for error shrinks as the equilibrium of your system’s profitability becomes more fragile with the tight numbers involved in the shorter time frames. Avoid <1H time frames.
Know and calculate fees and slippage. To avoid market shock, backtest using conservative fees and slippage parameters. Systems rarely show unexpectedly good returns when they are confronted to the markets, so put all chances on your side by being outrageously conservative—or a the very least, realistic. Test results that do not include fees and slippage are worthless. Slippage is there for a reason, and that’s because our interventions in the market change the market. It is easier to find alpha in illiquid markets such as cryptos because not many large players participate in them. If your backtesting results are based on moving large positions and you don’t also add the inevitable slippage that will occur when you enter/exit thin markets, your backtesting will produce unrealistic results. Even if you do include large slippage in your settings, the Engine can only do so much as it will not let slippage push fills past the high or low of the entry bar, but the gap may be much larger in illiquid markets.
Never test and optimize your system on the same dataset , as that is the perfect recipe for overfitting or data dredging, which is trying to find one precise set of rules/parameters that works only on one dataset. These setups are the most fragile and often get destroyed when they meet the real world.
Try to find datasets yielding more than 100 trades. Less than that and results are not as reliable.
Consider all backtesting results with suspicion. If you never entertained sceptic tendencies, now is the time to begin. If your backtest results look really good, assume they are flawed, either because of your methodology, the data you’re using or the software doing the testing. Always assume the worse and learn proper backtesting techniques such as monte carlo simulations and walk forward analysis to avoid the traps and biases that unchecked greed will set for you. If you are not familiar with concepts such as survivor bias, lookahead bias and confirmation bias, learn about them.
Stick to simple bars or candles when designing systems. Other types of bars often do not yield reliable results, whether by design (Heikin Ashi) or because of the way they are implemented on TV (Renko bars).
Know that you don’t know and use that knowledge to learn more about systems and how to properly test them, about your biases, and about yourself.
Manage risk first , then capture opportunity.
Respect the inherent uncertainty of the future. Cleanse yourself of the sad arrogance and unchecked greed common to newcomers to trading. Strive for rationality. Respect the fact that while backtest results may look promising, there is no guarantee they will repeat in the future (there is actually a high probability they won’t!), because the future is fundamentally unknowable. If you develop a system that looks promising, don’t oversell it to others whose greed may lead them to entertain unreasonable expectations.
Have a plan. Understand what king of trading system you are trying to build. Have a clear picture or where entries, exits and other important levels will be in the sort of trade you are trying to create with your system. This stated direction will help you discard more efficiently many of the inevitably useless ideas that will pop up during system design.
Be wary of complexity. Experienced systems engineers understand how rapidly complexity builds when you assemble components together—however simple each one may be. The more complex your system, the more difficult it will be to manage.
Play! . Allow yourself time to play around when you design your systems. While much comes about from working with a purpose, great ideas sometimes come out of just trying things with no set goal, when you are stuck and don’t know how to move ahead. Have fun!
@LucF
NOTES
While the engine’s code can supply multiple consecutive entries of longs or shorts in order to scale positions (pyramid), all exits currently assume the execution bot will exit the totality of the position. No partial exits are currently possible with the Engine.
Because the Engine is literally crippled by the limitations on the number of plots a script can output on TV; it can only show a fraction of all the information it calculates in the Data Window. You will find in the Plot Module vast amounts of commented out lines that you can activate if you also disable an equivalent number of other plots. This may be useful to explore certain characteristics of your system in more detail.
When backtesting using the TV backtesting feature, you will need to provide the strategy parameters you wish to use through either Settings/Properties or by changing the default values in the code’s header. These values are defined in variables and used not only in the strategy() statement, but also as defaults in the Engine’s relevant Inputs.
If you want to test using pyramiding, then both the strategy’s Setting/Properties and the Engine’s Settings/Inputs need to allow pyramiding.
If you find any bugs in the Engine, please let us know.
THANKS
To @glaz for allowing the use of his unpublished MA Squize in the filters.
To @everget for his Chandelier stop code, which is also used as a filter in the Engine.
To @RicardoSantos for his pseudo-random generator, and because it’s from him that I first read in the Pine chat about the idea of using an external indicator as input into another. In the PineCoders group, @theheirophant then mentioned the idea of using it as a buy/sell signal and @simpelyfe showed a piece of code implementing the idea. That’s the tortuous story behind the use of the external indicator in the Engine.
To @admin for the Volatility stop’s original code and for the donchian function lifted from Ichimoku .
To @BobHoward21 for the v3 version of Volatility Stop .
To @scarf and @midtownsk8rguy for the color tuning.
To many other scripters who provided encouragement and suggestions for improvement during the long process of writing and testing this piece of code.
To J. Welles Wilder Jr. for ATR, used extensively throughout the Engine.
To TradingView for graciously making an account available to PineCoders.
And finally, to all fellow PineCoders for the constant intellectual stimulation; it is a privilege to share ideas with you all. The Engine is for all TradingView PineCoders, of course—but especially for you.
Look first. Then leap.
[3Commas] Signal BuilderSignal Builder is a tool designed to help traders create custom buy and sell signals by combining multiple technical indicators. Its flexibility allows traders to set conditions based on their specific strategy, whether they’re into scalping, swing trading, or long-term investing. Additionally, its integration with 3Commas bots makes it a powerful choice for those looking to automate their trades, though it’s also ideal for traders who prefer receiving alerts and making manual decisions.
🔵 How does Signal Builder work?
Signal Builder allows users to define custom conditions using popular technical indicators, which, when met, generate clear buy or sell signals. These signals can be used to trigger TradingView alerts, ensuring that you never miss a market opportunity. Additionally, all conditions are evaluated using "AND" logic, meaning signals are only activated when all user-defined conditions are met. This increases precision and helps avoid false signals.
🔵 Available indicators and recommended settings:
Signal Builder provides access to a wide range of technical indicators, each customizable to popular settings that maximize effectiveness:
RSI (Relative Strength Index): An oscillator that measures the relative strength of price over a specific period. Traders typically configure it with 14 periods, using levels of 30 (oversold) and 70 (overbought) to identify potential reversals.
MACD (Moving Average Convergence Divergence): A key indicator tracking the crossover between two moving averages. Common settings include 12 and 26 periods for the moving averages, with a 9-period signal line to detect trend changes.
Ultimate Oscillator: Combines three different time frames to offer a comprehensive view of buying and selling pressure. Popular settings are 7, 14, and 28 periods.
Bollinger Bands %B: Provides insight into where the price is relative to its upper and lower bands. Standard settings include a 20-period moving average and a standard deviation of 2.
ADX (Average Directional Index): Measures the strength of a trend. Values above 25 typically indicate a strong trend, while values below suggest weak or sideways movement.
Stochastic Oscillator: A momentum indicator comparing the closing price to its range over a defined period. Popular configurations include 14 periods for %K and 3 for %D smoothing.
Parabolic SAR: Ideal for identifying trend reversals and entry/exit points. Commonly configured with a 0.02 step and a 0.2 maximum.
Money Flow Index (MFI): Similar to RSI but incorporates volume into the calculation. Standard settings use 14 periods, with levels of 20 and 80 as oversold and overbought thresholds.
Commodity Channel Index (CCI): Measures the deviation of price from its average. Traders often use a 20-period setting with levels of +100 and -100 to identify extreme overbought or oversold conditions.
Heikin Ashi Candles: These candles smooth out price fluctuations to show clearer trends. Commonly used in trend-following strategies to filter market noise.
🔵 How to use Signal Builder:
Configure indicators: Select the indicators that best fit your strategy and adjust their settings as needed. You can combine multiple indicators to define precise entry and exit conditions.
Define custom signals: Create buy or sell conditions that trigger when your selected indicators meet the criteria you’ve set. For example, configure a buy signal when RSI crosses above 30 and MACD confirms with a bullish crossover.
TradingView alerts: Set up alerts in TradingView to receive real-time notifications when the conditions you’ve defined are met, allowing you to react quickly to market opportunities without constantly monitoring charts.
Monitor with the panel: Signal Builder includes a visual panel that shows active conditions for each indicator in real time, helping you keep track of signals without manually checking each indicator.
🔵 3Commas integration:
In addition to being a valuable tool for any trader, Signal Builder is optimized to work seamlessly with 3Commas bots through Webhooks. This allows you to automate your trades based on the signals you’ve configured, ensuring that no opportunity is missed when your defined conditions are met. If you prefer automation, Signal Builder can send buy or sell signals to your 3Commas bots, enhancing your trading process and helping you manage multiple trades more efficiently.
🔵 Example of use:
Imagine you trade in volatile markets and want to trigger a sell signal when:
Stochastic Oscillator indicates overbought conditions with the %K value crossing below 80.
Bollinger Bands %B shows the price has surpassed the upper band, suggesting a potential reversal.
ADX is below 20, indicating that the trend is weak and could be about to change.
With Signal Builder , you can configure these conditions to trigger a sell signal only when all are met simultaneously. Then, you can set up a TradingView alert to notify you as soon as the signal is activated, giving you the opportunity to react quickly and adjust your strategy accordingly.
👨🏻💻💭 If this tool helps your trading strategy, don’t forget to give it a boost! Feel free to share in the comments how you're using it or if you have any questions.
_________________________________________________________________
The information and publications within the 3Commas TradingView account are not meant to be and do not constitute financial, investment, trading, or other types of advice or recommendations supplied or endorsed by 3Commas and any of the parties acting on behalf of 3Commas, including its employees, contractors, ambassadors, etc.
Overnight Positioning w EMA - Strategy [presentTrading]I've recently started researching Market Timing strategies, and it’s proving to be quite an interesting area of study. The idea of predicting optimal times to enter and exit the market, based on historical data and various indicators, brings a dynamic edge to trading. Additionally, it is integrated with the 3commas bot for automated trade execution.
I'm still working on it. Welcome to share your point of view.
█ Introduction and How it is Different
The "Overnight Positioning with EMA " is designed to capitalize on market inefficiencies during the overnight trading period. This strategy takes a position shortly before the market closes and exits shortly after it opens the following day. What sets this strategy apart is the integration of an optional Exponential Moving Average (EMA) filter, which ensures that trades are aligned with the underlying trend. The strategy provides flexibility by allowing users to select between different global market sessions, such as the US, Asia, and Europe.
It is integrated with the 3commas bot for automated trade execution and has a built-in mechanism to avoid holding positions over the weekend by force-closing positions on Fridays before the market closes.
BTCUSD 20 mins Performance
█ Strategy, How it Works: Detailed Explanation
The core logic of this strategy is simple: enter trades before market close and exit them after market open, taking advantage of potential price movements during the overnight period. Here’s how it works in more detail:
🔶 Market Timing
The strategy determines the local market open and close times based on the selected market (US, Asia, Europe) and adjusts entry and exit points accordingly. The entry is triggered a specific number of minutes before market close, and the exit is triggered a specific number of minutes after market open.
🔶 EMA Filter
The strategy includes an optional EMA filter to help ensure that trades are taken in the direction of the prevailing trend. The EMA is calculated over a user-defined timeframe and length. The entry is only allowed if the closing price is above the EMA (for long positions), which helps to filter out trades that might go against the trend.
The EMA formula:
```
EMA(t) = +
```
Where:
- EMA(t) is the current EMA value
- Close(t) is the current closing price
- n is the length of the EMA
- EMA(t-1) is the previous period's EMA value
🔶 Entry Logic
The strategy monitors the market time in the selected timezone. Once the current time reaches the defined entry period (e.g., 20 minutes before market close), and the EMA condition is satisfied, a long position is entered.
- Entry time calculation:
```
entryTime = marketCloseTime - entryMinutesBeforeClose * 60 * 1000
```
🔶 Exit Logic
Exits are triggered based on a specified time after the market opens. The strategy checks if the current time is within the defined exit period (e.g., 20 minutes after market open) and closes any open long positions.
- Exit time calculation:
exitTime = marketOpenTime + exitMinutesAfterOpen * 60 * 1000
🔶 Force Close on Fridays
To avoid the risk of holding positions over the weekend, the strategy force-closes any open positions 5 minutes before the market close on Fridays.
- Force close logic:
isFriday = (dayofweek(currentTime, marketTimezone) == dayofweek.friday)
█ Trade Direction
This strategy is designed exclusively for long trades. It enters a long position before market close and exits the position after market open. There is no shorting involved in this strategy, and it focuses on capturing upward momentum during the overnight session.
█ Usage
This strategy is suitable for traders who want to take advantage of price movements that occur during the overnight period without holding positions for extended periods. It automates entry and exit times, ensuring that trades are placed at the appropriate times based on the market session selected by the user. The 3commas bot integration also allows for automated execution, making it ideal for traders who wish to set it and forget it. The strategy is flexible enough to work across various global markets, depending on the trader's preference.
█ Default Settings
1. entryMinutesBeforeClose (Default = 20 minutes):
This setting determines how many minutes before the market close the strategy will enter a long position. A shorter duration could mean missing out on potential movements, while a longer duration could expose the position to greater price fluctuations before the market closes.
2. exitMinutesAfterOpen (Default = 20 minutes):
This setting controls how many minutes after the market opens the position will be exited. A shorter exit time minimizes exposure to market volatility at the open, while a longer exit time could capture more of the overnight price movement.
3. emaLength (Default = 100):
The length of the EMA affects how the strategy filters trades. A shorter EMA (e.g., 50) reacts more quickly to price changes, allowing more frequent entries, while a longer EMA (e.g., 200) smooths out price action and only allows entries when there is a stronger underlying trend.
The effect of using a longer EMA (e.g., 200) would be:
```
EMA(t) = +
```
4. emaTimeframe (Default = 240):
This is the timeframe used for calculating the EMA. A higher timeframe (e.g., 360) would base entries on longer-term trends, while a shorter timeframe (e.g., 60) would respond more quickly to price movements, potentially allowing more frequent trades.
5. useEMA (Default = true):
This toggle enables or disables the EMA filter. When enabled, trades are only taken when the price is above the EMA. Disabling the EMA allows the strategy to enter trades without any trend validation, which could increase the number of trades but also increase risk.
6. Market Selection (Default = US):
This setting determines which global market's open and close times the strategy will use. The selection of the market affects the timing of entries and exits and should be chosen based on the user's preference or geographic focus.
TrippleMACDCryptocurrency Scalping Strategy for 1m Timeframe
Introduction:
Welcome to our cutting-edge cryptocurrency scalping strategy tailored specifically for the 1-minute timeframe. By combining three MACD indicators with different parameters and averaging them, along with applying RSI, we've developed a highly effective strategy for maximizing profits in the cryptocurrency market. This strategy is designed for automated trading through our bot, which executes trades using hooks. All trades are calculated for long positions only, ensuring optimal performance in a fast-paced market.
Key Components:
MACD (Moving Average Convergence Divergence):
We've utilized three MACD indicators with varying parameters to capture different aspects of market momentum.
Averaging these MACD indicators helps smooth out noise and provides a more reliable signal for trading decisions.
RSI (Relative Strength Index):
RSI serves as a complementary indicator, providing insights into the strength of bullish trends.
By incorporating RSI, we enhance the accuracy of our entry and exit points, ensuring timely execution of trades.
Strategy Overview:
Long Position Entries:
Initiate long positions when all three MACD indicators signal bullish momentum and the RSI confirms bullish strength.
This combination of indicators increases the probability of successful trades, allowing us to capitalize on uptrends effectively.
Utilizing Linear Regression:
Linear regression is employed to identify consolidation phases in the market.
Recognizing consolidation periods helps us avoid trading during choppy price action, ensuring optimal performance.
Suitability for Grid Trading Bots:
Our strategy is well-suited for grid trading bots due to frequent price fluctuations and opportunities for grid activation.
The strategy's design accounts for price breakthroughs, which are advantageous for grid trading strategies.
Benefits of the Strategy:
Consistent Performance Across Cryptocurrencies:
Through rigorous testing on various cryptocurrency futures contracts, our strategy has demonstrated favorable results across different coins.
Its adaptability makes it a versatile tool for traders seeking consistent profits in the cryptocurrency market.
Integration of Advanced Techniques:
By integrating multiple indicators and employing linear regression, our strategy leverages advanced techniques to enhance trading performance.
This strategic approach ensures a comprehensive analysis of market conditions, leading to well-informed trading decisions.
Conclusion:
Our cryptocurrency scalping strategy offers a sophisticated yet user-friendly approach to trading in the fast-paced environment of the 1-minute timeframe. With its emphasis on automation, accuracy, and adaptability, our strategy empowers traders to navigate the complexities of the cryptocurrency market with confidence. Whether you're a seasoned trader or a novice investor, our strategy provides a reliable framework for achieving consistent profits and maximizing returns on your investment.
Heatmap MACD Strategy - Pineconnector (Dynamic Alerts)Hello traders
This script is an upgrade of this template script.
Heatmap MACD Strategy
Pineconnector
Pineconnector is a trading bot software that forwards TradingView alerts to your Metatrader 4/5 for automating trading.
Many traders don't know how to dynamically create Pineconnector-compatible alerts using the data from their TradingView scripts.
Traders using trading bots want their alerts to reflect the stop-loss/take-profit/trailing-stop/stop-loss to breakeven options from your script and then create the orders accordingly.
This script showcases how to create Pineconnector alerts dynamically.
Pineconnector doesn't support alerts with multiple Take Profits.
As a workaround, for 2 TPs, I had to open two trades.
It's not optimal, as we end up paying more spreads for that extra trade - however, depending on your trading strategy, it may not be a big deal.
TradingView Alerts
1) You'll have to create one alert per asset X timeframe = 1 chart.
Example : 1 alert for EUR/USD on the 5 minutes chart, 1 alert for EUR/USD on the 15-minute chart (assuming you want your bot to trade the EUR/USD on the 5 and 15-minute timeframes)
2) For each alert, the alert message is pre-configured with the text below
{{strategy.order.alert_message}}
Please leave it as it is.
It's a TradingView native variable that will fetch the alert text messages built by the script.
3) Don't forget to set the webhook URL in the Notifications tab of the TradingView alerts UI.
EA configuration
The Pyramiding in the EA on Metatrader must be set to 2 if you want to trade with 2 TPs => as it's opening 2 trades.
If you only want 1 TP, set the EA Pyramiding to 1.
Regarding the other EA settings, please refer to the Pineconnector documentation on their website.
Logger
The Pineconnector commands are logged in the TradingView logger.
You'll find more information about it from this TradingView blog post
Important Notes
1) This multiple MACDs strategy doesn't matter much.
I could have selected any other indicator or concept for this script post.
I wanted to share an example of how you can quickly upgrade your strategy, making it compatible with Pineconnector.
2) The backtest results aren't relevant for this educational script publication.
I used realistic backtesting data but didn't look too much into optimizing the results, as this isn't the point of why I'm publishing this script.
3) This template is made to take 1 trade per direction at any given time.
Pyramiding is set to 1 on TradingView.
The strategy default settings are:
Initial Capital: 100000 USD
Position Size: 1 contract
Commission Percent: 0.075%
Slippage: 1 tick
No margin/leverage used
For example, those are realistic settings for trading CFD indices with low timeframes but not the best possible settings for all assets/timeframes.
Concept
The Heatmap MACD Strategy allows selecting one MACD in five different timeframes.
You'll get an exit signal whenever one of the 5 MACDs changes direction.
Then, the strategy re-enters whenever all the MACDs are in the same direction again.
It takes:
long trades when all the 5 MACD histograms are bullish
short trades when all the 5 MACD histograms are bearish
You can select the same timeframe multiple times if you don't need five timeframes.
For example, if you only need the 30min, the 1H, and 2H, you can set your timeframes as follow:
30m
30m
30m
1H
2H
Risk Management Features
All the features below are pips-based.
Stop-Loss
Trailing Stop-Loss
Stop-Loss to Breakeven after a certain amount of pips has been reached
Take Profit 1st level and closing X% of the trade
Take Profit 2nd level and close the remaining of the trade
Custom Exit
I added the option ON/OFF to close the opened trade whenever one of the MACD diverges with the others.
Help me help the community
If you see any issue when adding your strategy logic to that template regarding the orders fills on your Metatrader, please let me know in the comments.
I'll use your feedback to make this template more robust. :)
What's next?
I'll publish a more generic template built as a connector so you can connect any indicator to that Pineconnector template.
Then, I'll publish a template for Capitalise AI, ProfitView, AutoView, and Alertatron.
Thank you
Dave
ATR and IV Volatility TableThis is a volatility tool designed to get the daily bottom and top values calculated using a daily ATR and IV values.
ATR values can be calculated directly, however for IV I recommend to take the values from external sources for the asset that you want to trade.
Regarding of the usage, I always recommend to go at the end of the previous close day of the candle(with replay function) or beginning of the daily open candle and get the expected values for movements.
For example for 26April for SPX, we have an ATR of 77 points and the close of the candle was 4296.
So based on ATR for 27 April our TOP is going to be 4296 + 77 , while our BOT is going to be 4296-77
At the same time lets assume the IV for today is going to be around 25% -> this is translated to 25 / (sqrt (252)) = 1.57 aprox
So based on IV our TOP is going to be 4296 + 4296 * 0.0157 , while our BOT is going to be 4296 - 4296 * 0.0157
I found out from my calculations that 80-85% of the times these bot and top points act as an amazing support and resistence points for day trading, so I fully recommend you to start including them into your analysis.
If you have any questions let me know !
TrendsThe Trends indicator is created for trend trading and (Bitsgap) crypto bots of crypto assets over longer time periods.
Works best for 4h, Daily and Weekly candles (even Monthly), but unsuitable for hourly candles and day trading.
This indicator shows you if a crypto pair is in a Bear, Bull or Sideways market.
The idea is to simplify decision making when to sell or buy, or what pairs to use with trading bots.
Stick to the rule of not having bots in a Bear trend!
- Blue = Bull trend
- Red = Bear trend
- Green = Sideways trend - which can be profitable with trading bots
Mazuuma Churn IndicatorThis indicator was specifically made to confirm a periode of sideways movement (churn) on Bitcoin. It can probably be used for other cryptocurrencies as well. I use it on the daily timeframe.
Yellow means "Unconfirmed".
Orange means "Partially Confirmed".
Red means "Confirmed"
The indicator is not perfect, so use your common sense.
Churn starts when at least 2 of the conditions below are met (use also your common sense):
1. ATR < MA 20 on ATR
2. Distance to EMA 200 must be ≤ 16% at “Open churn”
3. EMA 12 on RSI between 40 and 60
4. ADX < 25
The above are weighted. Meaning no 1 has most significance. The numbers can be tweaked.
Reversal coming
* The indicators above break out, especially the ATR
* Color shift of the Heikin Ashi candle on weekly timeframe
* Engulfing candle on weekly timeframe
Because of the offset of the EMA 200, the precision of the Churn predictor can be off after a VERY big spike up or down, e.g. dec 2017. After such a spike use your common sense.
Personally I use this for bot trading, i.e. turn off trend following bots when in sideways market and use grid bots or other means of trading instead.
Multi VWAPMulti VWAP indicator for Wick Hunter
For when you are running out of indicator slots
Can configure each set for Setting 1/2/3, or for Binance bot 1/Binance bot 2/Bybit bot, etc.
By honeybadger, built on original code by STP Todd (see indicator "Wick Hunter VWAP")
BTC 15 minThis strategy try to catch the uptrend mainly (seems to work on BTC 15 less on others)
the aim is to get 2% in uptrend which is more easy to do then to search only for lowest
since it buy in uptrend it can risky if market change direction
there are two take profit (1% and 2% ) , you take out 50% of equity after the first 1% gain
the stop loss and re buy set 5%
so you exit after 5 % loss and re buy it again at lower price
the aim here is to do leverage trades so you can calculate your risk or lot and the leverage power you want
now set on 100% lot leverage X1
you can try any combination you want but when you do leverage trading you need to do things that the back tester of TV cannot do so well
for example if you put 100X leverage you will be liquidated at 1%
50=2%
20=5%
10=10%
5=20%
you need that your stop loss will be above the liquidation level
stop loss are shit in margin trades as they can kick you out very fast and you will lose many good trades
so I prefer 5X max 10 X trade (this bot can work by himself but i prefer to do it manually for this kind of trades.
all u need to do is to choose what risk you want to have (3% of lot? 5%, 10% or higher )
so this tool try to give you upward buy strategy that aim to get longs at upward trends (short targets that are more easy to get )
and to use leverage as way to make more profit (now bot set to no leverage )
be wise with your money :)
the bot not suppose to repaint but if you find repaint issue then let me know
buy system is based on cross of linear over modified non repainted HMA that set to 1 min (so it buy the uptrend only+ filter based on ema that try not to start cycle of buy in down traade
sell is not so important is mainly cased on percentage channel seen
trend color on Chanel not related to the buy and sell system
Kirk65 UTBot Strategy FixedCredits to @HPotter for the orginal code.
Credits to @Yo_adriiiiaan for recently publishing the UT Bot study based on the original code.
Credits to @TradersAITradingPlans for making UT Bot strategy.
Strategy fixed with time period by Kirk65.
UT Bot works great with 2 hour time frame with Heikin Ashi, but riskier. Use "Once per bar" In alerts with 1.5% stoploss. If the price goes against Alerts, stoploss will save your assets. Wait until next Alert.
4 hour time frame is less risky and less profitable.
Happy trading..
Kirk65
Swiss Knife [MERT]Introduction
The Swiss Knife indicator is a comprehensive trading tool designed to provide a multi-dimensional analysis of the market. By integrating a wide array of technical indicators across multiple timeframes, it offers traders a holistic view of market sentiment, momentum, and potential reversal points. This indicator is particularly useful for traders looking to combine trend analysis, momentum indicators, volume data, and price action into a single, easy-to-read format.
---
Key Features
Multi-Timeframe Analysis : Evaluates indicators on Daily , 4-Hour , 1-Hour , and 15-Minute timeframes.
Comprehensive Indicator Suite : Incorporates MACD , Awesome Oscillator (AO) , Parabolic SAR , SuperTrend , DPO , RSI , Stochastic Oscillator , Bollinger Bands , Ichimoku Cloud , Chande Momentum Oscillator (CMO) , Donchian Channels , ADX , volume-based momentum indicators, Fractals , and divergence detection.
Market Sentiment Scoring : Aggregates signals from multiple indicators to provide an overall sentiment score.
Visual Aids : Displays EMA lines, trendlines, divergence signals, and a sentiment table directly on the chart.
Super Trend Reversal Signals : Identifies potential market reversal points by assessing the momentum of automated trading bots.
---
Explanation of Each Indicator
Moving Average Convergence Divergence (MACD)
- Purpose : Measures the relationship between two moving averages of price.
- Interpretation : A positive histogram suggests bullish momentum; a negative histogram indicates bearish momentum.
Awesome Oscillator (AO)
- Purpose : Gauges market momentum by comparing recent market movements to historic ones.
- Interpretation : Above zero indicates bullish momentum; below zero indicates bearish momentum.
Parabolic SAR (SAR)
- Purpose : Identifies potential reversal points in price direction.
- Interpretation : Dots below price suggest an uptrend; dots above price suggest a downtrend.
SuperTrend
- Purpose : Determines the prevailing market trend.
- Interpretation : Provides buy or sell signals based on price movements relative to the SuperTrend line.
Detrended Price Oscillator (DPO)
- Purpose : Removes trend from price to identify cycles.
- Interpretation : Values above zero suggest price is above the moving average; values below zero indicate it is below.
Relative Strength Index (RSI)
- Purpose : Measures the speed and change of price movements.
- Interpretation : Values above 50 indicate bullish momentum; values below 50 indicate bearish momentum.
Stochastic Oscillator
- Purpose : Compares a particular closing price to a range of its prices over a certain period.
- Interpretation : Values above 50 indicate bullish conditions; values below 50 indicate bearish conditions.
Bollinger Bands (BB)
- Purpose : Measures market volatility and provides relative price levels.
- Interpretation : Price above the middle band suggests bullishness; below the middle band suggests bearishness.
Ichimoku Cloud
- Purpose : Provides support and resistance levels, trend direction, and momentum.
- Interpretation : Bullish signals when price is above the cloud; bearish signals when price is below the cloud.
Chande Momentum Oscillator (CMO)
- Purpose : Measures momentum on both up and down days.
- Interpretation : Values above 50 indicate strong upward momentum; values below -50 indicate strong downward momentum.
Donchian Channels
- Purpose : Identifies volatility and potential breakouts.
- Interpretation : Price above the upper band suggests bullish breakout; below the lower band suggests bearish breakout.
Average Directional Index (ADX)
- Purpose : Measures the strength of a trend.
- Interpretation : DI+ above DI- indicates bullish trend; DI- above DI+ indicates bearish trend.
Volume Momentum Indicators (VolMom, CumVolMom, POCMom)
- Purpose : Analyze volume to assess buying and selling pressure.
- Interpretation : Positive values suggest bullish volume momentum; negative values indicate bearish volume momentum.
Fractals
- Purpose : Identify potential reversal points in the market.
- Interpretation : Up fractals may indicate a future downtrend; down fractals may indicate a future uptrend.
Divergence Detection
- Purpose : Identifies divergences between price and various indicators (RSI, MACD, Stochastic, OBV, MFI, A/D Line).
- Interpretation : Bullish divergences suggest potential upward reversal; bearish divergences suggest potential downward reversal.
- Note : This functionality utilizes the library from Divergence Indicator .
---
Coloring Scheme
Background Color
- Purpose : Reflects the overall market sentiment by combining sentiment scores from all indicators across different timeframes.
- Interpretation :
- Green Shades : Indicate bullish market sentiment.
- Red Shades : Indicate bearish market sentiment.
- Intensity : The strength of the color corresponds to the strength of the sentiment score.
Sentiment Table
- Purpose : Displays the status of each indicator across different timeframes.
- Interpretation :
- Green Cell : The indicator suggests a bullish signal.
- Red Cell : The indicator suggests a bearish signal.
- Percentage Score : Indicates the overall bullish or bearish sentiment on that timeframe.
Exponential Moving Averages (EMAs)
- Purpose : Provide dynamic support and resistance levels.
- Colors :
- EMA 10 : Lime
- EMA 20 : Yellow
- EMA 50 : Orange
- EMA 100 : Red
- EMA 200 : Purple
Trendlines
- Purpose : Visual representation of support and resistance levels based on pivot points.
- Interpretation :
- Upward Trendlines : Colored green , indicating support levels.
- Downward Trendlines : Colored red , indicating resistance levels.
- Note : Trendlines are drawn using the library from Simple Trendlines .
---
Utility of Market Sentiment
The indicator aggregates signals from multiple technical indicators across various timeframes to compute an overall market sentiment score . This comprehensive approach helps traders understand the prevailing market conditions by:
Confirming Trends : Multiple indicators pointing in the same direction can confirm the strength of a trend.
Identifying Reversals : Divergences and fractals can signal potential turning points.
Timeframe Alignment : Aligning signals across different timeframes can enhance the probability of successful trades.
---
Divergences
Divergence occurs when the price of an asset moves in the opposite direction of a technical indicator, suggesting a potential reversal.
- Bullish Divergence : Price makes a lower low, but the indicator makes a higher low.
- Bearish Divergence : Price makes a higher high, but the indicator makes a lower high.
The indicator detects divergences for:
RSI
MACD
Stochastic Oscillator
On-Balance Volume (OBV)
Money Flow Index (MFI)
Accumulation/Distribution Line (A/D Line)
By identifying these divergences, traders can spot early signs of trend reversals and adjust their strategies accordingly.
---
Trendlines
Trendlines are essential tools for identifying support and resistance levels. The indicator automatically draws trendlines based on pivot points:
- Upward Trendlines (Support) : Connect higher lows, indicating an uptrend.
- Downward Trendlines (Resistance) : Connect lower highs, indicating a downtrend.
These trendlines help traders visualize the trend direction and potential breakout or reversal points.
---
Super Trend Reversals (ST Reversal)
The core idea behind the Super Trend Reversals indicator is to assess the momentum of automated trading bots (often referred to as 'Supertrend bots') that enter the market during critical turning points. Specifically, the indicator is tuned to identify when the market is nearing bottoms or peaks, just before it shifts direction based on the triggered Supertrend signals. This approach helps traders:
Engage Early : Enter the market as reversal momentum builds up.
Optimize Entries and Exits : Enter under favorable conditions and exit before momentum wanes.
By capturing these reversal points, traders can enhance their trading performance.
---
Conclusion
The Swiss Knife indicator serves as a versatile tool that combines multiple technical analysis methods into a single, comprehensive indicator. By assessing various aspects of the market—including trend direction, momentum, volume, and price action—it provides traders with valuable insights to make informed trading decisions.
---
Citations
- Divergence Detection Library : Divergence Indicator by DevLucem
- Trendline Drawing Library : Simple Trendlines by HoanGhetti
---
Note : This indicator is intended for informational purposes and should be used in conjunction with other analysis techniques. Always perform due diligence before making trading decisions.
---
Super Trend ReversalsMain Concept
The core idea behind the Super Trend Reversals indicator is to assess the momentum of automated trading bots (often referred to as 'Supertrend bots') that enter the market during critical turning points. Specifically, the indicator is tuned to identify when the market is nearing bottoms or peaks, but just before it shifts direction based on the triggered Supertrend signals. This approach helps traders engage with the market right as the reversal momentum builds up, allowing for entry just as conditions become favorable and exit before momentum wanes.
How It Works
The Super Trend Reversals uses multiple Supertrend calculations, each with different period and multiplier settings, to form a comprehensive view of the trend. The total trend score from these calculations is then analyzed using the Relative Strength Index (RSI) and Exponential Moving Averages (EMA) to gauge the strength and sustainability of the trend.
A key feature of this indicator is the isCurrentRangeSmaller() function, which evaluates if the current price range is lower than the average over the recent period. This function is critical as it helps determine the stability of the market environment, reducing the likelihood of entering or exiting trades based on erratic price movements that could lead to false signals.
speed of tradesThis indicator calculates the speed of trades, on other platform that is called speed of tape, but they said you need delta and others for the calculation.
Calculation method
This indicator calculates the number of trades per bar and filter it, if they are above a sma it highlights the column to know that could be a bar where there are more trades than usual.
It's based on an example of pinescript v5 user manual where explain the use of varip
HF Bots filter and common uses
know where there are more trades than usual help you to have an idea that could be HF Bots working on that bar, also if you dont belive on that, can also help you to have an idea of momentum or stoping action.
Why is this indicator original?
The speed of trades indicator give you an counter of number of trades and a filter for bars where there are a lot of trades, so searching speed of tape/trades indicator that don't exist on tradingview, this indicator is original.
How to charge data?
By default it doesn't load historical tick data, this indicator only works on realtime bars.
[DisDev] D-I-Y Gridbot🟩 This script is a “do-it-yourself” Grid Bot Simulator, used for visualizing support and resistance levels. Prices are divided into grids, or trade zones, that will trigger signals each time a new zone is entered. During ranging markets, each transaction is followed by a “take profit.” As the market starts to trend, transactions are stacked (compare to DCA ), until the market consolidates. No signals are triggered above the upper gridline or below the lower gridline. Unlike the previous version, all grids may be adjusted in real-time by dragging the gridlines up and down to the desired support and resistance levels.
When adding the indicator to a new chart, you must choose six grid levels by clicking on the desired support or resistance price. You can change all of these levels at any time directly on the chart.
⚡ OVERVIEW ⚡
The D-I-Y Gridbot is an interactive tool designed for visualizing support and resistance levels. As a continuation of the original Gridbot Simulator , which has received significant recognition on TradingView, earning over 4000 boosts and an Editor's Pick status. This tool serves not only as an evolved version of its predecessor, but also as an open-source template for developing future gridbots. It aims to foster discussions and facilitate innovations around grid-trading strategies.
One of the new features of this gridbot is the real-time adjustability of all gridlines. Users can move these lines up and down to set their desired support and resistance levels in response to changing market conditions. Additionally, the D-I-Y Gridbot is compatible with multiple timeframes and can be used on most TradingView charts.
Drag gridlines up or down to desired price level.
Key Features 🔑
All gridlines are adjustable in real-time, directly on the chart
Signals can be filtered by a customizable moving average or by VWAP
Customizable support and resistance levels
Potentially increases profitability in ranging markets
Benefits 💸
Customizable Support and Resistance Levels : The D-I-Y Gridbot allows users to set their preferred support and resistance levels, which can be changed at any time directly on the chart. This provides users with the ability to customize their trading parameters based on their strategy and risk tolerance.
Various Trading Strategies : The D-I-Y Gridbot supports various trading strategies, including Mean Reversion, Ranging Markets, and Dollar-cost averaging (DCA). This allows users to capitalize on price reversals, execute buy and sell orders at predetermined levels, and buy more of an asset as the price falls, respectively.
Multi-Timeframe and Versatility : The D-I-Y Gridbot is compatible with multiple timeframes and can be used on any TradingView chart.
Experimental and Educational : The D-I-Y Gridbot is considered a proof-of-concept tool that is both experimental and educational. This can provide traders with a deeper understanding of grid trading strategies and the ability to experiment with different trading parameters and strategies.
⚙️ CONFIGURATION & SETTINGS ⚙️
Inputs 🔧
Trigger : Candle location to trigger the signal. "Wick" will use either high or low, depending on the signal direction. "Close" will use the close price. “MA” will use the selected moving average or VWAP.
Confirmation : Market direction to confirm the candle trigger. "Reverse" will confirm the signal when the price crosses back over the trigger. "Breakout" will confirm when the price breaks out of the trigger.
Number of Support/Resistance zones : 1 = Only Top Grid is Support/Only Bottom Grid is Resistance. 2 = Top two grids are Resistance/Bottom two grids are Support. 3 = Top three grids are Resistance/Bottom three grids are Support
MA Type : Exponential Moving Average (EMA), Hull Moving Average (HMA), Simple Moving Average (SMA), Triple Exponential Moving Average (TEMA), Volume Weighted Moving Average (VWMA), Volume Weighted Average Price (VWAP)
MA Filter : Use Moving Average as a reversion filter for signals. When enabled, no buys when above MA, no sells when below. Use in conjunction with S/R zones to reduce false signals.
Allow Repeat Signals . When enabled, signals will reset when nearest gridline is triggered. When disabled, only one signal will be triggered per gridline.
Line/Fill colors
Gridlines . Adjusts gridline prices manually.
Left : Trigger = Wick. Confirm = Breakout. Buys are signaled when LOW breaks below gridline. Sells are triggered when HIGH breaks above gridline.
Right : Trigger = Close. Confirm = Breakout. Buys are signaled when the candle CLOSES below the gridline. Sells are triggered when the candle CLOSES above the gridline.
Left : Confirm=Breakout. Signals on breaking through the next gridline.
Right : Confirm=Reverse. Signals only when crossing back from the gridline.
S/R Zones=1. Upper gridline is Resistance / Lower is Support. Middle 4 are neutral.
S/R Zones = 3. Upper three gridlines are Resistance / Lower three are Support
Notes:
If gridlines are dragged out of order on a live chart, they will auto-sort into the correct order.
Price levels may be entered in settings, or adjusted in real-time directly on the chart.
When changing symbols, remember to adjust the gridlines to accommodate the new symbol.
Alerts 🔔
Users can set alerts based on their chosen parameters for triggers, confirmations, number of support/resistance zones, and smoothing type, enabling precise control over alert conditions.
💡 USAGE & STRATEGY 💡
Trading Strategies 📈
Mean Reversion: The script can be used to capitalize on price reversals back to the mean.
Ranging Markets: The script excels in ranging markets, executing buy and sell orders at predetermined levels.
Dollar-cost averaging (DCA): The script can be used to execute DCA orders, buying more of an asset as the price falls, and lowering the average cost per unit.
Timeframes and Symbols ⌚
Multi-Timeframe: The indicator is compatible with multiple timeframes.
Versatile: Can be used on any crypto trading pair on TradingView.
🤖 DETAILS & METHODOLOGY 🤖
Algorithm and Calculation 🛡️
Grids are set and adjusted when loading the indicator on the chart and may be customized anytime afterward by clicking and dragging the gridlines on the chart.
Gridlines are updated, sorted, and stored in a float array.
Signals are calculated based on candle trigger, market direction, and previous price level.
📚 ADDITIONAL RESOURCES 📚
Chart Examples 📊
S/R Zones = 3: Three Support and Three Resistance. Filter = 50-period Triple Exponential Moving Average (TEMA)
S/R Zones = 1: One Support, One Resistance, and Four Neutral Zones. Support Zones: Buys only. Resistance Zones: Sells only. Neutral Zones: Grid-dependent
When MA filter is enabled, Buys are only triggered below Moving Average, and Sells are only triggered above.
Trigger = Wick. Confirmation = Breakout. Buys are signaled when Low breaks above the next grid level. Sells are signaled when High breaks below the next grid level.
🚀 CONCLUSION 🚀
The D-I-Y Gridbot is a proof-of-concept, emphasizing its experimental and educational nature. In future versions, we will aim to incorporate concepts such as auto-adjusting grids and angled grids for trending markets. The script is designed to evolve through user feedback and suggestions, shaping its future iterations.
Credit: This is a continuation of the Gridbot series by xxattaxx-DisDev . Explicit permission was granted by user xxattaxx-disdev to re-use all Gridbot code and all materials without restrictions.
⚠️ DISCLAIMER ⚠️
This indicator is a proof-of-concept and is considered experimental and educational. When gridlines are drawn in hindsight, signals appear to be predictive and valid. Future results may always vary when the trend direction changes. Comments and suggestions are encouraged.
This indicator is provided as a tool for traders and should not be used as the sole basis for making trading decisions. Always conduct your own research and consider your risk tolerance before entering any trades.
Keltner Trend V3It's just a simple keltner trend with options added to:
Eradicate repainting
more MAs
Json alerts (useful for bots)
I recommend using "open" option for all sources if you are going to use it with a bot, or if you want to be safe and enter with confirmations. Using the default settings would also show you all the entries without repainting as it uses high and low prices to check breakouts and not solely the close price (which is generally a false representative in historic analysis).
My favorite lengths are 7, 14, and 21. There is no specific reason, they just seem to work well most of the time. You can (and should) optimize it to your purposes.
Thanks to the original author @jaggedsoft this script is just a improved version of theirs.
Сoncentrated Market Maker Strategy by oxowlConcentrated Market Maker Strategy by oxowl. This script plots an upper and lower bound for liquidity provision, and checks for rebalancing conditions. It also includes alert conditions for when the price crosses the upper or lower bounds.
Here's an overview of the script:
It defines the input parameters: liquidity range percentage, rebalance frequency in minutes, and minimum trade size in assets.
It calculates the upper and lower bounds for liquidity provision based on the liquidity range percentage.
It initializes variables for the last rebalance time and price.
It defines a rebalance condition based on the frequency and current price within the specified range.
If the rebalance condition is met, it updates the last rebalance time and price.
It plots the upper and lower bounds on the chart as lines and adds price labels for both bounds.
It defines alert conditions for when the price crosses the upper or lower bounds.
Finally, it creates alert conditions with appropriate messages for when the price crosses the upper or lower bounds.
Concentrated liquidity is a concept often used in decentralized finance (DeFi) market-making strategies. It allows liquidity providers (LPs) to focus their liquidity within a specific price range, rather than across the entire price curve. Using an indicator with concentrated liquidity can offer several advantages:
Increased capital efficiency: Concentrated liquidity allows LPs to allocate their capital within a narrower price range. This means that the same amount of capital can generate more significant price impact and potentially higher returns compared to providing liquidity across a broader range.
Customized risk exposure: LPs can choose the price range they feel most comfortable with, allowing them to better manage their risk exposure. By selecting a range based on their market outlook, they can optimize their positions to maximize potential returns.
Adaptive strategies: Indicators that support concentrated liquidity can help traders adapt their strategies based on market conditions. For example, they can choose to provide liquidity around a stable price range during low-volatility periods or adjust their range when market conditions change.
To continue integrating this script into your trading strategy, follow these steps:
Import the script into your TradingView account. Navigate to the Pine editor, paste the code, and save it as a new script.
Apply the indicator to a trading pair chart. You can customize the input parameters (liquidity range percentage, rebalance frequency, and minimum trade size) based on your preferences and risk tolerance.
Set alerts for when the price crosses the upper or lower bounds. This will notify you when it's time to take action, such as adding or removing liquidity, or rebalancing your position.
Monitor the performance of your strategy over time. Adjust the input parameters as needed to optimize your returns and manage risk effectively.
(Optional) Integrate the script with a trading bot or automation platform. If you're using an API-based trading solution, you can incorporate the logic and conditions from the script into your bot's algorithm to automate the process of providing concentrated liquidity and rebalancing your positions.
Remember that no strategy is foolproof, and past performance is not indicative of future results. Always exercise caution when trading and carefully consider your risk tolerance.
Futures/Spot Ratiowhat is Futures /Spot Ratio?
Although futures and spot markets are separate markets, they are correlated. arbitrage bots allow this gap to be closed. But arbitrage bots also have their limits. so there are always slight differences between futures and spot markets. By analyzing these differences, the movements of the players in the market can be interpreted and important information about the price can be obtained. Futures /Spot Ratio is a tool that facilitates this analysis.
what it does?
it compresses the ratio between two selected spot and futures trading pairs between 0 and 100. its purpose is to facilitate use and interpretation. it also passes a regression (Colorful Regression) through the middle of the data for the same purpose.
about Colorful Regression:
how it does it?
it uses this formula:
how to use it?
use it to understand whether the market is priced with spot trades or leveraged positions. A value of 50 is the breakeven point where the ratio of the spot and leveraged markets are equal. Values above 50 indicate excess of long positions in the market, values below 50 indicate excess of short positions. I have explained how to interpret these ratios with examples below.
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!
libKageMiscLibrary "libKageMisc"
Kage's Miscelaneous library
print(_value)
Print a numerical value in a label at last historical bar.
Parameters:
_value : (float) The value to be printed.
Returns: Nothing.
barsBackToDate(_year, _month, _day)
Get the number of bars we have to go back to get data from a specific date.
Parameters:
_year : (int) Year of the specific date.
_month : (int) Month of the specific date. Optional. Default = 1.
_day : (int) Day of the specific date. Optional. Default = 1.
Returns: (int) Number of bars to go back until reach the specific date.
bodySize(_index)
Calculates the size of the bar's body.
Parameters:
_index : (simple int) The historical index of the bar. Optional. Default = 0.
Returns: (float) The size of the bar's body in price units.
shadowSize(_direction)
Size of the current bar shadow. Either "top" or "bottom".
Parameters:
_direction : (string) Direction of the desired shadow.
Returns: (float) The size of the chosen bar's shadow in price units.
shadowBodyRatio(_direction)
Proportion of current bar shadow to the bar size
Parameters:
_direction : (string) Direction of the desired shadow.
Returns: (float) Ratio of the shadow size per body size.
bodyCloseRatio(_index)
Proportion of chosen bar body size to the close price
Parameters:
_index : (simple int) The historical index of the bar. Optional. Default = 0.()
Returns: (float) Ratio of the body size per close price.
lastDayOfMonth(_month)
Returns the last day of a month.
Parameters:
_month : (int) Month number.
Returns: (int) The number (28, 30 or 31) of the last day of a given month.
nameOfMonth(_month)
Return the short name of a month.
Parameters:
_month : (int) Month number.
Returns: (string) The short name ("Jan", "Feb"...) of a given month.
pl(_initialValue, _finalValue)
Calculate Profit/Loss between two values.
Parameters:
_initialValue : (float) Initial value.
_finalValue : (float) Final value = Initial value + delta.
Returns: (float) Profit/Loss as a percentual change.
gma(_Type, _Source, _Length)
Generalist Moving Average (GMA).
Parameters:
_Type : (string) Type of average to be used. Either "EMA", "HMA", "RMA", "SMA", "SWMA", "WMA" or "VWMA".
_Source : (series float) Series of values to process.
_Length : (simple int) Number of bars (length).
Returns: (float) The value of the chosen moving average.
xFormat(_percentValue, _minXFactor)
Transform a percentual value in a X Factor value.
Parameters:
_percentValue : (float) Percentual value to be transformed.
_minXFactor : (float) Minimum X Factor to that the conversion occurs. Optional. Default = 10.
Returns: (string) A formated string.
isLong()
Check if the open trade direction is long.
Returns: (bool) True if the open position is long.
isShort()
Check if the open trade direction is short.
Returns: (bool) True if the open position is short.
lastPrice()
Returns the entry price of the last openned trade.
Returns: (float) The last entry price.
barsSinceLastEntry()
Returns the number of bars since last trade was oppened.
Returns: (series int)
getBotNameFrosty()
Return the name of the FrostyBot Bot.
Returns: (string) A string containing the name.
getBotNameZig()
Return the name of the FrostyBot Bot.
Returns: (string) A string containing the name.
getTicksValue(_currencyValue)
Converts currency value to ticks
Parameters:
_currencyValue : (float) Value to be converted.
Returns: (float) Value converted to minticks.
getSymbol(_botName, _botCustomSymbol)
Formats the symbol string to be used with a bot
Parameters:
_botName : (string) Bot name constant. Either BOT_NAME_FROSTY or BOT_NAME_ZIG. Optional. Default is empty string.
_botCustomSymbol : (string) Custom string. Optional. Default is empy string.
Returns: (string) A string containing the symbol for the bot. If all arguments are empty, the current symbol is returned in Binance format.
showProfitLossBoard()
Calculates and shows a board of Profit/Loss through the years.
Returns: Nothing.