(IK) Grid Script

This 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).
Phát hành các Ghi chú: Big update!

My old version had a handful of bugs in it. I've optimized that logic in addition to adding a few new features

The basic algorithm is slightly tweaked. Buy when you cross under a grid line, and sell when you cross over a grid line. But, instead of dealing with orders in a queue, I'm mapping orders to the Grid Line Array. If you buy on line #1, you will sell that order on line #2, no matter what price does in between. If you buy on line #2, you will sell on line #3. You can only have one open order per grid line. You can't sell on the bottom grid line, and you can't buy on the top grid line.

A grid strategy is traditionally done with limit orders, but this uses market orders. I simply haven't messed with limit orders in pine script yet, but I imagine it would be a pretty small change. Perhaps in a future update I'll add the option.

Unlike my previous version, order quantity is now calculated automatically based on how many grid lines you have.

Similar to my previous version, this script still plots 'near grid lines'. The blue line represents your closest 'buy', while the purple line represents your closest 'sell'. My updated logic doesn't actually use these values any more, but I decided to leave them in for visual aid.

Grid line quantity is capped at 15. This was a fairly arbitrary decision. To increase this limit, you'll need to change the maxval of the input, add plotting code for more lines, and adjust the pyramiding setting

---Introducing Auto-Bounds---
Instead of setting grid bounds manually, you now have to option to set them automatically. These auto bounds will follow price action, turning this strategy from very hands-on to quite hands-off. A 'manual grid' will theoretically* never lose money (excluding slippage and commission), but there's no safety if price falls below your grid, and no trading if price rises above your grid. An 'auto grid' will likely lose money as price trends down, but you never have to worry about price exiting your grid.

I've attached a screen shot of this strategy with Auto Bounds turned on
Profit factor is much lower (~2.8) and drawdown is much higher (~12%), but using auto bounds comes with a sense of security if you're worried about price going beyond your manually set bounds. It adds a sort of built-in stop loss functionality because it will happily take a small loss if the grid shifts down, alleviating your risk and allowing for more trades

Settings for Auto Bound include:
-Source: should bounds be based on recent High & Low, or based on a Simple Moving Average
-Lookback: How far back to look for Highs and Lows -OR- length of simple moving average
-Deviation: if deviation is 0.05 (5%) and Source = High & Low, then add 5% to the upperbound, and minus 5% from the lower bound. If Source = Average, then the upperbound will be 5% up from the SMA, and the lowerbound will be 5% below the SMA. Deviation does not have to be positive if Source = High & Low; you can narrow your bounds instead of widening them. Deviation must be positive if Source = Average.

That's about it I think. I'm probably going to develop a modified version of this specifically geared towards automating with specific third-party services. This would involve some more logic in configuring alert messages. As always, feel free to steal/modify/improve this script; just let me know in the comments what you do!

* my back testing with manual bounds shows a ~82% success rate (should be 100%). There's something going on with the entry and exit id's (it looks like a trade opened with one id is exited with another id). I'm not sure exactly what's going on here in my list of trades, but all of the trade signals are showing up on the chart where they should be with the correct id's. Please leave any insights in the comments.
Phát hành các Ghi chú: Bug Fix - added to line up my trade entry/exit id's. This gives me a 100% profit percentage with a manual grid. Of course, this is all fun and games until price falls too far below that bottom grid line, or hits the top once and never again. Keep an eye out if you use manual grid bounds!

Maintenance - removed the property from my plotting code; using instead
Phát hành các Ghi chú: Typos in my last update, haha. It should read:

Bug Fix - added close_entries_rule="ANY" to line up my trade entry/exit id's. This gives me a 100% profit percentage with a manual grid. Of course, this is all fun and games until price falls too far below that bottom grid line, or hits the top once and never again. Keep an eye out if you use manual grid bounds!

Maintenance - removed the transp property from my plotting code; using color.rgb() instead
Mã nguồn mở

Với tinh thần của TradingView, tác giả đã xuất bản tập lệnh theo mã nguồn mở, vì thế trader có thể dễ dàng hiểu và tùy chỉnh được. Bạn có thể sử dụng miễn phí, hoặc tùy chỉnh lại mã đã được cấp phép bởi Quy tắc Chung. Bạn có thể sử dụng nó trên biểu đồ.

Bạn muốn sử dụng tập lệnh này trên biểu đồ?

Bình luận

It could be more useful if we could set the upper and lower limits as a percentage of the current price.
Good work.
+1 Phản hồi
tapRoot_coding hasankeskin
@hasankeskin, That's a cool idea. I've been meaning to give this one a little update; I'll keep that in mind when I get around to it!
Phản hồi
great work! It is perfect for range market
+1 Phản hồi
tapRoot_coding Crypto-Engineer
@Crypto-Engineer, Thanks!
Phản hồi
Hi, whatever settings I use, I get little returns like 0.09%. What should I change?
Phản hồi
This is truly amazing work! I do have one suggestion though. Wouldn’t it be More profitable of instead of bying on the cross down at each level, only had it buy on the cross up after crossing down levels. That way it would only buy the lowest level. Doing the same in reverse for selling would make it sell on the highest level crossed upwards when crossing it back down. This in combination with moving grids would be amazing I think. Any thoughts on this? Cheers! :)
Phản hồi
I love this script. I've been toying around with this, but honestly I'm not very good at pinescript yet. I think an amazing feature would be to prevent the autogrid from running down, but allow it to run up. If the price action runs down below a set amount, you stop loss and get out of the trade for the day. I've been thinking about using this for stock trading, for tickers like AMD that range well, but can have some significant up or down days within the range. I'm attempting to get it to automatically grab the opening price for the day and set a floor grid value of 2% down from open and after a significant run-up (think AMC or GME squeeze), the script would change the floor value to 5 percent down from the high so that you lock profits for the day if the stock tanks quickly. I'd think this same approach would work well for crypto as well.

At any rate, thanks for the amazing work and allowing us newbs to use it for free.
Phản hồi
tapRoot_coding binarycataclysm
@binarycataclysm, Thank you! Those are all great ideas. If you manage to implement them (great way to learn!), I'd be curious to see how they play out in back testing.

And this script is as much yours as it is mine; we're all dipping our feet here in the same communal pool of knowledge.
Phản hồi
It's closing with a different id because you need to set `close_entries_rule="ANY"` also. To choose the trade to close.
Phản hồi
@athiwatch, Thanks! I wasn't aware of this setting. I'll mess around with it
Phản hồi