Advertisement
drakoin

Python Wrapper v1.2 Poloniex API, bugs fixed (2014 May 31st)

Jul 14th, 2014
883
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.63 KB | None | 0 0
  1. # Python Wrapper v1.2 Poloniex API, some bugs fixed (2014 May 31st)
  2. #
  3. # Original code copied from https://poloniex.com/api  http://pastebin.com/SB5c4Yr1 (unknown author)
  4. # Some bugs repaired by me. Thank me if you want to - BTC 19ZLhMMyJMAExiLCx3H5fPv9DYDUFsK4Hk
  5.  
  6. import urllib
  7. import urllib2
  8. import json
  9. import time
  10. import hmac,hashlib
  11.  
  12. def createTimeStamp(datestr, stampformat="%Y-%m-%d %H:%M:%S"):
  13.     return time.mktime(time.strptime(datestr, stampformat))
  14.  
  15. class poloniex:
  16.     def __init__(self, APIKey, Secret):
  17.         self.APIKey = APIKey
  18.         self.Secret = Secret
  19.  
  20.     def post_process(self, before):
  21.         after = before
  22.  
  23.         # Add timestamps if there isnt one but is a datetime
  24.         if('return' in after):
  25.             if(isinstance(after['return'], list)):
  26.                 for x in xrange(0, len(after['return'])):
  27.                     if(isinstance(after['return'][x], dict)):
  28.                         if('datetime' in after['return'][x] and 'timestamp' not in after['return'][x]):
  29.                             after['return'][x]['timestamp'] = float(createTimeStamp(after['return'][x]['datetime']))
  30.                            
  31.         return after
  32.  
  33.     def api_query(self, command, req={}):
  34.  
  35.         if(command == "returnTicker" or command == "return24Volume"):
  36.             ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=' + command))
  37.             return json.loads(ret.read())
  38.         elif(command == "returnOrderBook"):
  39.             ret = urllib2.urlopen(urllib2.Request('http://poloniex.com/public?command=' + command + '&currencyPair=' + str(req['currencyPair'])))
  40.             return json.loads(ret.read())
  41.         elif(command == "returnMarketTradeHistory"):
  42.             ret = urllib2.urlopen(urllib2.Request('http://poloniex.com/public?command=' + "returnTradeHistory" + '&currencyPair=' + str(req['currencyPair'])))
  43.             return json.loads(ret.read())
  44.         else:
  45.             req['command'] = command
  46.             req['nonce'] = int(time.time()*1000)
  47.             post_data = urllib.urlencode(req)
  48.  
  49.             sign = hmac.new(self.Secret, post_data, hashlib.sha512).hexdigest()
  50.             headers = {
  51.                 'Sign': sign,
  52.                 'Key': self.APIKey
  53.             }
  54.  
  55.             ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/tradingApi', post_data, headers))
  56.             jsonRet = json.loads(ret.read())
  57.             return self.post_process(jsonRet)
  58.  
  59.  
  60.     def returnTicker(self):
  61.         return self.api_query("returnTicker")
  62.  
  63.     def return24Volume(self):
  64.         return self.api_query("return24Volume")
  65.  
  66.     def returnOrderBook (self, currencyPair):
  67.         return self.api_query("returnOrderBook", {'currencyPair': currencyPair})
  68.  
  69.     def returnMarketTradeHistory (self, currencyPair):
  70.         return self.api_query("returnMarketTradeHistory", {'currencyPair': currencyPair})
  71.  
  72.  
  73.     # Returns all of your balances.
  74.     # Outputs:
  75.     # {"BTC":"0.59098578","LTC":"3.31117268", ... }
  76.     def returnBalances(self):
  77.         return self.api_query('returnBalances')
  78.  
  79.  
  80.     # Returns all of your deposit addresses. Sample output:
  81.     # {"BTC":"19YqztHmspv2egyD6jQM3yn81x5t5krVdJ","LTC":"LPgf9kjv9H1Vuh4XSaKhzBe8JHdou1WgUB", ... "ITC":"Press Generate.." ... }
  82.     def returnDepositAddresses(self):
  83.         return self.api_query('returnDepositAddresses')
  84.  
  85.     # Returns your deposit and withdrawal history within a range,
  86.     # specified by the "start" and "end" POST parameters,
  87.     # both of which should be given as UNIX timestamps. Sample output:
  88.     # {"deposits":
  89.     # [{"currency":"BTC","address":"...","amount":"0.01006132","confirmations":10,
  90.     # "txid":"17f819a91369a9ff6c4a34216d434597cfc1b4a3d0489b46bd6f924137a47701","timestamp":1399305798,"status":"COMPLETE"},{"currency":"BTC","address":"...","amount":"0.00404104","confirmations":10,
  91.     # "txid":"7acb90965b252e55a894b535ef0b0b65f45821f2899e4a379d3e43799604695c","timestamp":1399245916,"status":"COMPLETE"}],
  92.     # "withdrawals":[{"withdrawalNumber":134933,"currency":"BTC","address":"1N2i5n8DwTGzUq2Vmn9TUL8J1vdr1XBDFg","amount":"5.00010000",
  93.     # "timestamp":1399267904,"status":"COMPLETE: 36e483efa6aff9fd53a235177579d98451c4eb237c210e66cd2b9a2d4a988f8e","ipAddress":"..."}]}
  94.    
  95.     def returnDepositsWithdrawals(self, start, end):
  96.         return self.api_query('returnDepositsWithdrawals',{"start":start, "end":end})
  97.  
  98.     # Returns your open orders for a given market, specified by the "currencyPair" POST parameter, e.g. "BTC_XCP"
  99.     # Inputs:
  100.     # currencyPair  The currency pair e.g. "BTC_XCP"
  101.     # Outputs:
  102.     # orderNumber   The order number
  103.     # type          sell or buy
  104.     # rate          Price the order is selling or buying at
  105.     # Amount        Quantity of order
  106.     # total         Total value of order (price * quantity)
  107.     def returnOpenOrders(self,currencyPair):
  108.         return self.api_query('returnOpenOrders',{"currencyPair":currencyPair})
  109.  
  110.  
  111.     # Returns your trade history for a given market, specified by the "currencyPair" POST parameter
  112.     # Inputs:
  113.     # currencyPair  The currency pair e.g. "BTC_XCP"
  114.     # Outputs:
  115.     # date          Date in the form: "2014-02-19 03:44:59"
  116.     # rate          Price the order is selling or buying at
  117.     # amount        Quantity of order
  118.     # total         Total value of order (price * quantity)
  119.     # type          sell or buy
  120.     def returnTradeHistory(self,currencyPair):
  121.         return self.api_query('returnTradeHistory',{"currencyPair":currencyPair})
  122.  
  123.     # 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.
  124.     # Inputs:
  125.     # currencyPair  The curreny pair
  126.     # rate          price the order is buying at
  127.     # amount        Amount of coins to buy
  128.     # Outputs:
  129.     # orderNumber   The order number
  130.     def buy(self,currencyPair,rate,amount):
  131.         return self.api_query('buy',{"currencyPair":currencyPair,"rate":rate,"amount":amount})
  132.  
  133.     # 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.
  134.     # Inputs:
  135.     # currencyPair  The curreny pair
  136.     # rate          price the order is selling at
  137.     # amount        Amount of coins to sell
  138.     # Outputs:
  139.     # orderNumber   The order number
  140.     def sell(self,currencyPair,rate,amount):
  141.         return self.api_query('sell',{"currencyPair":currencyPair,"rate":rate,"amount":amount})
  142.  
  143.     # Cancels an order you have placed in a given market.
  144.     # Required POST parameters are "currencyPair" and "orderNumber".
  145.     # Inputs:
  146.     # currencyPair  The curreny pair
  147.     # orderNumber   The order number to cancel
  148.     # Outputs:
  149.     # succes        1 or 0
  150.     def cancelOrder(self,currencyPair,orderNumber):
  151.         return self.api_query('cancelOrder',{"currencyPair":currencyPair,"orderNumber":orderNumber})
  152.  
  153.     # Immediately places a withdrawal for a given currency, with no email confirmation.
  154.     # In order to use this method, the withdrawal privilege must be enabled for your API key.
  155.     # Required POST parameters are "currency", "amount", and "address".
  156.     # Sample output: {"response":"Withdrew 2398 NXT."}
  157.     # Inputs:
  158.     # currency      The currency to withdraw
  159.     # amount        The amount of this coin to withdraw
  160.     # address       The withdrawal address
  161.     # Outputs:
  162.     # response      Text containing message about the withdrawal
  163.     def withdraw(self, currency, amount, address):
  164.         return self.api_query('withdraw',{"currency":currency, "amount":amount, "address":address})
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement