Guest User

Poloniex Python API Modified for Lending

a guest
Aug 26th, 2016
356
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.41 KB | None | 0 0
  1. #SEARCH TECHNIUM UNLIMITED FOR THE ACTUAL BOT, THAT REQUIRES THIS API, and FOR INSTRUCTIONS
  2. #PASTEBIN SCREWS UP SPACING, YOU MAY HAVE TO EDIT MANUALLY!
  3.  
  4. import urllib
  5. import urllib2
  6. import json
  7. import time
  8. import hmac,hashlib
  9.  
  10. def createTimeStamp(datestr, format="%Y-%m-%d %H:%M:%S"):
  11.     return time.mktime(time.strptime(datestr, format))
  12.  
  13. class Poloniex:
  14.     def __init__(self, APIKey, Secret):
  15.         self.APIKey = APIKey
  16.         self.Secret = Secret
  17.  
  18.     def post_process(self, before):
  19.         after = before
  20.  
  21.         # Add timestamps if there isnt one but is a datetime
  22.         if('return' in after):
  23.             if(isinstance(after['return'], list)):
  24.                 for x in xrange(0, len(after['return'])):
  25.                     if(isinstance(after['return'][x], dict)):
  26.                         if('datetime' in after['return'][x] and 'timestamp' not in after['return'][x]):
  27.                             after['return'][x]['timestamp'] = float(createTimeStamp(after['return'][x]['datetime']))
  28.                            
  29.         return after
  30.  
  31.     def api_query(self, command, req={}):
  32.  
  33.         if(command == "returnTicker" or command == "return24hVolume"):
  34.             ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=' + command))
  35.             return json.loads(ret.read())
  36.         elif(command == "returnOrderBook"):
  37.             ret = urllib2.urlopen(urllib2.Request('http://poloniex.com/public?command=' + command + '&currencyPair=' + str(req['currencyPair'])))
  38.             return json.loads(ret.read())
  39.         elif(command == "returnMarketTradeHistory"):
  40.             ret = urllib2.urlopen(urllib2.Request('http://poloniex.com/public?command=' + "returnTradeHistory" + '&currencyPair=' + str(req['currencyPair'])))
  41.             return json.loads(ret.read())
  42.         elif(command == "returnLoanOrders"):
  43.             ret = urllib2.urlopen(urllib2.Request('http://poloniex.com/public?command=' + "returnLoanOrders" + '&currency=' + str(req['currency'])))
  44.             return json.loads(ret.read())
  45.         else:
  46.             req['command'] = command
  47.             req['nonce'] = int(time.time()*1000)
  48.             post_data = urllib.urlencode(req)
  49.  
  50.             sign = hmac.new(self.Secret, post_data, hashlib.sha512).hexdigest()
  51.             headers = {
  52.                 'Sign': sign,
  53.                 'Key': self.APIKey
  54.             }
  55.  
  56.             ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/tradingApi', post_data, headers))
  57.             jsonRet = json.loads(ret.read())
  58.             return self.post_process(jsonRet)
  59.  
  60.  
  61.     def returnTicker(self):
  62.         return self.api_query("returnTicker")
  63.  
  64.     def return24hVolume(self):
  65.         return self.api_query("return24hVolume")
  66.  
  67.     def returnOrderBook (self, currencyPair):
  68.         return self.api_query("returnOrderBook", {'currencyPair': currencyPair})
  69.  
  70.     def returnMarketTradeHistory (self, currencyPair):
  71.         return self.api_query("returnMarketTradeHistory", {'currencyPair': currencyPair})
  72.  
  73.  
  74.     # Returns all of your balances.
  75.     # Outputs:
  76.     # {"BTC":"0.59098578","LTC":"3.31117268", ... }
  77.     def returnBalances(self):
  78.         return self.api_query('returnBalances')
  79.  
  80.     def returnAvailableAccountBalances(self,account):
  81.         return self.api_query('returnAvailableAccountBalances',{"account":account})
  82.  
  83.     # Returns your open orders for a given market, specified by the "currencyPair" POST parameter, e.g. "BTC_XCP"
  84.     # Inputs:
  85.     # currencyPair  The currency pair e.g. "BTC_XCP"
  86.     # Outputs:
  87.     # orderNumber   The order number
  88.     # type          sell or buy
  89.     # rate          Price the order is selling or buying at
  90.     # Amount        Quantity of order
  91.     # total         Total value of order (price * quantity)
  92.     def returnOpenOrders(self,currencyPair):
  93.         return self.api_query('returnOpenOrders',{"currencyPair":currencyPair})
  94.  
  95.     def returnOpenLoanOffers(self,currency):
  96.         return self.api_query('returnOpenLoanOffers',{"currency":currency})
  97.  
  98.     def returnActiveLoans(self):
  99.         return self.api_query('returnActiveLoans')
  100.  
  101.     # Returns your trade history for a given market, specified by the "currencyPair" POST parameter
  102.     # Inputs:
  103.     # currencyPair  The currency pair e.g. "BTC_XCP"
  104.     # Outputs:
  105.     # date          Date in the form: "2014-02-19 03:44:59"
  106.     # rate          Price the order is selling or buying at
  107.     # amount        Quantity of order
  108.     # total         Total value of order (price * quantity)
  109.     # type          sell or buy
  110.     def returnTradeHistory(self,currencyPair):
  111.         return self.api_query('returnTradeHistory',{"currencyPair":currencyPair})
  112.  
  113.     # 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.
  114.     # Inputs:
  115.     # currencyPair  The curreny pair
  116.     # rate          price the order is buying at
  117.     # amount        Amount of coins to buy
  118.     # Outputs:
  119.     # orderNumber   The order number
  120.     def buy(self,currencyPair,rate,amount):
  121.         return self.api_query('buy',{"currencyPair":currencyPair,"rate":rate,"amount":amount})
  122.  
  123.     # 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.
  124.     # Inputs:
  125.     # currencyPair  The curreny pair
  126.     # rate          price the order is selling at
  127.     # amount        Amount of coins to sell
  128.     # Outputs:
  129.     # orderNumber   The order number
  130.     def sell(self,currencyPair,rate,amount):
  131.         return self.api_query('sell',{"currencyPair":currencyPair,"rate":rate,"amount":amount})
  132.  
  133.     def createLoanOffer(self,currency,amount,duration,autoRenew,lendingRate):
  134.         return self.api_query('createLoanOffer',{"currency":currency,"amount":amount,"duration":duration,"autoRenew":autoRenew,"lendingRate":lendingRate,})
  135.  
  136.     # Cancels an order you have placed in a given market. Required POST parameters are "currencyPair" and "orderNumber".
  137.     # Inputs:
  138.     # currencyPair  The curreny pair
  139.     # orderNumber   The order number to cancel
  140.     # Outputs:
  141.     # succes        1 or 0
  142.     def cancel(self,currencyPair,orderNumber):
  143.         return self.api_query('cancelOrder',{"currencyPair":currencyPair,"orderNumber":orderNumber})
  144.  
  145.     def cancelLoanOffer(self,currency,orderNumber):
  146.         return self.api_query('cancelLoanOffer',{"currency":currency,"orderNumber":orderNumber})
  147.  
  148.     # 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."}
  149.     # Inputs:
  150.     # currency      The currency to withdraw
  151.     # amount        The amount of this coin to withdraw
  152.     # address       The withdrawal address
  153.     # Outputs:
  154.     # response      Text containing message about the withdrawal
  155.     def withdraw(self, currency, amount, address):
  156.         return self.api_query('withdraw',{"currency":currency, "amount":amount, "address":address})
  157.  
  158.     def returnLoanOrders(self,currency):
  159.         return self.api_query('returnLoanOrders',{"currency":currency})
  160.  
  161.     # Toggles the auto renew setting for the specified orderNumber
  162.     def toggleAutoRenew(self, orderNumber):
  163.         return self.api_query('toggleAutoRenew',{"orderNumber":orderNumber})
Advertisement
Add Comment
Please, Sign In to add comment