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 C++. Switch to Python

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).

using Order = std::tuple<std::string, long long, std::string, std::optional<long long>>;
std::optional<Order> parse_order(const std::string& s);

A valid string returns {side, qty, symbol, price} with the price in integer cents (152.35 is 15235, 7 is 700) and std::nullopt for a market order; an invalid string returns std::nullopt for the whole result.

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", 15235}

parse_order("S 50 TSLA @ MKT");
// {"SELL", 50, "TSLA", std::nullopt}

parse_order("B 100 aapl @ 152.35");   // std::nullopt, a lowercase symbol is invalid
parse_order("S 5 MSFT @ 401.10");
// {"SELL", 5, "MSFT", 40110}

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