Advertisement
Guest User

Poloniex api python wrapper version 2

a guest
Sep 8th, 2014
13,229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import urllib
  2. import urllib2
  3. import json
  4. import time
  5. import hmac,hashlib
  6.  
  7. def createTimeStamp(datestr, format="%Y-%m-%d %H:%M:%S"):
  8.     return time.mktime(time.strptime(datestr, format))
  9.  
  10. class poloniex:
  11.     def __init__(self, APIKey, Secret):
  12.         self.APIKey = APIKey
  13.         self.Secret = Secret
  14.  
  15.     def post_process(self, before):
  16.         after = before
  17.  
  18.         # Add timestamps if there isnt one but is a datetime
  19.         if('return' in after):
  20.             if(isinstance(after['return'], list)):
  21.                 for x in xrange(0, len(after['return'])):
  22.                     if(isinstance(after['return'][x], dict)):
  23.                         if('datetime' in after['return'][x] and 'timestamp' not in after['return'][x]):
  24.                             after['return'][x]['timestamp'] = float(createTimeStamp(after['return'][x]['datetime']))
  25.                            
  26.         return after
  27.  
  28.     def api_query(self, command, req={}):
  29.  
  30.         if(command == "returnTicker" or command == "return24Volume"):
  31.             ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=' + command))
  32.             return json.loads(ret.read())
  33.         elif(command == "returnOrderBook"):
  34.             ret = urllib2.urlopen(urllib2.Request('http://poloniex.com/public?command=' + command + '&currencyPair=' + str(req['currencyPair'])))
  35.             return json.loads(ret.read())
  36.         elif(command == "returnMarketTradeHistory"):
  37.             ret = urllib2.urlopen(urllib2.Request('http://poloniex.com/public?command=' + "returnTradeHistory" + '&currencyPair=' + str(req['currencyPair'])))
  38.             return json.loads(ret.read())
  39.         else:
  40.             req['command'] = command
  41.             req['nonce'] = int(time.time()*1000)
  42.             post_data = urllib.urlencode(req)
  43.  
  44.             sign = hmac.new(self.Secret, post_data, hashlib.sha512).hexdigest()
  45.             headers = {
  46.                 'Sign': sign,
  47.                 'Key': self.APIKey
  48.             }
  49.  
  50.             ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/tradingApi', post_data, headers))
  51.             jsonRet = json.loads(ret.read())
  52.             return self.post_process(jsonRet)
  53.  
  54.  
  55.     def returnTicker(self):
  56.         return self.api_query("returnTicker")
  57.  
  58.     def return24Volume(self):
  59.         return self.api_query("return24Volume")
  60.  
  61.     def returnOrderBook (self, currencyPair):
  62.         return self.api_query("returnOrderBook", {'currencyPair': currencyPair})
  63.  
  64.     def returnMarketTradeHistory (self, currencyPair):
  65.         return self.api_query("returnMarketTradeHistory", {'currencyPair': currencyPair})
  66.  
  67.  
  68.     # Returns all of your balances.
  69.     # Outputs:
  70.     # {"BTC":"0.59098578","LTC":"3.31117268", ... }
  71.     def returnBalances(self):
  72.         return self.api_query('returnBalances')
  73.  
  74.     # Returns your open orders for a given market, specified by the "currencyPair" POST parameter, e.g. "BTC_XCP"
  75.     # Inputs:
  76.     # currencyPair  The currency pair e.g. "BTC_XCP"
  77.     # Outputs:
  78.     # orderNumber   The order number
  79.     # type          sell or buy
  80.     # rate          Price the order is selling or buying at
  81.     # Amount        Quantity of order
  82.     # total         Total value of order (price * quantity)
  83.     def returnOpenOrders(self,currencyPair):
  84.         return self.api_query('returnOpenOrders',{"currencyPair":currencyPair})
  85.  
  86.  
  87.     # Returns your trade history for a given market, specified by the "currencyPair" POST parameter
  88.     # Inputs:
  89.     # currencyPair  The currency pair e.g. "BTC_XCP"
  90.     # Outputs:
  91.     # date          Date in the form: "2014-02-19 03:44:59"
  92.     # rate          Price the order is selling or buying at
  93.     # amount        Quantity of order
  94.     # total         Total value of order (price * quantity)
  95.     # type          sell or buy
  96.     def returnTradeHistory(self,currencyPair):
  97.         return self.api_query('returnTradeHistory',{"currencyPair":currencyPair})
  98.  
  99.     # Places a buy order in a given market. Required POST parameters are "currencyPair", "rate", and "amount". If successful, the method will return the order number.
  100.     # Inputs:
  101.     # currencyPair  The curreny pair
  102.     # rate          price the order is buying at
  103.     # amount        Amount of coins to buy
  104.     # Outputs:
  105.     # orderNumber   The order number
  106.     def buy(self,currencyPair,rate,amount):
  107.         return self.api_query('buy',{"currencyPair":currencyPair,"rate":rate,"amount":amount})
  108.  
  109.     # Places a sell order in a given market. Required POST parameters are "currencyPair", "rate", and "amount". If successful, the method will return the order number.
  110.     # Inputs:
  111.     # currencyPair  The curreny pair
  112.     # rate          price the order is selling at
  113.     # amount        Amount of coins to sell
  114.     # Outputs:
  115.     # orderNumber   The order number
  116.     def sell(self,currencyPair,rate,amount):
  117.         return self.api_query('sell',{"currencyPair":currencyPair,"rate":rate,"amount":amount})
  118.  
  119.     # Cancels an order you have placed in a given market. Required POST parameters are "currencyPair" and "orderNumber".
  120.     # Inputs:
  121.     # currencyPair  The curreny pair
  122.     # orderNumber   The order number to cancel
  123.     # Outputs:
  124.     # succes        1 or 0
  125.     def cancel(self,currencyPair,orderNumber):
  126.         return self.api_query('cancelOrder',{"currencyPair":currencyPair,"orderNumber":orderNumber})
  127.  
  128.     # Immediately places a withdrawal for a given currency, with no email confirmation. In order to use this method, the withdrawal privilege must be enabled for your API key. Required POST parameters are "currency", "amount", and "address". Sample output: {"response":"Withdrew 2398 NXT."}
  129.     # Inputs:
  130.     # currency      The currency to withdraw
  131.     # amount        The amount of this coin to withdraw
  132.     # address       The withdrawal address
  133.     # Outputs:
  134.     # response      Text containing message about the withdrawal
  135.     def withdraw(self, currency, amount, address):
  136.         return self.api_query('withdraw',{"currency":currency, "amount":amount, "address":address})
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement