Back to General

File Parsing · General · Practice Question

Decode Text

Sign in to track your progress

Question

A trader starts the day with a position of 125 lots in a futures contract.

Throughout the trading session, position updates are recorded in a text file as a single semicolon-separated string:

U10;D5;U20;D15;D10;U25;D5;U30

Each update consists of a direction and a quantity:

  • U indicates the trader's position increased by the specified number of lots.
  • D indicates the trader's position decreased by the specified number of lots.

Write a q expression to read the file and calculate the trader's final position.

Solution

txt:first read0 `:file.txt
items:";" vs txt

sign:(1 -1) "UD"?1#'items
qty:"J"$1_'items

125 + sum sign * qty

Alternative Solution

txt:first read0 `:file.txt

125 + sum value ssr/[txt;("U";"D";";");(" ";"-";",")]

Explanation

First, read the contents of the file:

txt:first read0 `:file.txt

This returns:

"U10;D5;U20;D15;D10;U25;D5;U30"

Next, split the string into individual updates:

items:";" vs txt

Result:

"U10"
"D5"
"U20"
"D15"
"D10"
"U25"
"D5"
"U30"

Extract the direction from each update and convert it into a sign:

sign:(1 -1) "UD"?1#'items

Extract the numeric quantities:

qty:"J"$1_'items

Multiply each quantity by its sign and calculate the total change:

sum sign * qty

Result:

50

Finally, add the net change to the trader's starting position:

125 + 50

Result:

175

The alternative solution uses ssr to rewrite the original text into a q expression:

ssr/[txt;("U";"D";";");(" ";"-";",")]

This converts:

"U10;D5;U20;D15;D10;U25;D5;U30"

into:

" 10,-5, 20,-15,-10, 25,-5, 30"

Then value evaluates the string as a numeric list, and sum calculates the net position change.

The trader's final position is 175 lots.