Example #1
0
    def request_lag(self):
        """Request server time to calculate lag"""
        def lag_thread():
            json_time = http_request("%s://%s/0/public/Time" % (
                self.proto,
                HTTP_HOST
            ))
            if not self._terminating:
                try:
                    answer = json.loads(json_time)
                    if not answer["error"]:
                        lag = time.time() - answer['result']['unixtime']
                        result = {
                            'lag': lag * 1000,
                            'lag_text': "%0.3f s" % lag
                        }
                        translated = {
                            "op": "result",
                            "result": result,
                            "id": "order_lag"
                        }
                        self.signal_recv(self, (json.dumps(translated)))
                except Exception as exc:
                    self.debug("### exception in lag_thread:", exc)

        start_thread(lag_thread, "http request lag")
Example #2
0
    def request_history(self):
        """Start the trading history thread"""

        # Api() will have set this field to the timestamp of the last
        # known candle, so we only request data since this time
        # since = self.history_last_candle

        def history_thread():
            """request trading history"""

            querystring = "?pair=%s" % self.pair
            if not self.history_last_candle:
                querystring += "&since=%i" % ((time.time() - 172800) * 1e9)
                # self.debug("Requesting history since: %s" % time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(time.time() - 172800)))
            else:
                querystring += "&since=%i" % (self.history_last_candle * 1e9)
                # self.debug("Last candle: %s" % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self.history_last_candle)))

            # self.debug("### requesting history")
            json_hist = http_request("%s://%s/0/public/Trades%s" % (
                self.proto,
                HTTP_HOST,
                querystring
            ))
            if json_hist and not self._terminating:
                try:
                    raw_history = json.loads(json_hist)

                    if raw_history['error']:
                        self.debug("Error in history: %s" % raw_history['error'])
                        return

                    # self.debug("History: %s" % raw_history)
                    history = []
                    for h in raw_history["result"][self.pair]:
                        history.append({
                            'price': float(h[0]),
                            'amount': float(h[1]),
                            'date': h[2]
                        })
                    if history:
                        self.signal_fullhistory(self, history)
                except Exception as exc:
                    self.debug("### exception in history_thread:", exc)

        start_thread(history_thread, "http request trade history")
Example #3
0
    def request_history(self):
        """request trading history"""
        # Api() will have set this field to the timestamp of the last
        # known candle, so we only request data since this time
        # since = self.history_last_candle

        def history_thread():
            """request trading history"""

            if not self.history_last_candle:
                querystring = "&start=%i&end=%i" % ((time.time() - 172800), (time.time() - 86400))
                # self.debug("### requesting 2d history since %s" % time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(time.time() - 172800)))
            else:
                querystring = "&start=%i" % (self.history_last_candle - 14400)
                # self.debug("Last candle: %s" % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self.history_last_candle - 14400)))

            json_hist = http_request("%s://%s/public?command=returnTradeHistory&currencyPair=%s%s" % (
                self.proto,
                HTTP_HOST,
                self.pair,
                querystring
            ))
            if json_hist and not self._terminating:
                try:
                    raw_history = json.loads(json_hist)

                    # self.debug("History: %s" % raw_history)

                    history = []
                    for h in reversed(raw_history):
                        history.append({
                            'price': float(h['rate']),
                            'amount': float(h['amount']),
                            'date': time.mktime(time.strptime(h['date'], "%Y-%m-%d %H:%M:%S")) - 480
                        })

                    # self.debug("History: %s" % history)

                    if history and not self._terminating:
                        self.signal_fullhistory(self, history)
                except Exception as exc:
                    self.debug("### exception in history_thread:", exc)

        start_thread(history_thread, "http request trade history")
Example #4
0
    def request_fulldepth(self):
        """start the fulldepth thread"""

        def fulldepth_thread():
            """request the full market depth, initialize the order book
            and then terminate. This is called in a separate thread after
            the streaming API has been connected."""
            # self.debug("### requesting full depth")
            json_depth = http_request("%s://%s/public?command=returnOrderBook&currencyPair=%s&depth=500" % (
                self.proto,
                HTTP_HOST,
                self.pair
            ))
            if json_depth and not self._terminating:
                try:
                    fulldepth = json.loads(json_depth)

                    # self.debug("Depth: %s" % fulldepth)

                    depth = {}
                    depth['error'] = {}

                    if 'error' in fulldepth:
                        depth['error'] = fulldepth['error']

                    depth['data'] = {'asks': [], 'bids': []}

                    for ask in fulldepth['asks']:
                        depth['data']['asks'].append({
                            'price': float(ask[0]),
                            'amount': float(ask[1])
                        })
                    for bid in reversed(fulldepth['bids']):
                        depth['data']['bids'].append({
                            'price': float(bid[0]),
                            'amount': float(bid[1])
                        })

                    self.signal_fulldepth(self, depth)
                except Exception as exc:
                    self.debug("### exception in fulldepth_thread:", exc)

        start_thread(fulldepth_thread, "http request full depth")
Example #5
0
    def request_ticker(self):
        """Request ticker"""
        def ticker_thread():
            querystring = "?pair=%s" % self.pair
            json_ticker = http_request("%s://%s/0/public/Ticker%s" % (
                self.proto,
                HTTP_HOST,
                querystring
            ))
            if not self._terminating:
                try:
                    answer = json.loads(json_ticker)
                    # self.debug("TICK %s" % answer)
                    if not answer["error"]:
                        bid = float(answer['result'][self.pair]['b'][0])
                        ask = float(answer['result'][self.pair]['a'][0])
                        self.signal_ticker(self, (bid, ask))
                except Exception as exc:
                    self.debug("### exception in ticker_thread:", exc)

        start_thread(ticker_thread, "http request ticker")
Example #6
0
    def request_fulldepth(self):
        """Start the fulldepth thread"""

        def fulldepth_thread():
            """Request the full market depth, initialize the order book
            and then terminate. This is called in a separate thread after
            the streaming API has been connected."""
            querystring = "?pair=%s" % self.pair
            # self.debug("### requesting full depth")
            json_depth = http_request("%s://%s/0/public/Depth%s" % (
                self.proto,
                HTTP_HOST,
                querystring
            ))
            if json_depth and not self._terminating:
                try:
                    fulldepth = json.loads(json_depth)
                    depth = {}
                    depth['error'] = fulldepth['error']
                    # depth['data'] = fulldepth['result']
                    depth['data'] = {'asks': [], 'bids': []}
                    for ask in fulldepth['result'][self.pair]['asks']:
                        depth['data']['asks'].append({
                            'price': float(ask[0]),
                            'amount': float(ask[1])
                        })
                    for bid in reversed(fulldepth['result'][self.pair]['bids']):
                        depth['data']['bids'].append({
                            'price': float(bid[0]),
                            'amount': float(bid[1])
                        })
                    if depth:
                        self.signal_fulldepth(self, (depth))
                except Exception as exc:
                    self.debug("### exception in fulldepth_thread:", exc)

        start_thread(fulldepth_thread, "http request full depth")
Example #7
0
 def start(self):
     """start the client"""
     self._recv_thread = start_thread(self._recv_thread_func, "socket receive thread")
     self._http_thread = start_thread(self._http_thread_func, "http thread")
Example #8
0
 def start(self):
     """Start the client"""
     self._http_thread = start_thread(self._http_thread_func, "http thread")