How to create this array?

k4zv
I want to create an array named 'result' as the figure shown above, Please help!
//
1stly, I use code below to generate k1L, k4H:

k1L = ValueWhen(k1, L);
k4H = ValueWhen(k4, H);

//
2ndly, I need to let k4H shows values from the position of k1=1.
(Please notice that position of k1=1 and k4=1 is not fixed)

You seem to want to look forward if k1 is true earlier than k4.

Data used:

Date,Time,L,H,Aux1,Aux2
2019-01-01,09:00,900,910,0,0
2019-01-01,09:01,888,895,1,0
2019-01-01,09:02,905,915,0,0
2019-01-01,09:03,880,890,0,0
2019-01-01,09:04,870,877,0,1
2019-01-01,09:05,860,855,0,0
2019-01-01,09:06,850,866,1,0
2019-01-01,09:07,810,822,0,1
/// what is it about:
/// @link https://forum.amibroker.com/t/how-to-create-this-array/15240/2
k1 = Aux1;
k4 = Aux2;
k1L = ValueWhen(k1, L);
k4H = ValueWhen(k4, H);

rev_k4h = Reverse(Nz(k4h));// reverse k4h array
cond = Reverse(Nz(k4));// reverse k4
val_when = ValueWhen(cond, rev_k4h);
k4h_rev = Reverse(val_when);// reverse back

// marks 877 etc. at k1 > 0 and k4 == 0 
//-> looking forward for k4 being true then
result1 = IIf(k1 AND !k4, k4h_rev, 0);
//
// marks 877 etc. at k1 > 0 and k4 > 0 at same bar 
// -> not looking forward then
result1 = IIf(k1 AND k4, k4h, result1);
//
// keeps 877 etc. since k1 > 0
result2 = Nz(ValueWhen(k1>0, result1));

Plot( result1, "result1", colorOrange, styleHistogram);
Plot( result2, "resul2", colorRed);

Upper code seems to work if k4 is true after k1 being true (then it looks forward for k4H value if k4 is true) and it works if k1 and k4 are true at same bar (then it stores k4H at k1 == 1 of same bar).

See picture with different k1 == true positions

if Data 1
9

if Data 2
10

6 Likes

Thank you for your treasure instructions, I will read it carefully! :smiley:

Currently I think my problem should be solved by codes below :

k1L = ValueWhen(k1, L);
k4H = ValueWhen(k4, H);
k1bars = BarsSince(k1L);
k4H = Ref(k4H, k1bars); // look forward

No, that will not work. Import the data I posted (or look at your own picture).

The code you posted makes no sense.
It makes no sense because

  1. Location of k4 is unknown (it can be located anywhere). So using Ref and some bars of past to look forward is like fishing in the dark.
  2. Besides k1L will always be true except for barindex zero (using your data) -> k1L larger zero then. It is just price being kept since expression (k1) was true. So BarsSince(k1L) will always be zero (if bi > 0). Look at your own picture of what k1L array actually is like.

PS:

A better method than thinking/assuming is to follow advice of this post here How do I debug my formula.

1 Like