Sharing a common DolphinDB use case and solution for data processing.
I have a table of stock observation data recording minute-by-minute indicator states, with two key indicators:
- ov95: Breakthrough signal for the 95% pressure level (0 or 1)
- ov70: Breakthrough signal for the 70% pressure level (0 or 1)
I need to calculate a position state column with these rules:
- Initial position is 0 (no position)
- When current position=0 and ov95=1, position changes to 1 (open position)
- When current position=1 and ov70=0, position changes to 0 (close position)
- All other cases maintain the previous position
Here's what the logic would look like in procedural pseudocode:
position = 0 # Initialize
for each row in table:
if position == 0 and row.ov95 == 1:
position = 1
elif position == 1 and row.ov70 == 0:
position = 0
# Else position remains unchanged
row.position = position # Store the computed value
The key challenge here: Each row's position state depends on the previous row's position value, creating a state dependency chain.
My sample data:
| Timestamp | StockCode | ov95 | ov70 | pos = 0
|----------------------|-----------|------|------|
| 2022-06-01 09:45:03 | 000717 | 1 | 0 | -> pos = 1
| 2022-06-01 09:45:06 | 000717 | 1 | 0 | -> pos = 0
| 2022-06-01 09:45:09 | 000717 | 1 | 0 | -> pos = 1
| 2022-06-01 09:45:12 | 000717 | 0 | 0 | -> pos = 0
| 2022-06-01 09:45:15 | 000717 | 0 | 0 | -> pos = 0
| 2022-06-01 09:45:18 | 000717 | 0 | 0 | -> pos = 0
| 2022-06-01 09:45:21 | 000717 | 0 | 1 | -> pos = 0
| 2022-06-01 09:45:24 | 000717 | 0 | 1 | -> pos = 0
| 2022-06-01 09:45:27 | 000717 | 0 | 1 | -> pos = 0
I've tried using simple CASE WHEN statements but found I can't reference the calculated result from the previous row.
In Python or Java this would be easy with loops, but I'm wondering if this can be done in pure DolphinDB SQL? If so, what approach should I use to implement this state-dependent calculation?

ov95 : 1, ov70 : 0followed byov95 : 0, ov70 : 0you want that second row to still haveposition : 1?