tapRoot_coding

(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).
版本注释: 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.
版本注释: 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
版本注释: 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
开源脚本

本着真正的TradingView精神,该脚本的作者将其开源发布,因此交易者可以理解和验证它。为作者加油! 您可以免费使用它,但是在发布中重复使用此代码受网站规则的约束。您可以收藏它以在图表上使用。

想在图表上使用此脚本?

评论

It's closing with a different id because you need to set `close_entries_rule="ANY"` also. To choose the trade to close.
+2 回复
@athiwatch, Thanks! I wasn't aware of this setting. I'll mess around with it
回复
@athiwatch, updated - thanks for the tip!
回复
It could be more useful if we could set the upper and lower limits as a percentage of the current price.
Good work.
+1 回复
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!
回复
great work! It is perfect for range market
+1 回复
tapRoot_coding Crypto-Engineer
@Crypto-Engineer, Thanks!
回复
How do I set my parameters with start date time and end date time ?
回复
Thank you for posting this! This is pretty crazy. I am in the process of developing an MAR algo and it has higher profit ranges like 100k% but a lil bit lower 70-80% percent profitable, the lowest draw down I think I got was around 25%. I'm kind of uncertain about one thing; what part is the best part to develop in an algo? (I know to keep drawdown at a minimum.) Percent profitable? Profit factor? Net profit? Thanks in advance! Have a good day!
回复
nawmeancuh nawmeancuh
@nawmeancuh, Also one more thing. I seen, once I started to play around with values, that I am getting all the variables, but no data. Is this okay, or is it only valid if there is data shown? (Btw data I mean the little graph under "Strategy Tester") Thanks again, lol.
回复