FreedX Grid Backtest█ FreedX Grid Backtest is an open-source tool that offers accurate GRID calculations for GRID trading strategies. This advanced tool allows users to backtest GRID trading parameters with precision, accurately reflecting exchange functionalities. We are committed to enhancing trading strategies through precise backtesting solutions and address the issue of unreliable backtesting practices observed on GRID trading strategies. FreedX Grid Backtest is designed for optimal calculation speed and plotting efficiency, ensuring users to achieve fastest calculations during their analysis.
█ GRID TRADING STRATEGY SETTINGS
The core of the FreedX Grid Backtest tool lies in its ability to simulate grid trading strategies. Grid trading involves placing orders at regular intervals within a predefined price range, creating a grid of orders that capitalize on market volatility.
Features:
⚙️ Backtest Range:
→ Purpose: Allows users to specify the backtesting range of GRID strategy. Closes all positions at the end of this range.
→ How to Use: Drag the dates to fit the desired backtesting range.
⚙️ Investment & Compounding:
→ Purpose: Allows users to specify the total investment amount and select between fixed and compound investment strategies. Compounding adjusts trade quantities based on performance, enhancing the grid strategy's adaptability to market changes.
→ How to Use: Set the desired investment amount and choose between "Fixed" or "Compound" for the investment method.
⚙️ Leverage & Grid Levels:
→ Purpose: Leverage amplifies the investment amount, increasing potential returns (and risks). Users can define the number of grid levels, which determines how the investment is distributed across the grid.
→ How to Use: Input the desired leverage and number of grids. The tool automatically calculates the distribution of funds across each grid level.
⚙️ Distribution Type & Mode:
→ Purpose: Users can select the distribution type (Arithmetic or Geometric) to set how grid levels are determined. The mode (Neutral, Long, Short) dictates the direction of trades within the grid.
→ How to Use: Choose the distribution type and mode based on the desired trading strategy and market outlook.
⚙️ Enable LONG/SHORT Grids exclusively:
█ MANUAL LEVELS AND STOP TRIGGERS
Beyond automated settings, the tool offers manual adjustments for traders seeking finer control over their grid strategies.
Features:
⚙️ Manual Level Adjustment:
→ Purpose: Enables traders to manually set the top, reference, and bottom levels of the grid, offering precision control over the trading range.
→ How to Use: Activate manual levels and adjust the top, reference, and bottom levels as needed to define the grid's scope.
⚙️ Stop Triggers:
→ Purpose: Provides an option to set upper and lower price limits, acting as stop triggers to close or terminate trades. This feature safeguards investments against significant market movements outside the anticipated range.
→ How to Use: Enable stop triggers and specify the upper and lower limits. The tool will automatically manage positions based on these parameters.
---
This guide gives you a quick and clear overview of the FreedX Grid Backtest tool, explaining how you can use this cutting-edge tool to improve your trading strategies.
Gridtrading
Grid Bot BacktestingBinance, Bybit, Bitget, and other cross-exchange (grid) trading bot backtesting.
Auto bound: Automatically setting upper and lower price bounds.
Manual: Setting upper and lower price bounds manually.
The graph below represents the overall asset changes (initial investment amount + current position profit + grid profit).
Try using backtesting when setting up a grid bot on the exchange!
바이낸스, 바이비트, 비트겟 등 교차거래(그리드) 봇 백테스팅
Auto bound : 자동으로 상,하단 가격 설정
Manual : 직접 상,하단 가격 설정
아래 그래프는 총 자산 변화입니다.(초기투자금액 + 현재 포지션 수익 + 그리드 수익)
거래소에서 그리드 봇 설정할 때 백테스팅 유용하게 써보세요!
Hulk Grid Algorithm V2 - The Quant ScienceIt's the latest proprietary grid algorithm developed by our team. This software represents a clearer and more comprehensive modernization of the deprecated Hulk Grid Algorithm. In this new release, we have optimized the source code architecture and investment logic, which we will describe in detail below.
Overview
Hulk Grid Algorithm V2 is designed to optimize returns in sideways market conditions. In this scenario, the algorithm divides purchases with long orders at each level of the grid. Unlike a typical grid algorithm, this version applies an anti-martingale model to mitigate volatility and optimize the average entry price. Starting from the lower level, the purchase quantity is increased at each new subsequent level until reaching the upper level. The initial quantity of the first order is fixed at 0.50% of the initial capital. With each new order, the initial quantity is multiplied by a value equal to the current grid level (where 1 is the lower level and 10 is the upper level).
Example: Let's say we have an initial capital of $10,000. The initial capital for the first order would be $50 * 1 = $50, for the second order $50 * 2 = $100, for the third order $50 * 3 = $150, and so on until reaching the upper level.
All previously opened orders are closed using a percentage-based stop-loss and take-profit, calculated based on the extremes of the grid.
Set Up
As mentioned earlier, the user's goal is to analyze this strategy in markets with a lack of trend, also known as sideways markets. After identifying a price range within which the asset tends to move, the user can choose to create the grid by placing the starting price at the center of the range. This way, they can consider trading the asset, if the backtesting generates a return greater than the Buy & Hold return.
Grid Configuration
To create the grid, it's sufficient to choose the starting price during the launch phase. This level will be the center of the grid from which the upper and lower levels will be calculated. The grid levels are computed using an arithmetic method, adding and subtracting a configurable fixed amount from the user interface (Grid Step $).
Example: Let's imagine choosing 1000 as the starting price and 50 as the Grid Step ($). The upper levels will be 1000, 1050, 1100, 1150, 1200. The lower levels will be 950, 900, 850, 800, and 750.
Markets
This software can be used in all markets: stocks, indices, commodities, cryptocurrencies, ETFs, Forex, etc.
Application
With this backtesting software, is possible to analyze the strategy and search for markets where it can generate better performance than Buy & Hold returns. There are no alerts or automatic investment mechanisms, and currently, the strategy can only be executed manually.
Design
Is possible to modify the grid style and customize colors by accessing the Properties section of the user interface.
Martingale + Grid DCA Strategy [YinYangAlgorithms]This Strategy focuses on strategically Martingaling when the price has dropped X% from your current Dollar Cost Average (DCA). When it does Martingale, it will create a Purchase Grid around this location to likewise attempt to get you a better DCA. Likewise following the Martingale strategy, it will sell when your Profit has hit your target of X%.
Martingale may be an effective way to lower your DCA. This is due to the fact that if your initial purchase; or in our case, initial Grid, all went through and the price kept going down afterwards, that you may purchase more to help lower your DCA even more. By doing so, you may bring your DCA down and effectively may make it easier and quicker to reach your target profit %.
Grid trading may be an effective way of reducing risk and lowering your DCA as you are spreading your purchases out over multiple different locations. Likewise we offer the ability to ‘Stack Grids’. What this means, is that if a single bar was to go through 20 grids, the purchase amount would be 20x what each grid is valued at. This may help get you a lower DCA as rather than creating 20 purchase orders at each grid location, we create a single purchase order at the lowest grid location, but for 20x the amount.
By combining both Martingale and Grid DCA techniques we attempt to lower your DCA strategically until you have reached your target profit %.
Before we start, we just want to make it known that first off, this Strategy features 8% Commission Fees, you may change this in the Settings to better reflect the Commission Fees of your exchange. On a similar note, due to Commission Fees being one of the number one profit killers in fast swing trade strategies, this strategy doesn’t focus on low trades, but the ideology of it may result in low amounts of trades. Please keep in mind this is not a bad thing. Since it has the ability to ‘Stack Grid Purchases’ it may purchase more for less and result in more profit, less commission fees, and likewise less # of trades.
Tutorial:
In this example above, we have it set so we Martingale twice, and we use 100 grids between the upper and lower level of each martingale; for a total of 200 Grids. This strategy will take total capital (initial capital + net profit) and divide it by the amount of grids. This will result in the $ amount purchased per grid. For instance, say you started with $10,000 and you’ve made $2000 from this Strategy so far, your total capital is $12,000. If you likewise are implementing 200 grids within your Strategy, this will result in $12,000 / 200 = $60 per grid. However, please note, that the further down the grid / martingale is, the more volume it is able to purchase for $60.
The white line within the Strategy represents your DCA. As the Strategy makes purchases, this will continue to get lower as will your Target Profit price (Blue Line). When the Close goes above your Target Profit price, the Strategy will close all open positions and claim the profit. This profit is then reinvested back into the Strategy, which may exponentially help the Strategy become more profitable the longer it runs for.
In the example above, we’ve zoomed in on the first example. In this we want to focus on how the Strategy got back into the trades shortly after it sold. Currently within the Settings we have it set so our entry is when the Lowest with a length of 3 is less than the previous Lowest with a length of 3. This is 100% customizable and there are multiple different entry options you can choose from and customize such as:
EMA 7 Crossover EMA 21
EMA 7 Crossunder EMA 21
RSI 14 Crossover RSI MA 14
RSI 14 Crossunder RSI MA 14
MFI 14 Crossover MFI MA 14
MFI 14 Crossunder MFI MA 14
Lowest of X Length < Previous Lowest of X Length
Highest of X Length > Previous Highest of X Length
All of these entry options may be tailored to be checked for on a different Time Frame than the one you are currently using the Strategy on. For instance, you may be running the Strategy on the 15 minute Time Frame yet decide you want the RSI to cross over the RSI MA on the 1 Day to be a valid entry location.
Please keep in mind, this Strategy focuses on DCA, this means you may not want the initial purchase to be the best location. You may want to buy when others think it is a good time to sell. This is because there may be strong bearish momentum which drives the price down drastically and potentially getting you a good DCA before it corrects back up.
We will continue to add more Entry options as time goes on, and if you have any in mind please don’t hesitate to let us know.
Now, back to the example above, if we refer to the Yellow circle, you may see that the Lowest of a length of 3 was less than its previous lowest, this triggered the martingales to create their grids. Only a few bars later, the price went into the first grid and went a little lower than its midpoint (Yellow line). This caused about 60% of the first grid to be purchased. Shortly after the price went even lower into this grid and caused the entire first martingale grid to be purchased. However, if you notice, the white line (your DCA) is lower than the midpoint of the first grid. This is due to the fact that we have ‘Stack Grid Purchases’ enabled. This allows the Strategy to purchase more when a single bar crosses through multiple grid locations; and effectively may lower your average more than if it simply executed a purchase order at each grid.
Still looking at the same location within our next example, if we simply increase the Martingale amount from 2 to 3 we can see something strange happens. What happened is our Target Profit price was reached, then our entry condition was met, which caused all of the martingale grids to be formed; however, the price continued to increase afterwards. This may not be a good thing, sure the price could correct back down to these grid locations, but what if it didn’t and it just kept increasing? This would result in this Strategy being stuck and unable to make any trades. For this reason we have implemented a Failsafe in the Settings called ‘Reset Grids if no purchase happens after X bars’.
We have enabled our Failsafe ‘Reset Grids if no purchase happens after X bars’ in this example above. By default it is set to 100 bars, but you can change this to whatever works best for you. If you set it to 0, this Failsafe will be disabled and act like the example prior where it is possible to be stuck with no trades executing.
This Failsafe may be an important way to ensure the Strategy is able to make purchases, however it may also mean the Grids increase in price when it is used, and if a massive correction were to occur afterwards, you may lose out on potential profit.
This Strategy was designed with WebHooks in mind. WebHooks allow you to send signals from the Strategy to your exchange. Simply set up a Custom TradingView Bot within the OKX exchange or 3Commas platform (which has your exchange API), enter the data required from the bot into the settings here, select your bot type in ‘Webhook Alert Type’, and then set up the alert. After that you’re good to go and this Strategy will fully automate all of its trades within your exchange for you. You need to format the Alert a certain way for it to work, which we will go over in the next example.
Add an alert for this Strategy and simply modify the alert message so all it says is:
{{strategy.order.alert_message}}
Likewise change from the Alert ‘Settings’ to Alert ‘Notifications’ at the top of the alert popup. Within the Notifications we will enable ‘Webhook URL’ and then we will pass the URL we are sending the Webhook to. In this example we’ve put OKX exchange Webhook URL, however if you are using 3Commas you’ll need to change this to theirs.
OKX Webhook URL:
www.okx.com
3Commas Webhook URL:
app.3commas.io
Make sure you click ‘Create’ to actually create this alert. After that you’re all set! There are many Tutorials videos you can watch if you are still a little confused as to how Webhook trading works.
Due to the nature of this Strategy and how it is designed to work, it has the ability to never sell unless there it will make profit. However, because of this it also may be stuck waiting in trades for quite a long period of time (usually a few months); especially when your Target Profit % is 15% like in the example above. However, this example above may be a good indication that it may maintain profitability for a long period of time; considering this ‘Deep Backtest’ is from 2017-8-17.
We will conclude the tutorial here. Hopefully you understand how this Strategy has the potential to make calculated and strategic DCA Grid purchases for you and then based on a traditional Martingale fashion, bulk sell at the desired Target Profit Percent.
Settings:
Purchase Settings:
Only Purchase if its lower than DCA: Generally speaking, we want to lower our Average, and therefore it makes sense to only buy when the close is lower than our current DCA and a Purchase Condition is met.
Purchase Condition: When creating the initial buy location you must remember, you want to Buy when others are Fearful and Sell when others are Greedy. Therefore, many of the Buy conditions involve times many would likewise Sell. This is one of the bonuses to using a Strategy like this as it will attempt to get you a good entry location at times people are selling.
Lower / Upper Change Length: This Lower / Upper Length is only used if the Purchase Condition is set to 'Lower Changed' or 'Upper Changed'. This is when the Lowest or Highest of this length changes. Lowest would become lower or Highest would become higher.
Purchase Resolution: Purchase Resolution is the Time Frame that the Purchase Condition is calculated on. For instance, you may only want to start a new Purchase Order when the RSI Crosses RSI MA on the 1 Day, but yet you run this Strategy on the 15 minutes.
Sell Settings:
Trailing Take Profit: Trailing Take Profit is where once your Target Profit Percent has been hit, this will trail up to attempt to claim even more profit.
Target Profit Percent: What is your Target Profit Percent? The Strategy will close all positions when the close price is greater than your DCA * this Target Profit Percent.
Grid Settings:
Stack Grid Purchases: If a close goes through multiple Buy Grids in one bar, should we amplify its purchase amount based on how many grids it went through?
Reset Grids if no purchase happens after X Bars: Set this to 0 if you never want to reset. This is very useful in case the price is very bullish and continues to increase after our Target Profit location is hit. What may happen is, Target Profit location is hit, then the Entry condition is met but the price just keeps increasing afterwards. We may not want to be sitting waiting for the price to drop, which may never happen. This is more of a failsafe if anything. You may set it very large, like 500+ if you only want to use it in extreme situations.
Grid % Less than Initial Purchase Price: How big should our Buy Grid be? For instance if we bought at 0.25 and this value is set to 20%, that means our Buy Grid spans from 0.2 - 0.25.
Grid Amounts: How many Grids should we create within our Buy location?
Martingale Settings:
Amount of Times 'Planned' to Martingale: The more Grids + the More Martingales = the less $ spent per grid, however the less risk. Remember it may be better to be right and take your time than risk too much and be stuck too long.
Martingale Percent: When the current price is this percent less than our DCA, lets create another Buy Grid so we can lower our average more. This will make our profit location less.
Webhook Alerts:
Webhook Alert Type: How should we format this Alert? 3Commas and OKX take their alerts differently, so please select the proper one or your webhooks won't work.
3Commas Webhook Alerts:
3Commas Bot ID: The 3Commas Bot ID is needed so we know which BOT ID we are sending this webhook too.
3Commas Email Token: The 3Commas Email Token is needed for your webhooks to work properly as it is linked to your account.
OKX Webhook Alerts:
OKX Signal Token: This Signal Token is attached to your OKX bot and will be used to access it within OKX.
If you have any questions, comments, ideas or concerns please don't hesitate to contact us.
HAPPY TRADING!
RSI Box Strategy (pseudo- Grid Bot)This is a strategy intended primarily for algorithmic traders. It's a pseudo-grid bot that uses a dynamic, volume-weighted grid that only updates when the RSI meets certain conditions. It's also a breakout strategy, whereas normal grid bots are not (typical grid bots sell when a higher grid is reached, whereas this strategy sells when a lower grid is breached under specific conditions). This strategy also sells 100% of pyramiding orders on close.
In a nutshell, the strategy updates its grid to the volume-weighted highest/lowest values of your given source ("src" in the settings) each time that there is a RSI crossunder/crossover. From this range it produces an evenly-spaced grid of five lines, and uses the current source to determine which grid line is closest to the source. Then, if the source crosses over the line directly above the current line, it enters a buy order. If the source crosses under the line directly below the current line, it enters a sell order.
You can configure shorts, source, RSI length, and overbought/oversold levels in the settings.
For the strategy results below: fees are at 0.1% per trade, with order size 1% of equity and a max pyramiding value of 33. For a greater R/R profile, you can increase the order size, which will increase drawdown but potentially yield better results.
Grid Spot Trading Algorithm V2 - The Quant ScienceGrid Spot Trading Algorithm V2 is the last grid trading algorithm made by our developer team.
Grid Spot Trading Algorithm V2 is a fixed 10-level grid trading algorithm. The grid is divided into an accumulation area (red) and a selling area (green).
In the accumulation area, the algorithm will place new buy orders, selling the long positions on the top of the grid.
BUYING AND SELLING LOGIC
The algorithm places up to 5 limit orders on the accumulation section of the grid, each time the price cross through the middle grid. Each single order uses 20% of the equity.
Positions are closed at the top of the grid by default, with the algorithm closing all orders at the first sell level. The exit level can be adjusted using the user interface, from the first level up to the fifth level above.
CONFIGURING THE ALGORITHM
1) Add it to the chart: Add the script to the current chart that you want to analyze.
2) Select the top of the grid: Confirm a price level with the mouse on which to fix the top of the grid.
3) Select the bottom of the grid: Confirm a price level with the mouse on which to fix the bottom of the grid.
4) Wait for the automatic creation of the grid.
USING THE ALGORITHM
Once the grid configuration process is completed, the algorithm will generate automatic backtesting.
You can add a stop loss that destroys the grid by setting the destruction price and activating the feature from the user interface. When the stop loss is activated, you can view it on the chart.
AUTOMATIC GRID BOT STRATEGY [ilovealgotrading]
OVERVIEW:
This Grid trading strategy can help you maximize your profit in a ranging sideways market with no clear direction.
INDICATOR:
We can get some money by taking advantage of the movement of the price between the range we have determined.
Short positions are opened while the price is rising, long positions are opened while the price is falling.
Therefore, there is no need to predict the trend direction.
What is different in this indicator:
I want to say thank you to © thequantscience. His GRID SPOT TRADING ALGORITHM - GRID BOT TRADING strategy helped me when I was writing my indicator.
I want to explain what I have improved:
1- Grid strategy is a type of strategy that can be traded in very short time frames and users can trade this strategy algorithmically by connecting this strategy to their own accounts with the help of API systems. For this reason, I have developed a software that can give us signals by dynamically changing the long and short messages when users are trading.
2- We can change the start and end dates of our grid bot as we want. It is necessary to use this setting when setting up automatic bots, so that previously opened transactions are not taken into account.
3 - Lot or quantity size should not be excessively small when users are taking automatic trades because exchanges have limitations, to avoid this problem, I have prevented this error by automatically rounding up to the nearest quantity size inside the software.
4 - Users can avoid excessive losses by using stop loss on this grid bot if they wish.
5 - When our price is over the range high or below the range low, our open positions are closed, if the stop button is active. We can also change which close price time frame we take as a basis from the settings.
6 -Users can set how many dollars they can enter per transaction while performing their transactions automatically.
IMPLEMENTATION DETAILS – SETTINGS:
This script allows the user to choose the highs and lows leves of our range. Our bot trades in the specified range.
1. This strategy allows us to set start and end backtest dates.
2. We can change range high and range low leves of our bot
3. IF people want to trade algorithmically with the help of this bot, there are 6 different input systems that will receive the Json codes as an alarm
4. IF the price closes above the upper line or below the lower line, all transactions will be closed. We can determine in which time frame our transactions will be stopped if the price closes outside these levels.We can adjust how our bot works by activating or turning off the Stop Loss button.
5. In this strategy, you can determine your dollar cost for per position.
6. The user can also divide the interval we have determined into 10 parts or 20 equal parts.
7. The grid is divided and colored at the interval we set. At the same time, if we don't want we can turn off colored channels.
Notes:
If you're going to connect this bot to an automatic Long and Short direction,
Don’t forget! you need to Webhook URL,
Don’t miss paste this code to your message window {{strategy.order.alert_message}}
ALSO:
Set your range below the support zones and above the resistance zones.
Don't be afraid to take a wide range, it doesn't matter if you make a little money, the important thing is that you don't lose money.
If you have any ideas what to add to my work to add more sources or make calculations cooler, suggest in DM .
basilGrid GridBot Live [basilChart]This strategy is a full implementation of Live Grid Trading.
Prominent features of this live grid trading strategy are:
- Logarithmic Chart Support: This strategy can support Log Scale on graph. Meaning that grid lines won't have irregular gaps in between the lines if you would like to view the chart Log Scaled. Every line will be aligned correctly even if you use Log Scale or not.
- Precise Buy & Sell: Script will execute precise Buy and Sell orders.
- Dynamic Grid Level Count: From 2 grid levels to n amount of grid levels are supported. There is no limitation on grid level count, however there may be irregularities because of limitations when higher grid levels are used. You can pick any number starting from 2.
- Average Price: Traders can monitor average price of positions.
- Alerts: When order is filled trader can receive notification. Create new alert > Select basilGrid Live > Order fills only()
Characteristics of this script:
- Able to fill more than one order in one single candle.
- Levels will keep being updated with every trade.
- There will be always one grid level ignored and it will be the level which made the last order filling possible. This is normal behavior of grid trading system.
- You can both use Log Scale and Normal Scale with this script. No issue will be on grid levels.
Using the script:
- Add this script to the chart from indicators tab
- Set starting date for the live grid bot either by dragging and dropping the vertical line or by the date-time picker from indicator Inputs tab.
- Set highest and lowest limit for the script. These will be the boundary limits. Highest and lowest price for the script to work on. Lines will populate between these two values
- Set grid level count. Number of levels of the grid.
- Set amount to spend on per level. This quantity of order will be placed on each level when needed.
After setting the above settings, there is one last thing to do in order to get precise results. It is setting the Initial Capital.
- We can set this setting from 'Properties' tab. Named 'Initial Capital'. After setting the boundaries all we need to is to navigate to TradingView's own 'Data Window', and get the value there. Then paste it on the strategy's own related setting area.
In this example we used pair BTCUSDT 1D timeframe, our settings are:
Inputs Tab:
- Grid Count: 19
- High Limit: 65 500
- Low Limit: 15 000
- Quantity per level: 0.1
- Toggle Log Scale: Checked (because I always use Log Scale on charts, if Log Scale is turned on for the chart, this needs to be checked)
- Terminate Grid At The Upmost Level: Not checked
- Show Grid Levels: Checked
- Show Average Position Price: Checked
Properties Tab:
- Initial Capital: 22 628
- Slippage: 5
- Commission: 0.1% (this is the broker commission value)
This script's purpose is to make it easier to get the idea of grid trading, experiencing it in live session.
bc Grid Backtest v1.4This strategy is a full implementation of Grid Trading backtest.
Prominent features of this backtesting strategy are:
- Logarithmic Chart Support: This strategy can support Log Scale on graph. Meaning that grid lines won't have irregular gaps in between the lines if you would like to view the chart Log Scaled. Every line will be aligned correctly even if you use Log Scale or not.
- Precise Buy & Sell: Script will execute precise Buy and Sell orders.
- Dynamic Grid Level Count: From 2 grid levels to n amount of grid levels are supported. There is no limitation on grid level count. You can pick any number starting from 2.
- Customized Backtesting Results Table: A table which includes data for those who want to know has been added at top right. It can be disabled.
Characteristics of this script:
- Able to fill more than one order in one single candle.
- Levels will keep being updated with every trade.
- There will be always one grid level ignored and it will be the level which made the last order filling possible. This is normal behavior of grid trading system.
- You can both use Log Scale and Normal Scale with this script. No issue will be on grid levels.
Using the script:
- Add this script to the chart from indicators tab
- Set starting and ending date for the grid backtesting bot either by dragging and dropping the vertical lines or by the date-time picker from indicator Inputs tab.
- Set highest and lowest limit for the script. These will be the boundary limits. Highest and lowest price for the script to work on. Lines will populate between these two values
- Set grid level count. Number of levels of the grid.
- Set amount to spend on per level. This quantity of order will be placed on each level when needed.
After setting the above settings, there is one last thing to do in order to get precise results. It is setting the Initial Capital.
- We can set this setting from 'Properties' tab. Named 'Initial Capital'. After setting the boundaries all we need to is to navigate to TradingView's own 'Data Window', and get the value there. Then paste it on the strategy's own related setting area.
In this example we used pair BTCUSDT 4h timeframe, our settings are:
Inputs Tab:
- Grid Count: 13
- High Limit: 72 000
- Low Limit: 17 000
- Logarithmic Grids: Checked (because I always use Log Scale on charts, if Log Scale is turned on, this needs to be checked)
- Quantity per level: 0.1
- Show Table: Checked
- Show Grid Levels: Checked
- Show Average Position Price: Checked
Properties Tab:
- Initial Capital: 24 902
- Slippage: 5
- Commission: 0.1% (this is the broker commission value)
This script's purpose is to make simulating possible outcomes between two dates. Therefore making it easier to get the idea of grid trading, finding the best settings for your risk management and for your portfolio.
Rocket Grid Algorithm - The Quant ScienceThe Rocket Grid Algorithm is a trading strategy that enables traders to engage in both long and short selling strategies. The script allows traders to backtest their strategies with a date range of their choice, in addition to selecting the desired strategy - either SMA Based Crossunder or SMA Based Crossover.
The script is a combination of trend following and short-term mean reversing strategies. Trend following involves identifying the current market trend and riding it for as long as possible until it changes direction. This type of strategy can be used over a medium- to long-term time horizon, typically several months to a few years.
Short-term mean reversing, on the other hand, involves taking advantage of short-term price movements that deviate from the average price. This type of strategy is usually applied over a much shorter time horizon, such as a few days to a few weeks. By rapidly entering and exiting positions, the strategy seeks to capture small, quick gains in volatile market conditions.
Overall, the script blends the best of both worlds by combining the long-term stability of trend following with the quick gains of short-term mean reversing, allowing traders to potentially benefit from both short-term and long-term market trends.
Traders can configure the start and end dates, months, and years, and choose the length of the data they want to work with. Additionally, they can set the percentage grid and the upper and lower destroyers to manage their trades effectively. The script also calculates the Simple Moving Average of the chosen data length and plots it on the chart.
The trigger for entering a trade is defined as a crossunder or crossover of the close price with the Simple Moving Average. Once the trigger is activated, the script calculates the total percentage of the side and creates a grid range. The grid range is then divided into ten equal parts, with each part representing a unique grid level. The script keeps track of each grid level, and once the close price reaches the grid level, it opens a trade in the specified direction.
The equity management strategy in the script involves a dynamic allocation of equity to each trade. The first order placed uses 10% of the available equity, while each subsequent order uses 1% less of the available equity. This results in the allocation of 9% for the second order, 8% for the third order, and so on, until a maximum of 10 open trades. This approach allows for risk management and can help to limit potential losses.
Overall, the Rocket Grid Algorithm is a flexible and powerful trading strategy that can be customized to meet the specific needs of individual traders. Its user-friendly interface and robust backtesting capabilities make it an excellent tool for traders looking to enhance their trading experience.
Hulk Grid Algorithm - The Quant ScienceGrid-based intraday algorithm that works 50% in trend following and 50% in swing trading. Orders are executed on a grid of 10 levels. The grid levels are dynamic and calculated on the difference between the previous day's open and close. The algorithm makes only long trades based on the following logic:
1. The daily close of the previous day is analyzed, the first condition is met if the previous day was bullish, closing higher than the 'opening.
2. Must pass 'x' number of bars before placing market orders.
3. The range, as the difference between close and open of the previous day must be greater than 'x'.
If these three conditions are met then the algorithm will proceed to place long orders. On a total of 10 grid levels, up to five trades are executed per day.
If the current close is above level 1 of the grid (previous day's close) then trend following trading will take place, working on the upper 5 levels. In this case each order is placed starting at level 1 and closed at each level above.
If the current close is below level 1 of the grid (previous day's open) then swing trading will be carried out, working on the lower 5 levels. In this case each order is placed starting at level 2 and closed at the upper level.
If at the time of order execution the price is above or below the stop loss and take profit levels, the algorithm will cancel the orders and prevent trading.
All orders are closed exclusively for two reasons:
1. If the stop loss or take profit level is confirmed.
2. If the daily session is ended.
UI Interface
You can adjust:
1. Backtesting period
2. 'x' number of bars before placing orders at the market (remember to always add 2 to the number you enter in the user interface if you enter 2 then execution will occur at the market opening after the fourth bar).
3. Intercepted price range between close and open of the previous day, avoiding trading on days when the range is too low.
4. Stop loss, level calculated from the 'last lower grid, if the market breaks this level the grid is destroyed and closes all open positions.
5. Take profit, the level calculated from the last upper grid, if the market breaks this level the grid is destroyed and closes all open positions.
The backtesting you see in the example was generated on:
BINANCE:BTCUSDT
Timeframe 15 min
Stop loss 2%
Take profit 2%
Minimum bars 3
Size grid range 500
This algorithm can be used only on intraday timeframe.
Mean Reverse Grid Algorithm - The Quant ScienceMean Reverse Grid Algorithm - The Quant Science™ is a dynamic grid algorithm that follows the trend and run a mean reverting strategy on average percentage yield variation.
DESCRIPTION
Trades on different price levels of the grid, following the trend. The grid consists of 10 levels, 5 higher and 5 lower. The grids together create a channel, this channel represents the total percentage change where the algorithm works. The channel also represents the average change yields of the asset, identified during analysis with the "Yield Trend Indicator".
The algorithm can be set long or short.
1. Long algorithm: opens long positions with 20% of the capital every time the price crossunder a lower grid, for a maximum total of 5 simultaneous trades. Trades are closed each time the price crossover a higher grid.
2. Short algorithm: opens short positions with 20% of the capital every time the price crossover a higher grid, for a maximum total of 5 simultaneous trades. Trades are closed each time the price crossunder a lower grid.
USER INTERFACE SETTING
The user configures the percentage value of each grid from the user interface.
AUTO TRADING COMPLIANT
With the user interface, the trader can easily set up this algorithm for automatic trading. Automating it is very simple, activate the alert functions and enter the links generated by your broker.
BACKTESTING INCLUDED
With the user interface, the trader can adjust the backtesting period of the strategy before putting it live. You can analyze large periods such as years or months or focus on short-term periods.
NO LIMIT TIMEFRAME
This algorithm can be used on all timeframes and is ideal for lower timeframes.
GENERAL FEATURES
Multi-strategy: the algorithm can apply either the long strategy or the short strategy.
Built-in alerts: the algorithm contains alerts that can be customized from the user interface.
Integrated grid: the grid indicator is included.
Backtesting included: automatic backtesting of the strategy is generated based on the values set.
Auto-trading compliant: functions for auto trading are included.
ABOUT BACKTESTING
Backtesting refers to the period 1 August 2022 - today, ticker: ETH/USDT, timeframe 1H.
Initial capital: $1000.00
Commission per trade: 0.03%
GRID SPOT TRADING ALGORITHM - GRID BOT TRADING STRATEGYGRID SPOT TRADING ALGORITHM : LONG ONLY STRATEGY OPEN SOURCE
This is a long only strategy for spot assets.
HOW IT WORKS
Grid trading is a trading strategy where an investor creates a so-called "price grid". The basic idea of the strategy is to repeatedly buy at the pre-specified price and then wait for the price to rise above that level and then sell the position (and vice versa with shorting or hedging).
FEATURES
Grids: This algorithm has a total of 10 grids.
Take profit: The trader can increase or decrease the distance between the grids from the User Interface panel, the distance between one grid and another represents the take profit.
Management: The algorithm buys 10% of the capital every time the price breaks down a grid and sells during a rise to the next higher grid. The initial capital is invested in 10 sizes which represent 10% of the capital per trade.
Stop Loss: The algorithm knows no stop loss as long as it is not activated from the User Interface panel. By activating the stop loss from the User Interface panel the algorithm will insert a close condition on all trades which will be calculated from the last lower grid.
Trades: Trades are opened only if the price is within the grid. If the market leaves the grid the algorithm will not buy new positions or sell new positions.
Optimal market conditions: The favorable market for this algorithm is the sideways market.
LIMITATIONS OF THE MODEL
The trader must take into account that this is a static model. It only works perfectly well if the market is in a sideways phase and incurs heavy losses if the market takes a downward trend. The model is unusable for an uptrend. The trader must therefore carefully analyze the market where he intends to use this strategy, making sure that the price is in a sideways phase.
USES
Indispensable research and backtesting tool for those using bots for their investments. The algorithm produces a backtesting of the strategy for past history. It is used by professional traders to understand if this strategy has been profitable on a market and what parameters to use for bots using this strategy (Kucoin, Binance etc.).
If you would like to develop your own algorithm with customized conditions based on a grid strategy, please contact us.
If you need help in using this tool, please contact us without hesitation.
TTP Grid BacktesterThis pine script strategy allows to backtest Grid bots.
This initial version offers the following features:
- Set the top and bottom limits of the grid
- Plots the average position price, realised and unrealised profits
- Set the value to invest
- This script is a strategy so you can check each individual buy/sell, stats and all included with strategies
What does it do:
- Depending where is located the initial close price relative to the grid (above, below, inside) it will buy for as many levels are above the price.
- It will disable a level that recently filled an order (in the way grids bot do)
- When the grid starts it will disable the closest grid level
- It places limit orders in the active levels and many levels can be filled in a single candle
- You can activate recalculate on each order filled, which will allow to fill further needed orders if the price swings up and down crossing multiple times multiple grid levels but I have found that doing this can compromise the accuracy of the price used on those levels (there are minor gaps between the filled price and the original level price)
How to use it:
- When you add this strategy to the chart you will be asked to select the top and bottom limits of the grid
- Notice you can always select the strategy in the chart and drag and drop the limits to adjust the grid
- Once the grid is in place, you can use either lower chart timeframes for higher accuracy of the stats, or higher timeframes if you want to privilege longer periods of testing
How to set the correct "initial capital"
In order to prevent getting wrong stats you need to make sure you are using the correct initial capital. If you put less than what you are actually using your results will be over inflated. If you set an initial capital below what the bot requires, your results will be smaller than they should.
- If you want to use exactly 100% of the capital for the grid use then first select what amount per level you want to use. Set this value in the settings of the indicator (if you are trading BTCUSD pair, how much BTC you want to use per level, 0.01 for example).
- Once you have set this value, then open the TradingView "Data Window" to be able to visualise the calculation of cash required to run the grid that the strategy is giving you. In our example with BTCUSD this value will be given in USD.
- Enter this amount in the "Properties" tab, "Initial Capital". If you enter the exact amount you will be using all for the grid usage.
- The grid first action will be to buy 0.01 for each level that is above the current price in the first candle of the chart. If there are no levels above it won't do any initial investment.
- The rest of the cash will be use to buy levels below if the price goes to the lower range of the grid later
Intention of this script
I built this script to help me understand better how grid bots work.
Understanding the flow of realised vs unrealised profits in a grid can help me understand why sometimes even if you are in red on unrealised profits, you can still compensate with realised profits and many other tricky scenarios with grids.
Sometimes I'm running a grid bot and would like to simulate how much better (or worst) it would have been to run it using different limits.
Future work and ideas
Initially I'm focusing on confirming that the grid behaves correctly and that the stats are as accurate as possible.
That is the first priority.
Once I feel more confident with the accuracy I will consider adding some of the following ideas (not in any particular order):
- Table with stats including: price of each level, times the level filled an order, times it was use for selling/buying, etc. Time it took to become in realised profit. Comparison against profits from buy & hold.
- Trailing TP/SL
- Entry/exit price
- Trading time window: only trade between the specified dates/times
- Alerts
GRID Trading Optimized for Directional MarketsGRID trading is a popular trading strategy in Forex and Commodity markets.
It it however a tricky strategy when markets become directional.
This Directional GRID system adjusts its trading strategy and direction based on Overbought and Oversold RSI conditions on 2 timeframes.
It uses the short timeframe (chart) to trigger adjustments, so it delays buying/selling of all the levels, until it becomes overbought/sold
And it used the longer timeframe to trigger trading direction long/short.
This makes it far less likely to ever get "underwater", and builds in extra profit potential during market extremes.
I have coded it when i was trading SLV, but it could be optimized for any market using a "TradingView Strategy Input Optimizer".
Backtest based on a 25k max capital investment during 6 months.
Check the NET Profit (50%) result, and compare against the Buy & Hold (13.5%) return.
Losing trades are the ones that are currently open..
Av Bars in trades is the time between direction changes, as Position Adjustments are done more frequently.
Contact me for Trading Automation As A Service.
Up & Down Trend Trading Strategy - BNB/USDT 15minThis strategy will focus on up trend trading and down trend trading based on several indicators such as;
for up trend
1. SAR indicator
2. Super trend indicator
3. Simple moving average for the period of 100
down trend
1. RSI Indicator
2. Money flow index
3. Relative volatility index
4. Balance of powder
(IK) Grid ScriptThis is my take on a grid trading strategy. From Investopedia:
"Grid trading is most commonly associated with the foreign exchange market. Overall the technique seeks to capitalize on normal price volatility in an asset by placing buy and sell orders at certain regular intervals above and below a predefined base price."
This strategy is best used on sideways markets, without a definitive up or down major trend. Because it doesn't rely on huge vertical movement, this strategy is great for small timeframes. It only goes long. I've set initial_capital to 100 USD. default_qty_value should be your initial capital divided by your amount of grid lines. I'm also assuming a 0.1% commission per trade.
Here's the basic algorithm:
- Create a grid based on an upper-bound (strong resistance) and a lower-bound (strong support)
- Grid lines are spaced evenly between these two bounds. (I recommend anywhere between 5-10 grid lines, but this script lets you use up to 15. More gridlines = more/smaller trades)
- Identify nearest gridline above and below current price (ignoring the very closest grid line)
- If price crosses under a near gridline, buy and recalculate near gridlines
- If price crosses over a near gridline, sell and recalculate near gridlines
- Trades are entered and exited based on a FIFO system. So if price falls 3 grid lines (buy-1, buy-2, buy-3), and subsequently crosses above one grid line, only the first trade will exit (sell-1). If it falls again, it will enter a new trade (buy-4), and if it crosses above again it will sell the original second trade (sell-2). The amount of trades you can be in at once are based on the amount of grid lines you have.
This strategy has no built-in stop loss! This is not a 'set-it-and-forget-it" script. Make sure that price remains within the bounds of your grid. If prices exits above the grid, you're in the money, but you won't be making any more trades. If price exits below the grid, you're 100% staked in whatever you happen to be trading.
This script is more complicated than my last one, but should be more user friendly. Make sure to correctly set your lower-bound and upper-bound based on strong support and resistance (the default values for these are probably going to be meaningless). If you change your "Grid Quantity" (amount of grid lines) make sure to also change your 'Order Size' property under settings for proper test results (or default_qty_value in the strategy() declaration).
Grid ToolThe core idea of this grid tool is that you have to concentrate less on the trade entries (this happens automatically time-independent but price-dependant) but rather on the validity of the macro trend. Exiting a trend when it is no longer valid is more important than entering a trade. But as long as the trend is valid, the trader participates exponentially in the overall trend.
It is advisable to start with a basic position and then "set up" the grid on this in a ratio of 1/10.
A major advantage of grid trading is that the average entry price in a trend moves further and further away from the current market price while the position continues to grow.
A small timeframe should be used so that the distance between the trades corresponds as closely as possible to the selected grid gap and since TV backtests are carried out with closed bars.
Before starting a grid, pre-analysis the market to make sure it is trending. Select the grid gap and grid position size that you are comfortable with. Monitor the trend and from time to time take some profit :).
PS: The ADX filter looks interesting.
Cyato Grid Basic Buy & Sell [BACKTEST]Private indicator
This Grid bot strategy creates buy orders when the price goes down one level or more, and sell order when the price goes up one level or more.
To avoid useless trades, the lastest traded level is disabled until another level is crossed.
To create the grid, one upper level and one lower level is calculated. Those 2 levels are either given by the user using "MANUAL" mode or automatically calculated by an AI. The space between these two levels are then divided equally into several steps, creating the grid. The number of steps is chosen by the user, from 3 to 20.
HOW IT WORKS
This is the Backtest version meaning this is the one you should use with the Strategy Tester (more below).
Select either "MANUAL" or "AI" mode.
When using "MANUAL", you have to configure an upper level and a lower level.
When using "AI", the upper and lower level are automatically calculated from last 7 days high/low plus a 3% deviation. You can configure the timeframe and the deviation.
Select the grid quantity, from 3 to 20.
Example with 3:
Example with 10:
Example with 20:
You can choose between "Once Per Bar Close" or "Once Per Bar" alert type.
"Once Per Bar Close" will wait candle close to confirm a trade.
"Once Per Bar" will trigger a trade if the price crossed a step anytime inside a candle. Note that the backtest will still use bar close price in its calculation.
BACKTESTING
The strategy will buy 1 contract when a BUY signal appears and sell 1 contract when a SELL signal appears.
Here 1 contract = 1 BTC
The strategy can buy up to 20 contracts. Pyramiding is enabled.
The Backtest info panel is here to show how many trades are open in the backtest.
I know very well that a backtest has no value if several trades are left open. That is why I coded a feature to close all open trades at once on the last candle. This feature can be turned on and off.
To get this indicator, use the link in my signature below, thanks!
inwCoin Ultimate Grid StrategyinwCoin Ultimate Grid Strategy is the proof of concept of infamous grid trading strategy.
IDEA :
- The idea is to put the price level as a grids on the chart and when price cross up or cross down it will enter position.
- If the price move to next level it will take profit the last level and enter new position.
Caution :
- If market is trending into one direction, it's not wise to run this strategy counter trend. eg. run short grid when trend is up or run long grid when trend is down.
- So make sure you have something to define the big trend like Moving Average (18) TF weekly.
- I still can't try in range market ( sideway ) because this strategy using 5 min TF to work and tradingview don't provide data back that far.
How to use
1) Find out which start value of your asset that you want to use. Eg. BTC is 8000 for this time ( 22/2/2020 )
2) Define the spread of each grid as percent. ( eg. 2% for BTC ). You can choose small percent like 0.2% or 0.01 in asset like currency or altcoin/btc
3) The default grid level is 20 grids, so you can try and try again until you happy with the result.
4) This strategy is fix position size so it can easily calculate.
5) Don't forget to check "Properties" tab to try changing capital size and fee rate to match your criteria
6) This strategy is not perfect, it just some proof of concept to see if the strategy is working in real trade.
Extra :
If you want to access to alert for this strategy you can inbox me for detail.