goxtool icon indicating copy to clipboard operation
goxtool copied to clipboard

suggestion: use the decimal module instead of float

Open jandd opened this issue 11 years ago • 1 comments

Hello, first thanks a lot for goxtool.

I have one suggestion to improve it a bit. It would be nice to use decimal instead of the float builtin type to avoid rounding and precision errors or at least provide additional methods to provide BTC and fiat values as Decimal. I implemented a hackish decimal conversion in a helper class for a custom strategy but having it directly in goxapi would be nicer.

jandd avatar Dec 22 '13 22:12 jandd

this is my mixin for decimal handling:

class FormatterMixin(object):
    """
    Mixin to format BTC and fiat currency values and timestamps.
    """

    def base_to_decimal(self, value):
        """
        Convert an int BTC value to a Decimal BTC value.
        """
        return Decimal(value) / Decimal(self.gox.mult_base)

    def decimal_to_base(self, value):
        """
        Convert a Decimal BTC value to an int BTC value.
        """
        return int(value * Decimal(self.gox.mult_base))

    def quote_to_decimal(self, value):
        """
        Convert an int fiat value to a Decimal fiat value.
        """
        return Decimal(value) / Decimal(self.gox.mult_quote)

    def decimal_to_quote(self, value):
        """
        Convert a Decimal fiat value to an int fiat value.
        """
        return int(value * Decimal(self.gox.mult_quote))

    def format_base(self, value):
        """
        Format a base (BTC) value.
        """
        return "{0:0.8f} BTC".format(self.base_to_decimal(value))

    def format_quote(self, value):
        """
        Format a value in quote (fiat) currency.
        """
        return "{0:0.5f} {1}".format(
            self.quote_to_decimal(value),
            self.gox.currency)

    def format_time(self, tvalue):
        """
        Format an integer time value.
        """
        return time.strftime(
            "%Y-%m-%d %H:%M:%S", time.localtime(tvalue))

A class using this mixin needs a goxapi instance in self.gox.

jandd avatar Dec 22 '13 23:12 jandd