Coding
Parsing & Data

Trading-Term Parser

Difficulty

Asked at Wolverine Trading, Marshall Wace

Theory: Parsing and Data Hygiene

Read the problem, hints and solution here. The editor needs a bigger screen: open this page on a laptop to write and run your code.

Available in Python and C++. You are solving it in Python. Switch to C++

Implement parse_order(s), a parser for order shorthand. B 100 AAPL @ 152.35 means buy 100 shares of AAPL at 152.35, and S 50 TSLA @ MKT means sell 50 TSLA at market. The parser never guesses: anything that does not match the grammar exactly is rejected, not repaired.

Desks still pass orders around in this shorthand, in chat, in test fixtures and in legacy tools.

parse_order returns four values: side, which is "BUY" or "SELL"; qty, an integer; symbol, the string; and price, which is absent for a market order. If s is invalid, return nothing at all (the whole result, not a field).

def parse_order(s: str) -> tuple[str, int, str, float | None] | None: ...

A valid string returns the tuple (side, qty, symbol, price) with price a float, or None for a market order. An invalid string returns None.

A valid string is exactly five fields separated by single spaces, with no leading or trailing whitespace: SIDE QTY SYMBOL @ PRICE.

  • SIDE: exactly B or S (case-sensitive; BUY or b are invalid).
  • QTY: one or more digits, no leading zero, value greater than 0.
  • SYMBOL: 1 to 6 uppercase letters A-Z only.
  • The fourth field is exactly @.
  • PRICE: either exactly MKT (a market order, with no price), or one or more digits optionally followed by . and one or two decimal digits, with numeric value strictly greater than 0. So 152.35, 7 and 0.50 are valid; .35, 152., 152.345, 0 and 0.00 are not.

Examples

parse_order("B 100 AAPL @ 152.35")
# ('BUY', 100, 'AAPL', 152.35)

parse_order("S 50 TSLA @ MKT")
# ('SELL', 50, 'TSLA', None)

(parse_order("B 100 aapl @ 152.35"), parse_order("S 5 MSFT @ 401.10"))
# (None, ('SELL', 5, 'MSFT', 401.1))
# a lowercase symbol is invalid; note 401.10 parses to the float 401.1

Constraints

  • s has length at most 100; a single pass is plenty.
  • The quantity and the price in cents each fit in a 64-bit signed integer.
  • The hidden tests are a wall of near-misses: every field has invalid variants, and structural damage (extra spaces, missing @, trailing characters) must also be rejected.
Rate this problem
Language:
Python 3.12C++23
parse_order
Rate this problem