Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Python Wrapper v1.2 Poloniex API, some bugs fixed (2014 May 31st)
- #
- # Original code copied from https://poloniex.com/api http://pastebin.com/SB5c4Yr1 (unknown author)
- # Some bugs repaired by me. Thank me if you want to - BTC 19ZLhMMyJMAExiLCx3H5fPv9DYDUFsK4Hk
- import urllib
- import urllib2
- import json
- import time
- import hmac,hashlib
- def createTimeStamp(datestr, stampformat="%Y-%m-%d %H:%M:%S"):
- return time.mktime(time.strptime(datestr, stampformat))
- class poloniex:
- def __init__(self, APIKey, Secret):
- self.APIKey = APIKey
- self.Secret = Secret
- def post_process(self, before):
- after = before
- # Add timestamps if there isnt one but is a datetime
- if('return' in after):
- if(isinstance(after['return'], list)):
- for x in xrange(0, len(after['return'])):
- if(isinstance(after['return'][x], dict)):
- if('datetime' in after['return'][x] and 'timestamp' not in after['return'][x]):
- after['return'][x]['timestamp'] = float(createTimeStamp(after['return'][x]['datetime']))
- return after
- def api_query(self, command, req={}):
- if(command == "returnTicker" or command == "return24Volume"):
- ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=' + command))
- return json.loads(ret.read())
- elif(command == "returnOrderBook"):
- ret = urllib2.urlopen(urllib2.Request('http://poloniex.com/public?command=' + command + '¤cyPair=' + str(req['currencyPair'])))
- return json.loads(ret.read())
- elif(command == "returnMarketTradeHistory"):
- ret = urllib2.urlopen(urllib2.Request('http://poloniex.com/public?command=' + "returnTradeHistory" + '¤cyPair=' + str(req['currencyPair'])))
- return json.loads(ret.read())
- else:
- req['command'] = command
- req['nonce'] = int(time.time()*1000)
- post_data = urllib.urlencode(req)
- sign = hmac.new(self.Secret, post_data, hashlib.sha512).hexdigest()
- headers = {
- 'Sign': sign,
- 'Key': self.APIKey
- }
- ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/tradingApi', post_data, headers))
- jsonRet = json.loads(ret.read())
- return self.post_process(jsonRet)
- def returnTicker(self):
- return self.api_query("returnTicker")
- def return24Volume(self):
- return self.api_query("return24Volume")
- def returnOrderBook (self, currencyPair):
- return self.api_query("returnOrderBook", {'currencyPair': currencyPair})
- def returnMarketTradeHistory (self, currencyPair):
- return self.api_query("returnMarketTradeHistory", {'currencyPair': currencyPair})
- # Returns all of your balances.
- # Outputs:
- # {"BTC":"0.59098578","LTC":"3.31117268", ... }
- def returnBalances(self):
- return self.api_query('returnBalances')
- # Returns all of your deposit addresses. Sample output:
- # {"BTC":"19YqztHmspv2egyD6jQM3yn81x5t5krVdJ","LTC":"LPgf9kjv9H1Vuh4XSaKhzBe8JHdou1WgUB", ... "ITC":"Press Generate.." ... }
- def returnDepositAddresses(self):
- return self.api_query('returnDepositAddresses')
- # Returns your deposit and withdrawal history within a range,
- # specified by the "start" and "end" POST parameters,
- # both of which should be given as UNIX timestamps. Sample output:
- # {"deposits":
- # [{"currency":"BTC","address":"...","amount":"0.01006132","confirmations":10,
- # "txid":"17f819a91369a9ff6c4a34216d434597cfc1b4a3d0489b46bd6f924137a47701","timestamp":1399305798,"status":"COMPLETE"},{"currency":"BTC","address":"...","amount":"0.00404104","confirmations":10,
- # "txid":"7acb90965b252e55a894b535ef0b0b65f45821f2899e4a379d3e43799604695c","timestamp":1399245916,"status":"COMPLETE"}],
- # "withdrawals":[{"withdrawalNumber":134933,"currency":"BTC","address":"1N2i5n8DwTGzUq2Vmn9TUL8J1vdr1XBDFg","amount":"5.00010000",
- # "timestamp":1399267904,"status":"COMPLETE: 36e483efa6aff9fd53a235177579d98451c4eb237c210e66cd2b9a2d4a988f8e","ipAddress":"..."}]}
- def returnDepositsWithdrawals(self, start, end):
- return self.api_query('returnDepositsWithdrawals',{"start":start, "end":end})
- # Returns your open orders for a given market, specified by the "currencyPair" POST parameter, e.g. "BTC_XCP"
- # Inputs:
- # currencyPair The currency pair e.g. "BTC_XCP"
- # Outputs:
- # orderNumber The order number
- # type sell or buy
- # rate Price the order is selling or buying at
- # Amount Quantity of order
- # total Total value of order (price * quantity)
- def returnOpenOrders(self,currencyPair):
- return self.api_query('returnOpenOrders',{"currencyPair":currencyPair})
- # Returns your trade history for a given market, specified by the "currencyPair" POST parameter
- # Inputs:
- # currencyPair The currency pair e.g. "BTC_XCP"
- # Outputs:
- # date Date in the form: "2014-02-19 03:44:59"
- # rate Price the order is selling or buying at
- # amount Quantity of order
- # total Total value of order (price * quantity)
- # type sell or buy
- def returnTradeHistory(self,currencyPair):
- return self.api_query('returnTradeHistory',{"currencyPair":currencyPair})
- # 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.
- # Inputs:
- # currencyPair The curreny pair
- # rate price the order is buying at
- # amount Amount of coins to buy
- # Outputs:
- # orderNumber The order number
- def buy(self,currencyPair,rate,amount):
- return self.api_query('buy',{"currencyPair":currencyPair,"rate":rate,"amount":amount})
- # 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.
- # Inputs:
- # currencyPair The curreny pair
- # rate price the order is selling at
- # amount Amount of coins to sell
- # Outputs:
- # orderNumber The order number
- def sell(self,currencyPair,rate,amount):
- return self.api_query('sell',{"currencyPair":currencyPair,"rate":rate,"amount":amount})
- # Cancels an order you have placed in a given market.
- # Required POST parameters are "currencyPair" and "orderNumber".
- # Inputs:
- # currencyPair The curreny pair
- # orderNumber The order number to cancel
- # Outputs:
- # succes 1 or 0
- def cancelOrder(self,currencyPair,orderNumber):
- return self.api_query('cancelOrder',{"currencyPair":currencyPair,"orderNumber":orderNumber})
- # 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."}
- # Inputs:
- # currency The currency to withdraw
- # amount The amount of this coin to withdraw
- # address The withdrawal address
- # Outputs:
- # response Text containing message about the withdrawal
- def withdraw(self, currency, amount, address):
- return self.api_query('withdraw',{"currency":currency, "amount":amount, "address":address})
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement