In this short article we will take a look at rounding to the nearest tick. This can be useful for anyone who is using Tradingview’s alert system to send real order. Rounding to the nearest tick will ensure that orders are sent at valid levels and not rejected by your broker.
The Snippet
Let’s dive straight in with the snippet. The functions below can be copy and pasted into any script. There are two functions. One which will round up to the nearest tick and one which will round down. The functions have the same two inputs (called arguments):
x
, a series, e.g. a calculated stop loss level.mintick
, a float or integer that we will round to the nearest value.
1 2 3 4 5 6 7 8 |
// round(x*4)/4) round_up_to_tick(x, mintick)=> mult = 1 / mintick value = ceil(x*mult)/mult round_down_to_tick(x, mintick)=> mult = 1 / mintick value = floor(x*mult)/mult |
If the code above looks complex, fear not, we have a tutorial on functions in pine script:
Full Example
The example below has a couple of simple inputs so you can test each function easily. In reality, you would not manually enter the mintick
value yourself but instead grab it using the built-in variable syminfo.mintick
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © BacktestRookies //@version=4 study("Rounders", overlay=false) val = input(12.05, step=0.01, title='Value to round') mtick = input(0.1, step=0.01, title='Minimum tick to Simulate') dir = input("Up", options=["Up","Down"], title="Round") // NOTE // ======================================================== // Don't forget you can replace mtick with syminfo.mintick! // -------------------------------------------------------- round_up_to_tick(x, mintick)=> mult = 1 / mintick value = ceil(x*mult)/mult round_down_to_tick(x, mintick)=> mult = 1 / mintick value = floor(x*mult)/mult rounded = dir == "Up" ? round_up_to_tick(val, mtick) : round_down_to_tick(val, mtick) plot(rounded, title='Rounded Value') |
On the charts
This one is not much to look at but should look something like this:
Using a single, simple line makes it easy to test whether the rounding is working or not. Go on, try a few values and see for yourself!