سؤال

The standard way of implementing using loops i've already tried. This will take a long time if done on tick data as the px list passed would be huge. Is there an efficient way of doing this without using loops. May be using lists in some way?

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)]
هل كانت مفيدة؟

المحلول

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

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 should point out that this is only good if you are doing research and is not the way to do this if you want to compute stop losses for a live trading system. The runtime and memory of this increases linearly with respect to the number of ticks you have so by the end of the day it will be slow and a memory hog.

The way to do this for real is to maintain a table of entry prices 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 plant. This function either updates your entry prices or pushes an exit event to your trade manager. The key is that runtime and memory complexity should be constant with respect to the number of ticks you process.

نصائح أخرى

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
};
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top