# python 2.7
# POLONIEX.COM
# API 101 - BUY SELL CANCEL
# litepresence May 2017
CURRENCY = '' # currency ticker symbol
ASSET = '' # asset ticker symbol
APIKEY = '' # your api key
SECRET = '' # your api secret
CANCEL = True # True to cancel all outstanding orders first
ACTION = 'buy' # buy or sell
RATE = 0.0 # price
AMOUNT = 0.0 # asset quantity
#########################################################
# u a noob? be thankful and don't touch below here:
#########################################################
import hmac
import json
import hashlib
import requests
import time
PAIR = ('%s_%s' % (CURRENCY, ASSET))
class private: # keyed api access defitions; LIVE buy/sell etc.
def __init__(self, APIKey, Secret):
self.APIKey = APIKey
self.Secret = Secret
def api_query(self, payload={}):
uri="https://poloniex.com/tradingApi"
payload['nonce'] = int(time.time()*1000)
u={"'":""," ":"","{":"","}":"",",":"&",":":"="}
post_data=''.join(u[i] if i in u else i for i in str(payload))
sign = hmac.new(self.Secret, post_data, hashlib.sha512).hexdigest()
headers = {'Sign': sign,'Key': self.APIKey}
return addstamp(requests.post(uri,data=payload,headers=headers).json())
def orders(self,pair):
payload = {'command': 'returnOpenOrders','currencyPair': pair }
return self.api_query( payload=payload)
def cancel(self,pair,orderNumber):
payload = {'command': 'cancelOrder', 'currencyPair':pair,
'orderNumber':orderNumber}
return self.api_query(payload=payload)
def buy(self,pair,rate,amount):
payload = {'command': 'buy', 'currencyPair':pair,
'rate':('%.8f'%rate),'amount':('%.8f'%amount)}
return self.api_query(payload=payload)
def sell(self,pair,rate,amount):
payload = {'command': 'sell', 'currencyPair':pair,
'rate':('%.8f'%rate),'amount':('%.8f'%amount)}
return self.api_query(payload=payload)
def addstamp(b): # add unix timestamp if only 'date' or 'datetime' in dict
a=b
if ('return' in a) and (isinstance(a['return'], list)):
for x in xrange(0, len(a['return'])):
if (isinstance(a['return'][x], dict) and
('datetime' in a['return'][x]) and
('timestamp' not in a['return'][x])):
a['return'][x]['timestamp'] = float(
time.mktime(time.strptime(
a['return'][x]['datetime'],
"%Y-%m-%d %H:%M:%S")))
elif (isinstance(a, list)):
for x in xrange(0, len(a)):
if (isinstance(a[x], dict) and
('date' in a[x]) and ('timestamp' not in a[x])):
a[x]['timestamp'] = float(time.mktime(time.strptime(
a[x]['date'],"%Y-%m-%d %H:%M:%S")))
return a
def cancel_all(): # first order placed is cancelled last
key = private(APIKEY, SECRET)
try:
outstanding = key.orders(PAIR)
order_numbers = []
if len(outstanding)>0:
print 'CLOSING YOUR OPEN ORDERS:'
print outstanding
for i in range(len(outstanding)):
order_numbers.append(int(outstanding[i]['orderNumber']))
order_numbers.sort(reverse=True)
for i in range(len(order_numbers)):
try:
key.cancel(PAIR, orderNumber=order_numbers[i])
print 'cancel %s %s' % (PAIR, order_numbers[i])
except:
print ('%s cancel failed' % order_numbers[i])
pass
except:
print ('cancel_all() failed')
if CANCEL:
cancel_all()
if ACTION == 'buy':
try:
key = private(APIKEY, SECRET)
order = key.buy(PAIR,rate=RATE,amount=AMOUNT)
print 'BUYING:'
print PAIR, RATE, AMOUNT, order
except:
print 'buy() failed'
pass
if ACTION == 'sell':
try:
key = private(APIKEY, SECRET)
order = key.sell(PAIR,rate=RATE,amount=AMOUNT)
print 'SELLING:'
print PAIR, RATE, AMOUNT, order
except:
print 'sell() failed'
pass