Here is the NinjaScript expression that just does that:
price - price % TickSize + ((price % TickSize < TickSize / 2) ? 0.0 : TickSize);
If you are already familiar with the % and ? operators, the expression should make sense to you immediately. For those who are not, let me explain it to you one step a time.
First, TickSize is a property of any indicator or strategy in NinjaScript. It represents the minimum fluctuation in price of an instrument. For E-mini S&P 500, its value is 0.25.
Second, "%" is the modulus operator in C#. It computes the remainder after dividing its first operand by its second. To illustrate, 9 % 3 yields 0, 9 % 2 yields 1, and 9 % 0.7 yields 0.6. Therefore, price % TickSize or 1408.673 % 0.25 yields 0.173. Now you can see that the first part of the expression, price - price % TickSize, yields 1408.50, a valid price that is closet to but smaller than the initial one.
However, this is not the final result yet. Did you notice the remainder, 0.173 is more than half of the tick size, 0.25 / 2 or 0.125? So the third step is to add a tick size to the result when the situation occurs.
The second part of the expression, ((price % TickSize < TickSize / 2) ? 0.0 : TickSize), just does that. It uses the conditional operator in C#, "?". Here is a general expression using the operator, condition ? value 1 : value 2. The expression equals to value 1 when the condition is true; it equals to value 2 when the condition is false. To illustrate, the value of (100 > 50) ? 1 : 2 is 1 because 100 is larger than 50. On the other hand, the value of (10 > 50) ? 1 : 2 is 2 because 10 is smaller than 50.
The condition in our expression is price % TickSize < TickSize / 2, that is, the remainder is smaller than half of the tick size. When this is true, 0.0 as value 1 is added to the result. When it is false, the tick size as value 2 is added to the result. The final result is a “legitimate” price for the instrument rounded from the initial one.
To recap, simply replace the price variable in the expression above with any value and you can round it by the tick size of any instrument.
Comment