How to calculate the final stop loss in kdb?

The standard way to implement using loops I've already tried. This will take a lot of time if done according to the tick, as the px list passed will be huge. Is there an efficient way to do this without using loops. Can anyone use lists?

tlstop: {[ls; entry; loss; pxs] origentry: entry; i:0; curloss: 0f; exitpx: 0n; while[(i<count pxs) and (curloss>loss); curpx: pxs[i]; curpnl: $[ls=`l; curpx-entry; entry-curpx]; exitpx: $[curpnl<=loss; curpx; exitpx]; entry: $[curpnl>curloss; curpx; entry]; curloss: curpnl; i: i+1; ]; exitpx: $[exitpx=0n; last pxs; exitpx]; ans: $[ls=`l; exitpx-origentry; origentry-exitpx]; ans }; /tlstop[`s; 100.0; -2.0; (99 98 97 96 93)] 
+4
source share
2 answers

As you can see below, it is trivial to implement your algorithm idiomatically in about three lines of very detailed q or one line of short q if you want to annoy your colleagues.

 q)pxs:100 101 102 101 100 99 98 //Our price ticks. q)pxs 100 101 102 101 100 99 98 q)entry:({max (x;y)}\) pxs //Calculate entry prices for each tick. q)entry 100 101 102 102 102 102 102 q)(pxs-entry) <= -2 //Determine tick where stop loss condition is triggered. 0000111b q)first pxs where (pxs-entry) <= -2 //Calculate the price at which we would exit. 100 q)first pxs where (pxs-entry) <= -5 //We get null (0N) if stop loss is not triggered. 0N 

I must point out that this is good if you are doing research and not how to do it if you want to calculate stop loss for a live trading system. The runtime and memory of this increase linearly with respect to the number of ticks that you have, so by the end of the day it will be slow and will work with memory.

The way to do this in a real way is to maintain an entry price table for each open position and set up a function that runs every time a tick is pushed (asynchronously, of course) to your application by your ticker. This function either updates your entry prices or pushes the exit event to your trading manager. The key is that runtime and memory complexity should be constant relative to the number of ticks that you process.

+1
source

vectorised ...

 / trailing stop for long {[stoplossAtStart;prices] previous:prev prices; xtreme:maxs previous; sl:stoplossAtStart + sums (0|0,1_deltas[prices]) * 0b,1_(&). prices>/:(previous;xtreme); sl }; / trailing stop for short {[stoplossAtStart;prices] previous:prev prices; xtreme:mins previous; sl:stoplossAtStart + sums (0&0,1_deltas[prices]) * 0b,1_(&). prices</:(previous;xtreme); sl }; 
+1
source

Source: https://habr.com/ru/post/1488051/


All Articles