示例#1
0
    def __init__(self):
        self._USDT = 0.
        self._ETH = 0.
        self._BTC = 0.

        #
        self._utils = Utilities()
示例#2
0
    def __init__(self):
        self._settings = {}
        self._candles = []
        self._stack = Stack()

        # Attributes to other classes
        self._utils = Utilities()
        self._t = Transaction()

        # Run program's main loop
        self.run()
示例#3
0
class Stack():
    """
    Stack of money in three currencies:
        USDT, ETH, BTC
    """

    def __init__(self):
        self._USDT = 0.
        self._ETH = 0.
        self._BTC = 0.

        #
        self._utils = Utilities()

    def updateCurrency(self, currency: str, value: str) -> None:
        """
        Update Stack's currency with a given value.

        Args:
            currency (str): Currency to update.
            value (str): New value for the given currency.
        """

        if currency == "USDT":
            self._USDT = float(value)
        elif currency == "ETH":
            self._ETH = float(value)
        elif currency == "BTC":
            self._BTC = float(value)

    def update_s(self, updateCommand: str) -> None:
        """
        Update Stack's currencies from the given command.

        Args:
            updateCommand (str): Command to be parsed.
        """

        currenciesUpdate = updateCommand.split(sep=",")
        if len(currenciesUpdate) is not 3:
            Logger("Might update the three currencies.")
            return

        for currencyUpdate in currenciesUpdate:
            update = currencyUpdate.split(sep=":")
            if len(update) is not 2:
                Logger("Wrong format. Command: update_s")
            elif (update[CURRENCY] in globals.currencies) is False:
                Logger(
                    f"{update[CURRENCY]} is not a valid currency."
                    f"Currencies are {globals.currencies}"
                )
            elif self._utils.isFloat(update[VALUE]) is False:
                Logger("Wrong {} value.".format(update[CURRENCY]))
            else:
                self.updateCurrency(
                    currency=update[CURRENCY],
                    value=update[VALUE]
                )
示例#4
0
文件: Rate.py 项目: sheiiva/CNA_trade
    def initPrice(self, inputPrice: str) -> float:
        """
        Initialize a price value of the current rate.

        Args:
            inputPrice (str): Input string to be checked.

        Returns:
            float: Return None if it cannot initialize the price.
                   Return the cast value otherwise.
        """

        if Utilities().isFloat(inputPrice) is False:
            Logger("Prices might be floats.")
            return None
        return float(inputPrice)
示例#5
0
文件: Rate.py 项目: sheiiva/CNA_trade
    def initDate(self, inputDate: str) -> int:
        """
        Initialize the Rate's date.

        Args:
            inputDate (str): Input string to be checked.

        Returns:
            int: Return None if it cannot initialize the date.
                 Return the cast value otherwise.
        """

        if Utilities().isInt(inputDate) is False:
            Logger("Rate's date might be an integer.")
            return None

        return int(inputDate)
示例#6
0
def test_isFloatWrongcase():

    utils = Utilities()

    assert not utils.isFloat("Not a float")
示例#7
0
def test_isFloatNormalcase():

    utils = Utilities()

    assert utils.isFloat(42.)
示例#8
0
def test_isIntWrongcase():

    utils = Utilities()

    assert not utils.isInt("Not an integer")
示例#9
0
def test_isIntNormalcase():

    utils = Utilities()

    assert utils.isInt(42)
示例#10
0
class Trade():
    """
    Main class of the Trade project.
    """
    def __init__(self):
        self._settings = {}
        self._candles = []
        self._stack = Stack()

        # Attributes to other classes
        self._utils = Utilities()
        self._t = Transaction()

        # Run program's main loop
        self.run()

    def getInput(self) -> str:
        """
        Get input and catch potential errors.

        Returns:
            str: Input received from stdin.
        """

        try:
            inputs = input()
        except EOFError:
            exit(84)
        except KeyboardInterrupt:
            Logger("\nexit.", logType="INFO")
            exit(0)
        else:
            return inputs

    def initSettings(self, inputs: list) -> None:
        """
        Parse the input passed as argument
        and initialise corresponding class's attribute.

        Args:
            inputs (list): Input to be parsed.
        """

        if inputs[globals.VARIABLE] == "candle_format":
            # Candle format is set by default, don't need to stock it.
            return

        if self._utils.isInt(inputs[globals.VALUE]):
            value = int(inputs[globals.VALUE])
        elif self._utils.isFloat(inputs[globals.VALUE]):
            value = float(inputs[globals.VALUE])
        else:
            value = inputs[globals.VALUE]

        if inputs[globals.VARIABLE] == "initial_stack":
            self._stack._USDT = value
        if inputs[globals.VARIABLE] == "candles_given":
            self._t._period = int(value / 3)
        self._settings[inputs[globals.VARIABLE]] = value

    def fetchCommand(self, command: list) -> None:
        """
        Fetch the right command depending of the input and execute it.

        Args:
            command (list): the command to be checked and executed.
        """

        if command[0] == "settings" and len(command) is 3:
            self.initSettings(command)
        elif command[0] == "update" and len(command) == 4:
            if f"{command[1]} {command[2]}" == "game next_candles":
                newCandle = Candle(command[3])
                if newCandle._state == globals.VALID:
                    self._candles.append(newCandle)
                    self._t.update_lastClosePrices(newCandle)
            elif f"{command[1]} {command[2]}" == "game stacks":
                self._stack.update_s(command[3])
        elif f"{command[0]} {command[1]}" == "action order":
            # Server is waiting for a move. (`sell`|`buy`|`pass`)
            self._t.strategy(candles=self._candles, stack=self._stack)
        else:
            Logger("Unrecognized command.")

    def run(self) -> None:
        """
        Main loop of the Trade project.
        """

        while (True):
            inputCommand = self.getInput()
            # If no input: restart loop
            if len(inputCommand) is 0:
                continue
            inputParsed = inputCommand.split()
            # Fetch to the right command
            self.fetchCommand(inputParsed)