libKageBotLibrary "libKageBot"
Library of function to generate command strings for bots FrostyBot and Zignally. This version ONLY WORKS WITH FROSTYBOT.
strSize(_sizePercent, _sizeCurrency)
Converts a float to a formated string suitable to position size in percentage or currency. At leaste one parameter must be given
Parameters:
_sizePercent : (float) Position size in percent value. Optional. Default = na. Mandatory if _sizeCurrency is not given.
_sizeCurrency : (float) Position size in currency value. Optional. Default = na. Mandatory if _sizePercent is not given.
Returns: (string) A formated string containing the position size
entry(_bot, _direction, _sizePercent, _sizeCurrency)
Generates a simple entry command string for a bot
Parameters:
_bot : (TradeBot) Previously instancied bot type variable
_direction : (string) Flag to opena long or a short position. Must be either DIRECTION_LONG or DIRECTION_SHORT constant
_sizePercent : (float) Position size in percent value. Optional. Default = na. Mandatory if _sizeCurrency is not given.
_sizeCurrency : (float) Position size in currency value. Optional. Default = na. Mandatory if _sizePercent is not given.
Returns: (string) A string of a simple open position command
exit(_bot, _sizePercent, _sizeCurrency, _reduce)
Generates a simple exit command string for a bot
Parameters:
_bot : (TradeBot) Previously instancied bot type variable
_sizePercent : (float) Position size in percent value. Optional. Default = na. Mandatory if _sizeCurrency is not given.
_sizeCurrency : (float) Position size in currency value. Optional. Default = na. Mandatory if _sizePercent is not given.
_reduce : (bool) Flag to use Ruce Only option on Binance positions. Optional. Default = true
Returns: (string) A string of a simple close position command
cancelAll(_bot)
Generates a command string for a bot that cancels all open orders
Parameters:
_bot : (TradeBot) Previously instancied bot type variable
Returns: (string) A string of a command to cancel all open orders
leverage(_bot, _leverage, _type)
Generates a command string for a bot to set leverage
Parameters:
_bot : (TradeBot) Previously instancied bot type variable
_leverage : (int) The amount of leverage to be used when opening a position. Optional. If does not given, the bot's default will be used
_type : (string) Type of leverage. Must be either LEVERAGE_CROSS or LEVERAGE_ISOLATED. Optional. Default is LEVERAGE_CROSS.
Returns: (string) A string of a simple leverage command
entryLong(_bot, _leverage, _leverageType, _sizePercent, _sizeCurrency)
Generates a complete long entry command string for a bot
Parameters:
_bot : (TradeBot) Previously instancied bot type variable
_leverage : (int) The amount of leverage to be used when opening a position. Optional. If does not given, the bot's default will be used
_leverageType : (string) Type of leverage. Must be either LEVERAGE_CROSS or LEVERAGE_ISOLATED. Optional. Default is LEVERAGE_CROSS.
_sizePercent : (float) Position size in percent value. Optional. Default = na. Mandatory if _sizeCurrency is not given.
_sizeCurrency : (float) Position size in currency value. Optional. Default = na. Mandatory if _sizePercent is not given.
Returns: (string) A string of a complete open long position command
entryShort(_bot, _leverage, _leverageType, _sizePercent, _sizeCurrency)
Generates a complete short entry command string for a bot
Parameters:
_bot : (TradeBot) Previously instancied bot type variable
_leverage : (int) The amount of leverage to be used when opening a position. Optional. If does not given, the bot's default will be used
_leverageType
_sizePercent : (float) Position size in percent value. Optional. Default = na. Mandatory if _sizeCurrency is not given.
_sizeCurrency : (float) Position size in currency value. Optional. Default = na. Mandatory if _sizePercent is not given.
Returns: (string) A string of a complete open short position command
exitPosition(_bot, _sizePercent, _sizeCurrency, _reduce)
Generates a complete close position command string for a bot
Parameters:
_bot : (TradeBot) Previously instancied bot type variable
_sizePercent : (float) Position size in percent value. Optional. Default = na. Mandatory if _sizeCurrency is not given.
_sizeCurrency : (float) Position size in currency value. Optional. Default = na. Mandatory if _sizePercent is not given.
_reduce : (bool) Flag to use Ruce Only option on Binance positions. Optional. Default = true
Returns: (string) A string of a comlete close position command
printBot(_bot, _command)
Print bot's information for debug purposes
Parameters:
_bot : (TradeBot) Previously instancied bot type variable
_command : (string) A command string to be debugged
Returns: Nothing.
Constants
Constants to be used in both in internal and external code
Fields:
SERVER_FROSTBOT : (string) Identifier to FrostyBot
SERVER_ZIGNALY : (string) Identifier to Zignaly
DIRECTION_LONG : (string) Flag to open a long position
DIRECTION_SHORT
LEVERAGE_CROSS : (string) Flag to set leverage to cross
LEVERAGE_ISOLATED : (string) Flag to set leverage to isolated
TradeBot
Bot type to handle its essential information
Fields:
server : (string) Type o server. Must me one of the SERVER_* constant values
id : (string) Id of the account in the server (Stub for FrostyBot or Key to Zignally)
symbol : (string) Symbol of the pair to be negotiated (example: ETH/USDT)
leverage : (int) Leverage coeficient. Default is 1
Bots
3C QFL Mean reversalWhat is QFL trading strategy?
QFL stands for Quickfingersluc, and sometimes it is referred to as the Base Strategy or Mean Reversals. Its main idea is about identifying the moment of panic selling and buying below the base level and utilizing Safety orders.
What is Base level or Support Level?
Base level or Support Level refers to the lowest price level that was reached before the moment the price started increasing again. At that level, you can notice that buyers of some cryptocurrencies make a strong reaction.
In this strategy we can also reverse the strategy and go short. But i must warn you that that is alot riskier.
QFL is meant to be used on higher TF's like 1hr, 2hr and 4hr. But this strategy also work well on lower Timeframes.
The script also simulates DCA strategy with parameters used in 3commas DCA bots for futures trading.
Experiment with parameters to find your trading setup.
Beware how large your total leveraged position is and how far can market go before you get liquidated!
Do that with the help of futures liquidation calculators you can find online!
Included:
An internal average price and profit calculating, instead of TV`s native one, which is subject to severe slippage.
A graphic interface, so levels are clearly visible and back-test analyzing made easier.
Long & Short direction of the strategy.
Table display a summary of past trades
Vertical colored lines appear when the new maximum deviation from the original price has
been reached
All the trading happens with total account capital, and all order sizes inputs are expressed in percent.
Template Trailing Strategy (Backtester)💭 Overview
💢 What is the "Template Trailing Strategy” ❓
The "Template Trailing Strategy" (TTS) is a back-tester orchestration framework. It supercharges the implementation-test-evaluation lifecycle of new trading strategies, by making it possible to plug in your own trading idea.
While TTS offers a vast number of configuration settings, it primarily allows the trader to:
Test and evaluate your own trading logic that is described in terms of entry, exit, and cancellation conditions.
Define the entry and exit order types as well as their target prices when the limit, stop, or stop-limit order types are used.
Utilize a variety of options regarding the placement of the stop-loss and take-profit target(s) prices and support for well-known techniques like moving to breakeven and trailing.
Provide well-known quantity calculation methods to properly handle risk management and easily evaluate trading strategies and compare them.
Alert on each trading event or any related change through a robust and fully customizable messaging system.
All the above, build a robust tool that, once learned, significant and repetitive work that strategy developers often implement individually on every strategy script is eliminated. Taking advantage of TradingView’s built-in backtesting engine the evaluation of the trading ideas feels natural.
By utilizing the TTS one can easily swap “trading logic” by testing, evaluating, and comparing each trading idea and/or individual component of a strategy.
Finally, TTS, through its per-event alert management (and debugging) system, provides a fully automated solution that supports automated trading with real brokers via webhooks.
NOTE: The “Template Trailing Strategy” does not dictate the way you can combine different (types of) indicators or how you should combine them. Thus, it should not be confused as a “Trading System”, because it gives its user full flexibility on that end (for better or worse).
💢 What is a “Signal Indicator” ❓
“Signal Indicator” (SI) is an indicator that can output a “signal” that follows a specific convention so that the “Template Trailing Strategy” can “understand” and execute the orders accordingly. The SI realizes the core trading logic signaling to the TTS when to enter, exit, or cancel an order. A SI instructs the TTS “when” to enter or exit, and the TTS determines “how” to enter and exit the position once the Signal Indicator generates a signal.
A very simple example of a Signal Indicator might be a 200-day Simple Moving Average Signal. When the price of the security closes above the 200-day SMA, a SI would provide TTS with a “long entry signal”. Once TTS receives the “long entry signal”, the TTS will open a long position and send an alert or automated trade message via webhook to a broker, based on the Entry settings defined in TTS. If the TTS Entry settings specify a “Market” order type, then the open long position will be executed by TTS immediately. But if the TTS Entry settings specify a “Stop” order type with a 1% Stop Distance, then when the price of the security rises by 1% after the “long entry signal” occurs, the TTS will open a long position and the Long Entry alert or webhook to the broker will be sent.
🤔 How to Guide
💢 How to connect a “signal” from a “Signal Indicator” ❓
The “Template Trailing Strategy” was designed to receive external signals from a “Signal Indicator”. In this way, a “new trading idea” can be developed, configured, and evaluated separately from the TTS. Similarly, the SI can be held constant, and the trading mechanics can change in the TTS settings and back-tested to answer questions such as, “Am I better with a different stop loss placement method, what if I used a limit order instead of a stop order to enter, what if I used 25% margin instead of trading spot market?”
To make that possible by connecting an external signal indicator to TTS, you should:
Add in the same chart, the “Signal Indicator” of your choice (e.g. “Two MA Signal Indicator” , “Click Signal Indicator” , “Signal Adapter” , “Signal Composer” ) and the “Template Trailing Strategy”.
Go to the “Settings/Inputs” tab in the “🛠️ STRATEGY” group of the TTS and change the "𝐃𝐞𝐚𝐥 𝐂𝐨𝐧𝐝𝐢𝐭𝐢𝐨𝐧𝐬 𝐌𝐨𝐝𝐞" to “🔨External”
Go to the “🔨 STRATEGY – EXTERNAL” group settings of the TTS and change the “🔌𝐒𝐢𝐠𝐧𝐚𝐥 🛈➡” to the output signal of the “Signal Indicator” you want to connect. The selected combo box option should look like “:🔌Signal to TTS” where should correspond to the short title of your “Signal Indicator”
💢 How to create a Custom Trading logic ❓
The “Template Trailing Strategy” provides two ways to plug in your custom trading logic. Both of them have their advantages and disadvantages.
✍️ Develop your own Customized “Signal Indicator” 💥
The first approach is meant to be used for relatively more complex trading logic. The advantages of this approach are the full control and customization you have over the trading logic and the relatively simple configuration setup by having two scripts only. The downsides are that you have to have some experience with pinescript or you are willing to learn and experiment. You should also know the exact formula for every indicator you will use since you have to write it by yourself. Copy-pasting from existing open-source indicators will get you started quite fast though.
The idea here is either to create a new indicator script from scratch or to copy an existing non-signal indicator and make it a “Signal Indicator”. To create a new script, press the “Pine Editor” button below the chart to open the “Pine Editor” and then press the “Open” button to open the drop-down menu with the templates. Select the “New Indicator” option. Add it to your chart to copy an existing indicator and press the source code {} button. Its source code will be shown in the “Pine Editor” with a warning on top stating that this is a read-only script. Press the “create a working copy”. Now you can give a descriptive title and a short title to your script, and you can work on (or copy-paste) the (other) indicators of your interest. Having all the information needed to make your decision the only thing you should do is define a DealConditions object and plot it like this:
import jason5480/tts_convention/4 as conv
// Calculate the start, end, cancel start, cancel end conditions
dealConditions = conv.DealConditions.new(
startLongDeal = ,
startShortDeal = ,
endLongDeal = ,
endShortDeal = ,
cnlStartLongDeal = ,
cnlStartShortDeal = ,
cnlEndLongDeal = ,
cnlEndShortDeal = )
// Use this signal in scripts like "Template Trailing Strategy" and "Signal Composer" that can use its value
// Emit the current signal value according to the "two channels mod div" convention
plot(series = conv.getSignal(dealConditions), title = '🔌Signal to TTS', color = color.olive, display = display.data_window + display.status_line, precision = 0)
You should write your deal conditions appropriately based on your trading logic and put them in the code section shown above by replacing the “…” part after “=”. You can omit the conditions that are not relevant to your logic. For example, if you use only market orders for entering and exiting your positions the cnlStartLongDeal, cnlStartShortDeal, cnlEndLongDeal, and cnlEndShortDeal are irrelevant to your case and can be safely omitted from the DealConditions object. After successfully compiling your new custom SI script add it to the same chart with the TTS by pressing the “Add to chart” button. If all goes well, you will be able to connect your “signal” to the TTS as described in the “How to connect a “signal” from a “Signal Indicator”?” guide.
🧩 Adapt and Combine existing non-signal indicators 💥
The second approach is meant to be used for relatively simple trading logic. The advantages of this approach are the lack of pine script and coding experience needed and the fact that it can be used with closed-source indicators as long as the decision-making part is displayed as a line in the chart. The drawback is that you have to have a subscription that supports the “indicator on indicator” feature so you can connect the output of one indicator as an input to another indicator. Please check if your plan supports that feature here
To plug in your own logic that way you have to add your indicator(s) of preference in the chart and then add the “Signal Adapter” script in the same chart as well. This script is a “Signal Indicator” that can be used as a proxy to define your custom logic in the CONDITIONS group of the “Settings/Inputs” tab after defining your inputs from your preferred indicators in the VARIABLES group. Then a “signal” will be produced, if your logic is simple enough it can be directly connected to the TTS that is also added to the same chart for execution. Check the “How to connect a “signal” from a “Signal Indicator”?” in the “🤔 How to Guide“ for more information.
If your logic is slightly more complicated, you can add a second “Signal Adapter” in your chart. Then you should add the “Signal Composer” in the same chart, go to the SIGNALS group of the “Settings/Inputs” tab, and connect the “signals” from the “Signal Adapters”. “Signal Composer” is also a SI so its composed “signal” can be connected to the TTS the same way it is described in the “How to connect a “signal” from a “Signal Indicator”?” guide.
At this point, due to the composability of the framework, you can add an arbitrary number (bounded by your subscription of course) of “Signal Adapters” and “Signal Composers” before connecting the final “signal” to the TTS.
💢 How to set up ⏰Alerts ❓
The “Template Trailing Strategy” provides a fully customizable per-even alert mechanism. This means that you may have an entirely different message for entering and exiting into a position, hitting a stop-loss or a take-profit target, changing trailing targets, etc. There are no restrictions, and this gives you great flexibility.
First of all, you have to enable the alerts of the events that interest you. Go to the “🔔 ALERT MESSAGES” module of the TTS settings and check the “Enable…” checkbox of the events you are interested in. For each specific event, you will find a text area where you can type the exact message you want to receive when the event occurs. What’s more, there are placeholders you can use that will be replaced by the TTS with the actual values before the message is sent. The placeholder categories are the following and the placeholder names are self-explanatory.
Chart info: {{ticker}}, {{base_currency}}, {{quote_currency}}
Quantities and percentages: {{base_quantity}}, {{quote_quantity}}, {{quote_quantity_perc}},
{{take_profit_base_quantity}}, {{remaining_quantity_perc}}, {{remaining_base_quantity}}, {{risk_perc}}
Target prices: {{stop_loss_price}}, {{entry_price}}, {{entry+_price}}, {{entry-_price}},
{{exit_price}}, {{exit+_price}}, {{exit-_price}}, {{take_profit_price_1}},
{{take_profit_price_2}}, {{take_profit_price_3}}, {{take_profit_price_4}}, {{take_profit_price_5}}
❗ To get the message on the other side you have to set a strategy alert as described here and use the {{strategy.order.alert_message}} placeholder as text in the “Message Box” that contains the message that came from the TTS.
💢 How to execute my orders in a broker ❓
To execute your orders in a broker that supports webhook integration, you should enable the appropriate alerts in the “Template Trailing Strategy” first (see the “How to set up Alerts?” guide above). Then you should go to the “Create Alert/Notifications” tab check the “Webhook URL” and paste the URL provided by your broker. You have to read the documentation of your broker for more information on what messages are expected.
Keep in mind that some brokers have deep integration with TradingView so a per-event alert approach might be overkill.
📑 Definitions
This section tries to give some definitions in terms that appear in the “Settings/Inputs" tab of the “Template Trailing Strategy”
💢 What is Trailing ❓
Trailing is a technique where a price target follows another “barrier” price (usually high or low) by trying to keep a maximum distance from the “barrier” when it moves in only one direction (up or down). When the “barrier” moves in the other direction the price target will not change. There are as many types of trailing as price targets, which means that there are entry trailing, exit trailing, stop-loss trailing, and take-profit trailing techniques.
💢 What is a Moonbag ❓
A Moonbag in a trade is the quantity of the position that is reserved and will not be exited even if all take-profit targets defined in the strategy are hit, the quantity will be exited only if the stop-loss is hit or a close signal is received. This makes the stop-loss trailing technique in a trend-following strategy a good candidate to take advantage of a Moonbag.
💢 What is Distance ❓
Distance is the difference between two prices.
💢 What is Bias ❓
Bias is a psychological phenomenon where you make decisions based on market sentiment. For example, when you want to enter a long position you have a long bias, and when you want to exit from the long position you have a short bias. It is the other way around for the short position.
💢 What is the Margin Distance of a price target ❓
The Margin Distance of a price target is the distance that the target will deviate from its initial price. The direction of this deviation depends on the bias of the market. For example, suppose you are in a long position, and you set a take-profit target to the local high (HHLL). In that case, adding a margin of five ticks will place your take-profit target 5 ticks below this local high because you have a short bias when exiting a long position. When the bias is long the margin will be added resulting in a higher target price and when you have a short bias the margin will be subtracted.
⚙️ Settings
In the “Settings/Inputs” tab of the “Template Trailing Strategy”, you can find all the customizable settings that are provided by the framework. The variety of those settings is vast; hence we will only scratch the surface here. However, for every setting, there is an information icon 🛈 where you can learn more if you mouse over it. The “Settings/Inputs” tab is divided into ten main groups. Each one of them is responsible for one module of the framework. Every setting is part of a group that is named after the module it represents. So, to spot the module of a setting find the title that appears above it comes with an emoji and uppercase letters. Some settings might have the same name but belong to different modules e.g. “Distance Method”. Some settings are indented, which means that are closely related to the non-indented setting above. Usually, intended settings provide further configuration for one or more options of the non-intended setting. The groups that correspond to each module of the framework are the following:
📆 FILTERS
In this module time filters are implemented. You can define a DateTime window for your strategy to run. You can also specify a session by selecting the days of the week and the time range you want to operate.
🛠️ STRATEGY
This module contains the "𝐃𝐞𝐚𝐥 𝐂𝐨𝐧𝐝𝐢𝐭𝐢𝐨𝐧𝐬 𝐌𝐨𝐝𝐞" that defines if the “Template Trailing Strategy” will operate using the Internal or the External (“Signal Indicator”) conditions. Some general settings can be applied regardless of the mode.
🔨 STRATEGY – EXTERNAL
This sub-module makes the connection between the external signal of the “Signal Indicator” and the “Template Trailing Strategy”. It takes effect only if the "𝐃𝐞𝐚𝐥 𝐂𝐨𝐧𝐝𝐢𝐭𝐢𝐨𝐧𝐬 𝐌𝐨𝐝𝐞" is set to “🔨External”.
🔧 STRATEGY – INTERNAL
This sub-module defines the internal strategy logic and it's used as an example to demonstrate this framework. It should produce the same results as if the “Two MA Signal Indicator” was used as a “signal” in external mode. It takes effect only if the "𝐃𝐞𝐚𝐥 𝐂𝐨𝐧𝐝𝐢𝐭𝐢𝐨𝐧𝐬 𝐌𝐨𝐝𝐞" is set to “🔧Internal”.
🎢 VOLATILITY
This module defines the volatility parameters that are used in various other settings like average true range and standard deviation. It also makes it clear whether their values are updated during a trade (DYNAMIC) or not (STATIC).
🔷 ENTRY
This module defines how the start deal conditions will be executed by defining the order type of your entry and all necessary parameters to execute them.
🎯 TAKE PROFIT
This module defines the take-profit targets placement logic. The number of the take-profit targets to use, their distance from the entry price, and the distance from each other are only some of the features that can be configured.
🛑 STOP LOSS
This module defines the stop-loss target placement logic. The distance from the entry price, move to break even, and start trailing after a take-profit target is hit are only some of the features that can be configured.
🟪 EXIT
This module defines how the end deal conditions will be executed by defining the order type of your exit and all necessary parameters to execute them.
💰 QUANTITY/RISK MANAGEMENT
This module defines the method that calculates the amount of money you will put into each trade. Also, the percentage of the Moonbag quantity can be configured.
📊 ANALYTICS
This module can visualize some extra analytics of the strategy in the chart and calculate some metrics to measure the overall performance.
🔔 ALERT MESSAGES
This module defines all the messages that can be emitted per event during the strategy execution.
😲 Caveats
💢 Does “Template Trailing Strategy” has a repainting behavior ❓
The answer is that the “Template Trailing Strategy” does not repaint as long as the “Signal Indicator” that is connected also does not repaint. If you developed your own SI make sure that you understand and know how to prevent this behavior. The publication by @PineCoders here will give you a good idea on how to avoid most of the repainting cases.
⚠️There is an exception though, when the “Enable Trail⚠️💹” checkbox is checked, the Take Profit trailing feature is enabled, and a tick-based approach is used, meaning that after a while, when the TradingView discards all the real-time data, assumptions will be made by the backtesting engine that will cause a form of repainting. To avoid making false assumptions please disable this feature in the early stages and evaluate its usefulness in your strategy later on, after first confirming the success of the logic without this feature. In this case, consider turning on the bar magnifier feature. This way you will get more accurate backtest results when the Take Profit trailing feature is enabled.
💢 Can “Template Trailing Strategy” satisfy all my trading strategies ❓
While this framework can satisfy quite a large number of trading strategies there are cases where it cannot do so. For example, if you have a custom logic for your stop-loss or take-profit placement, or if you want to dollar cost average, then it might be better to start a new strategy script from scratch.
⚠️ It is not recommended to copy the official TTS code and start developing unless you are a pine wizard! Even in that case, there is a stiff learning curve that might not be worth your time. Last, you must consider that I do not offer support for customized versions of the TTS script and if something goes wrong in the process you are all alone.
🤗 Thanks
Special thanks to @upslidedown and @metadimensional, who regularly gave feedback all those years and helped me to shape the framework as it is today! Thanks to @EltAlt, @PlusUltraTrading, and everyone else who contributed by either filing a “defect report” or asking questions that helped me to understand what improvements were necessary.
Enjoy!
Jason
DCA Bot IndicatorName: DCA Bot Indicator
Category: Dollar Cost Average.
Operating mode: Alerts at a specific time, day of the week and day of the month.
Trades duration: N/A.
Timeframe: 1H
Suggested usage: long-term investing DCA strategies.
Entry: Only indicates the time and then the day of the week or the day of the month to buy.
Exit: As per long-term Investor’s strategy.
Usage: If you want to perform a Dollar Cost Averaging approach with:
- Daily purchases (at a specific time)
- Weekly purchases (at a specific time and day of the week)
- Monthly purchases (at a specific time and day of the month)
It is then possible to set the alert text with a preferred message or for use with trade automation systems. The green background identify the specific time chosen.
It is possible to identify through the Bias Analyzer the best time for the daily purchase.
Configuration:
- Buy Time: hour you would like to buy, please consider that the script is executed at the end of the defined time, so if you would like to buy at 2, have to put 1.
- Buy only Days of the Week: you can select the day you want.
- Buy only on Day of Month, you can specify a specific day.
Credits:
- dsteaves for inspiration
DCA RSI Add funds exit simulatorThis script helps with planning on how to exit DCA deals that are in the negative.
The following deal information is required
- Current average position price
- Funds invested
- Required take profit
Additional indicator settings are
- The date/time on which to start the simulator
- Minimum deviation % to start adding funds
- Expected bounceback from when funds are added
The RSI trigger
Adding funds is triggered when the selected RSI settings yield a value that is at or beyond the selected threshold.
How it works
The amount of funds needed are calculated based on the supplied settings, such that the new average price matches the expected bounceback.
It will also show if the exit strategy has failed to hit the TP (this happens when the RSI threshold is hit again)
DCA Bot Long/Short Thanks to @TheTradingParrot for the inspiration and knowledge shared.
Thanks to @ericlin0122 for the original DCA Bot Emulator which is the backbone of this strategy.
The script simulates DCA strategy with parameters used in 3commas DCA bots for futures trading. Experiment with parameters
to find your trading setup.
Beware how large your total leveraged position is and how far can market go before you get liquidated!
Do that with the help of futures liquidation calculators you can find online!
I`ve added:
1) an internal average price and profit calculating, instead of TV`s native one, which is subject to severe slippage.
2) I`ve built a graphic interface, so levels are clearly visible and back-test analyzing made easier.
3) now both Long & Short direction of the strategy exist.
4) trailing TP which was featured in the initial script has been removed because TV`s execution model makes
it impossible to know how the real world trailing would have unfolded.
5) the table is self explanatory, and it is there to help you discover what happened and where.
6) vertical colored lines appear when the new maximum deviation from the original price has
been reached
All the trading happens with total account capital, and all order sizes inputs are expressed in percent.
Known issues:
When deviation is small, and the same candle triggers safety AND the close order, the initial orders are closed, but a
new one opens on the next candle. This is "resolved" by closing the unwanted trade forcefully on the next candle, affecting
profit calculating minimally and guaranteeing that what should be closed has been closed.
The code could be improved through use of arrays, making the table flexible so the number of rows should be dynamic depending
on the number of SOs.
!!!!! IMPORTANT!!!!!
This strategy script is made to receive a signal from an exterior study script, which should plot +100 for long or -100 for short
entry (that is by default - values can be changed in the strategy settings menu). That plot should be found in "Enter Trigger" input
dropdown menu at the bottom of strategy settings menu. Removing the "and trigger == long/short_trigger" condition from strategy entry
conditions makes the strategy open trades ASAP.
Cheers!
Zendog V2 backtest DCA bot 3commasHi everyone,
After a few iterations and additional implemented features this version of the Backtester is now open source.
The Strategy is a Backtester for 3commas DCA bots. The main usage scenario is to plugin your external indicator, and backtest it using different DCA settings.
Before using this script please make sure you read these explanations and make sure you understand how it works.
Features:
- Because of Tradingview limitations on how orders are grouped into Trades, this Strategy statistics are calculated by the script, so please ignore the Strategy Tester statistics completely
Statistics Table explained:
- Status: either all deals are closed or there is a deal still running, in which case additional info
is provided below, as when the deal started, current PnL, current SO
- Finished deals: Total number of closed deals both Winning and Losing.
A deal is comprised as the Base Order (BO) + all Safety Orders (SO) related to that deal, so this number
will be different than the Strategy Tester List of Trades
- Winning Deals: Deal ended in profit
- Losing deals: Deals ended with loss due to Stop Loss. In the future I might add a Deal Stop condition to
the script, so that will count towards this number as well.
- Total days ( Max / Avg days in Deal ):
Total Days in the Backtest given by either Tradingview limitation on the number of candles or by the
config of the script regarding "Limit Date Range".
Max Days spent in a deal + which period this happened.
Avg days spent in a deal.
- Required capital: This is the total capital required to run the Backtester and it is automatically calculated by
the script taking into consideration BO size, SO size, SO volume scale. This should be the same as 3commas.
This number overwrites strategy.initial_capital and is used to calculate Profit and other stats, so you don't need
to update strategy.initial_capital every time you change BO/SO settings
- Profit after commission
- Buy and Hold return: The PnL that could have been obtained by buying at the close of the first candle of the
backtester and selling at the last.
- Covered deviation: The % of price move from initial BO order covered by SO settings
- Max Deviation: Biggest market % price move vs BO price, in the other direction (for long
is down, for short it is up)
- Max Drawdown: Biggest market % price move vs Avg price of the whole Trade (BO + any SO), in the other
direction (for long price goes down, for short it goes up)
This is calculated for the whole Trade so it is different than List of Trades
- Max / Avg bars in deal
- Total volume / Commission calculated by the strategy. For correct commission please set Commission in the
Inputs Tab and you may ignore Properties Tab
- Close stats for deals: This is a list of how many Trades were closed at each step, including Stop Loss (if
configured), together with covered deviation for that step, the number of deals, and the percentage of this
number from all the deals
TODO: Might add deal avg value for each step
- Settings Table that can be enabled / disabled just to have an overview of your configs on the chart, this is a
drawn on bottom left
- Steps Table similar to 3commas, this is also drawn on bottom left, so please disable Settings table if you want
to see this one
TODO: Might add extra stats here
- Deal start condition: built in RSI-7 or plugin any external indicator and compare with any value the indicator plots
(main purpose of this strategy is to connect your own studies, so using external indicator is recommended)
- Base order and safety orders configs similar to 3commas (order size, percent deviation, safety orders,
percent scale and volume scale)
- Long and Short
- Stop Loss
- Support for Take profit from base order or from Total volume of the deal
- Configs help (besides self explanatory):
- Chart theme: Adjust according to the theme you run on. There is no way to detect theme at the moment.
This adjust different colors
- Deal Start Type: Either a builtin RSI7 or "External indicator"
- Indicator Source an value: If using External Indicator then select source, comparison and value.
For example you could start a deal when Volume is greater than xxxx, or code a custom indicator that plots
different values based on your conditions and test those values
- Visuals / Decimals for display: Adjust according to your symbol
- BO Entry Price for steps table: This is the BO start deal price used to calculate the steps in the table
3CCI & 3RSI for botsThis script is for trading grid bots. Only CCI and RSI are used, but there are three different timeframes available for each. When using it, you must select a chart with a period equal to or less than the minimum in the indicator settings. For example, the following periods are selected in the settings: 1 hour, 15 minutes, 5 minutes, so we use a 5-minute chart. A buy or sell signal will be received if the settings of all 6 indicators match. The default settings do not carry any information, use your own. The code is quite simple and may be of interest to a beginner like me.
Alert for 3Commas Bollinger StrategyThis is just an alert for the 3Commas Bollinger Strategy written by tedwardd
Backtesting 3commas DCA Bot v2Updating previously published simulated 3commas DCA logic with a sexier insert and more meaningful default parameters.
Bollinger Bands + RSI Alerts for 3commas/DCA botHey Folks !
This is in indicator that generates buy alerts combining Bollinger Bands and RSI.
RSI validates the BB signal by confirming we are not in an oversold area.
Interval: 3m to 15m
Recommended settings for 3commas DCA bot
- TP/TTP: 0.3%/0.1%,
- Base Order: Your choice ,
- Safety Order: 1.2 * Your choice of base order
- Safety Order Volume Scale: 1.2,
- Safety Order Step Scale: 1.5,
- Price Deviation to Open Safety Order (% from initial order): 0.25%,
- Max Safety Trades Count: 7
- DO NOT USE STOP LOSS
> Create Alert with Buy Alert and link it to "Message for deal start signal"
LordPepe Stochastic SignalsThis is the Lord Pepe. Howdy. Basic buy/sell indicator to accumulate along a downtrend and release your stack during the uptrend and oversold levels of the stochastic. The buys should be used to stack, and sells indicate levels of profit taking, they do not signal a long term reversal, only < 25% of stack should be released on "OB" signals.
OB - overbought (sell)
OS - oversold (buy)
ck - EMA Cross with AlertsDisplays 5 popular EMAs (you can hide any you don’t want to see from the “Styles” screen when editing the config).
Set the values for your EMAs by clicking the cog after adding this indicator to your chart.
A Long or Short signal is fired when EMA1 crosses EMA2 - a cross up is a Long signal, a cross down is a Short signal.
Connect to your Bots (3commas / 3C.exchange recommended) to automate buys and sells!
ck - Ultimate Oscillator & RSI Indicator v1Hi,
This is an indicator that combines the Ultimate Oscillator with RSI.
Currently it displays signals on the screen when the RSI crosses from low to high (to open and close a long) and vice versa for short signals.
Further signals will be developed for Ultimate Oscillator longs/shorts.
Stay tuned!
3 EMAs with Crossing Alerts & 2 SMAsHi all,
This is a simple indicator that plots 3 EMA lines and 2MAs of your choice to the screen and has built in alert triggers.
Features:
1) Alerts are triggered when EMAs 1 (Signal line) and 2 (Baseline) cross - a Long signal is called if the cross is above EMA 3 ( Trendline ), a short if the cross is below EMA3
2) Signals are represented visually as a triangle on the chart, below the candles is a long, above is a short
3) TradingView Alerts can be easily set as I have labelled the signals clearly as many other Indicators like this aren’t easy to work out if trying to create alerts to trigger a 3commas bot, for example!
Each EMA is fully customisable and if you wish to take advantage of the alerts, only a few simple rules need to be followed:
EMA1 needs to be less than EMA2.
EMA2 needs to be the same or greater than EMA3
That’s it, happy trading!
Brandon BollSecond day at Pinescript and I am attempting to tweak the Bollinger Bands directed strategy to send alerts to Zignaly in order to automate long buy/sells.
I've left in the short script though for completeness.
The buy and sell instructions work perfectly but I don't know how to do a cancel order alert (as included in the original strategy)
5 EMAs plus Crossing AlertsHi all,
This is a simple indicator that plots 5 EMA lines of your choice to the screen.
Can be used to trigger scalping Bots (stoploss around 0.5% recommended, take profit 1% or higher, please backtest!)
Also can be used for manual scalping, 1 or 2 candles at a time.
Features:
1) Alerts are triggered when EMAs 1 (Signal line) and 2 (Baseline) cross - a Long signal is called if the cross is above EMA 3 (Trendline), a short if the cross is below EMA3
2) Signals are represented visually as a triangle on the chart, below the candles is a long, above is a short
3) TradingView Alerts can be easily set as I have labelled the signals clearly as many other Indicators like this aren’t easy to work out if trying to create alerts to trigger a 3commas bot, for example!
Each EMA is fully customisable and if you wish to take advantage of the alerts, only a few simple rules need to be followed:
EMA1 needs to be less than EMA2.
EMA2 needs to be the same or greater than EMA3
That’s it, happy trading!
Big shout out to B and the gang over at Crypto Trading Group!
EMA Bot Trigger - 14,26,55Work In Progress - Currently will send Long/Short triggers when EMA 14 Crosses EMA 26 - whether the cross is above the EMA 55 determines whether to Long or Short.
Eds Bot Signaler on Basis of RSI Stoch StochRSIEDS AWESOME BOT SIGNALER
Specially for use with e.g. 3commas or autoview
But can also be used just in normal manual (visual) mode
This Script is very early Beta. Works for visual manual use....
and also for 3Commas Bot as "Signaler" (how to connect with Bot, see the docu on 3commas).
... but can use as Signaler for any Bot who is able to get Tradingview sms-mails. (e.g. autoview)
It combines RSI, Stoch and Stoch-RSI.
You can choose normal RSI, or " returning RSI " (signals when leaving the sell/buy-zone. much higher profits with this)
You can choose how many of the indicators are needed to "fire".
You can choose if one of the indicators is a "must"
For Stoch & Stoch-RSI you can Choose sma or ema calculations of the moving average.
All the Values speak for themselves, if you are used to technical analyses (stay away in the moment, if you dont know, what rsi, stoch etc is used.
The Signals are also shown in the chart, the single ones, but also the combined which fires the Bot-Signal (shown as green and red column-candle at bottom)
Enjoy !! Free use in the moment.
More detailled Explanation in the future. Just play around!
If you wanna give something back:
BTC: 15buigKjh4JYnuVwcEWiYMpYvP3Lbp4ypL
Dotenslayer : An open range breakouts method indicator for botThis script shows the long and short points of certain Japanese bots like 'DotenKun' which use open range breakouts method.
Searching recent 18 bars as default and shows the range calculated with a factor (default k = 1.6). You can edit this condition by yourself.
When filled the long or short conditions, also shows the indicator on the price chart to help your trading on BTC.
Also, this script can make alarm events related to those conditions.
This script only works for BTCUSD, XBTUSD, BTCJPY, FXBTCJPY with 1H time span.
Disclaimer :
I don't own the source code of the certain bots and I didn't directly reference the source code of it.
So which means, I don't guarantee this script works as same as the bots works.
Also, I didn't mean to disturb their trading bot businesses.
Your donations are welcome! :
BTC : 327MqYGfHJFC7LRijGwQZXdTAyFwvYCzyv
ETH : 0x5E270c3667E65ba6158D292a98c5b54F81AfCAf1
Progressive Profit Taking with Trailing StopThis is version 2 of
Special features:
Added partial profit taking as price rises. Profit taking is triggered by price crossing an EMA.
After profit taking, price has to rise by a user-specified percent before taking profits again.
Also includes condition for fully closing position after meeting specified profit target.
To incorporate into your algo, turn the plotshape functions into alertcondition.