-
Range Bar in kdb
Hi all,
I am a new kdb user, i’m trying step by step to transform backtest logic written in Python into q language. Specifically, I am encountering problems replicating logic for constant range bars (https://help.cqg.com/cqgic/19/default.htm#!Documents/rangebarrb.htm).
If I am not mistaken, conceptually, the scan logic should be used to replace a traditional for loop, but unfortunately, I cannot achieve the desired result.
Below, I share very rudimentary code that runs correctly but is actually very slow. Any suggestions to adapt this logic efficiently?
Thanks
// Constant range bars, the bars update each time the “high – low” target is reached
rangeBars:{[lastPrice; rangeTarget]
candle: enlist 1;
cumulativeRange: 0;
candleIdx: 1;
high: first lastPrice;
low: first lastPrice;
loopFn: {[params]
lastPrice: params 0;
rangeTarget: params 1;
cumulativeRange: params 2;
candleIdx: params 3;
high: params 4;
low: params 5;
candle: params 6;
index: params 7;
/ Update high & low
if[lastPrice[index] > high; cumulativeRange+: abs lastPrice[index] – high; high: lastPrice[index]];
if[lastPrice[index] < low; cumulativeRange+: abs lastPrice[index] – low; low: lastPrice[index]];
/ Trigger cond
triggerCond: cumulativeRange > rangeTarget;
/ Update Variables if trigger
if[triggerCond;
candleIdx+: 1;
cumulativeRange: 0;
high: lastPrice[index];
low: lastPrice[index];
];
candle,: candleIdx;
(lastPrice; rangeTarget; cumulativeRange; candleIdx; high; low; candle; index + 1)
};
/ Loop
params: (lastPrice; rangeTarget; cumulativeRange; candleIdx; high; low; candle; 0);
do[count lastPrice – 1; params: loopFn params];
:params 6;
};
lastPrice: 1.0500 1.0501 1.0502 1.0503 1.0504 1.0505 1.0506 1.0507 1.0508 1.0509 1.0510 1.0511 1.0512;
rangeTarget: 0.0003; / (3 pips)
rangeBars[lastPrice; rangeTarget]
Log in to reply.