brokapi.numbers

Exact arithmetic on prices and quantities.

A price is a whole number of price steps. These helpers round to the step with decimal.Decimal, so 0.1 + 0.2 style noise never appears. They are the same rules as round_to_step of the Rust library.

>>> from decimal import Decimal
>>> from brokapi.numbers import RoundMode, round_to_step
>>> round_to_step(Decimal("244.37"), Decimal("0.05"), RoundMode.DOWN)
Decimal('244.35')
>>> round_to_step(Decimal("244.37"), Decimal("0.05"), RoundMode.UP)
Decimal('244.40')
class RoundMode(enum.Enum):

Where to go when the value is between two steps.

DOWN = <RoundMode.DOWN: 'Down'>

To the lower step (a buy price that must not exceed the plan).

UP = <RoundMode.UP: 'Up'>

To the higher step.

NEAREST = <RoundMode.NEAREST: 'Nearest'>

To the nearer step. In the middle, away from zero for positive values.

def is_on_step(value: decimal.Decimal, step: decimal.Decimal) -> bool:

Is value a whole number of step? A step of zero or below means "no grid" and answers True.

def round_to_step( value: decimal.Decimal, step: decimal.Decimal, mode: RoundMode = <RoundMode.DOWN: 'Down'>) -> decimal.Decimal:

Rounds value to a multiple of step. Exact: a value that already is a multiple is returned as it is.