Longbridge.Decimal (longbridge v0.1.0)

Copy Markdown View Source

Optional helpers for converting Longbridge wire-format strings to numeric values.

Longbridge returns monetary and quantitative fields as strings (e.g. "0.0723", "3241500000000"). This module provides helpers to convert those strings to a numeric type without pulling in the :decimal package as a hard dependency.

Most callers will want to use Decimal from the :decimal package for exact arithmetic on monetary values. If you don't depend on :decimal, parse_number/1 returns either an integer or a float depending on whether the string contains a decimal point.

Usage with :decimal

{:ok, config} = Longbridge.OAuth.load_token(client_id)
{:ok, %{price_close: p}} = Longbridge.FundamentalContext.valuation_comparison(config, "AAPL.US", "USD")
dec = Longbridge.Decimal.to_bigdecimal(p)
Float.round(Decimal.to_float(dec), 2)

Usage without :decimal

price = Longbridge.Decimal.parse_number("0.0723")
# => 0.0723

To use the :decimal-backed helpers, add {:decimal, "~> 2.0 or ~> 3.0"} to your mix.exs dependencies.

Summary

Functions

Parses a wire-format numeric string.

Sums a list of wire-format numeric strings into a single Decimal. nil and empty strings are treated as zero.

Parses a wire-format numeric string as a Decimal.

Functions

parse_number(s)

@spec parse_number(String.t() | nil) :: number() | nil

Parses a wire-format numeric string.

Returns an integer if the string contains no decimal point, or a float otherwise. Returns nil for empty strings or nil.

Examples

iex> Longbridge.Decimal.parse_number("100")
100
iex> Longbridge.Decimal.parse_number("3.14")
3.14
iex> Longbridge.Decimal.parse_number("")
nil

sum_bigdecimal(values)

@spec sum_bigdecimal([String.t() | nil | number()]) :: struct()

Sums a list of wire-format numeric strings into a single Decimal. nil and empty strings are treated as zero.

Requires the :decimal package in your app.

to_bigdecimal(s)

@spec to_bigdecimal(String.t() | nil) :: struct() | nil

Parses a wire-format numeric string as a Decimal.

Requires the :decimal package as a dependency in your app. Returns nil for empty/nil inputs.

If :decimal is not loaded, raises ArgumentError at call time with a hint to add the dependency.

Examples

iex> Longbridge.Decimal.to_bigdecimal("3.14") |> Decimal.to_string()
"3.14"