prof7bit / goxtool

display Mt.Gox live market data (in the console) and experiment with trading bots
185 stars 53 forks source link

suggestion: use the decimal module instead of float #50

Open jandd opened 10 years ago

jandd commented 10 years ago

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 commented 10 years ago

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.