def get_order_history(self, pair, since=None, until=int(time.time())): """Returns the past 200 trades, or up to 50,000 trades between a range specified in UNIX timestamps by the "start" and "end" GET parameters.""" if pair is not "all": query = {"command": "returnTradeHistory", "currencyPair": self.format_pair(pair)} else: query = {"command": "returnTradeHistory", "currencyPair": 'all'} if since is None: # default, return 200 last trades return self.private_api(query) if since > time.time(): raise APIError("AYYY LMAO start time is in the future, take it easy.") if self._to_timestamp(datetime.datetime.now() - self.time_limit) <= since: query.update({"start": str(since), "end": str(until)} ) return self.private_api(query) else: raise APIError('''Poloniex API does no support queries for data older than a year.\n Earilest data we can get is since {0} UTC'''.format((datetime.datetime.now() - self.time_limit).isoformat()) )
def api(cls, command, params): """call api""" if "usd" in params[ "symbol"]: # OKcoin API uses .com domain for USD pairs result = requests.get(cls.url.replace("$", "com") + command, params=params, headers=cls.headers, timeout=3) if "cny" in params[ "symbol"]: # OKcoin API uses .cn domain for CNY pairs result = requests.get(cls.url.replace("$", "cn") + command, params=params, headers=cls.headers, timeout=3) assert result.status_code == 200, { "error": "http_error: " + str(result.status_code) } try: ## try to get the error if result.json().get("result") is False: try: # API is not consistant about naming error field raise APIError( cls.error_codes.get(result.json()["errorCode"])) except KeyError: raise APIError( cls.error_codes.get(result.json()["error_code"])) except AttributeError: pass return result.json()
def api(cls, url): '''call api''' try: result = requests.get(url, headers=cls.headers, timeout=3) assert result.status_code == 200 return result.json() except requests.exceptions.RequestException as e: raise APIError(e)
def private_api(self, command, params): '''handles private api methods''' if not self.apikey or not self.secret: raise ValueError("API key and secret key required!") params["api_key"] = self.apikey params["sign"] = self.build_signature(params) result = requests.post(self.url.replace("$", "com") + command, params=params, headers=self.headers, timeout=3) if self.domain == "com": result = requests.get(self.url.replace("$", "com") + command, params=params, headers=self.headers, timeout=3) if self.domain == "cny": result = requests.get(self.url.replace("$", "cn") + command, params=params, headers=self.headers, timeout=3) assert result.status_code == 200, { "error": "http_error: " + str(result.status_code) } try: ## try to get the error if result.json().get("result") is False: # API is not consistent about naming error field if result.json()["errorCode"]: raise APIError( self.error_codes.get(result.json()["errorCode"])) else: raise APIError( self.error_codes.get(result.json()["error_code"])) except AttributeError: pass return result.json()
def api(cls, params): '''API calls''' assert params["command"] in cls.public_commands try: result = cls.api_session.get(cls.url + "public?", params=params, headers=cls.headers, timeout=cls.timeout) assert result.status_code == 200, {"error": "http_error: " + str(result.status_code)} return result.json() except requests.exceptions.RequestException as e: raise APIError(e)
def get_deposits_withdrawals(self, since=None, until=int(time.time())): """Returns your deposit and withdrawal history within a range, specified by the <since> and <until> parameters, both of which should be given as UNIX timestamps. (defaults to 1 month)""" if not since: since = self._to_timestamp(self._subtract_one_month( datetime.datetime.now())) if since > time.time(): raise APIError("Start time can't be future.") return self.private_api({'command': 'returnDepositsWithdrawals', 'start': since, 'end': until})
def get_market_trade_history(cls, pair, depth=200, since=None, until=int(time.time())): """Requests trade history for >pair<, of <depth> from >since< to >until< selected timeframe expressed in seconds (unix time) Each request is limited to 50000 trades or 1 year. If called without arguments, it will request last 200 trades for the pair.""" query = {"command": "returnTradeHistory", "currencyPair": cls.format_pair(pair)} if depth is None: depth = 200 if since is None and depth is not None and depth > 200: raise APIError("You can't get depth > 200 without <since> argument.") if since is None: # default, return 200 last trades if depth is not None: return cls.api(query)[-depth:] else: return cls.api(query) if since > time.time(): raise APIError("AYYY LMAO start time is in the future, take it easy.") if since is not None and cls._to_timestamp(datetime.datetime.now() - cls.time_limit) <= since: query.update({"start": str(since), "end": str(until)} ) return cls.api(query) else: raise APIError('''Poloniex API does no support queries for data older than a month. Earilest data we can get is since {0} UTC'''.format(( datetime.datetime.now() - cls.time_limit).isoformat()) )
def get_market_trade_history(cls, pair, limit=1000): """get market trade history""" pair = cls.format_pair(pair) if limit > 2000: raise APIError("Btc-e API can only return last 2000 trades.") if not isinstance(pair, list): return cls.api("trades" + "/" + pair + "/?limit={0}".format(limit))[pair] if pair == "all": # returns market history for all pairs with default history size. return cls.api("trades" + "/" + "-".join(cls.get_markets() + "/?limit={0}".format(limit))) else: # simply concat pairs in the list return cls.api("trades" + "/" + "-".join(pair) + "/?limit={0}".format(limit))
def get_lending_history(self, since=None, until=int(time.time()), limit=None): ''' Returns your lending history within a time range specified by the <since> and <until> parameters as UNIX timestamps. <limit> may also be specified to limit the number of rows returned. ''' if not since: since = self.to_timestamp(self.subtract_one_month(datetime.datetime.now() )) if since > time.time(): raise APIError("Start time can't be future.") return self.private_api({'command': 'returnLendingHistory', 'start': since, 'end': until, 'limit': limit})
def private_api(self, data): '''private API methods which require authentication''' assert data["command"] in self.private_commands if not self.apikey or not self.secret: raise ValueError("A Key and Secret needed!") data["nonce"] = self.get_nonce() # add nonce to post data pdata = requests.compat.urlencode(data).encode("utf-8") self.headers.update( {"Sign": hmac.new(self.secret, pdata, hashlib.sha512).hexdigest(), "Key": self.apikey }) try: result = requests.post(self.url + "tradingApi", data=data, headers=self.headers, timeout=self.timeout) #assert result.status_code == 200 return result.json() except requests.exceptions.RequestException as e: return APIError(e)