Advertisement
Guest User

Untitled

a guest
Dec 26th, 2015
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.88 KB | None | 0 0
  1. #!/usr/bin/env python2.7
  2. import base64
  3. import hashlib
  4. import hmac
  5. import json
  6. import time
  7. import urllib
  8. import requests
  9.  
  10. IS_LOCAL = False
  11.  
  12.  
  13. def pretty_print(input_dict):
  14. print json.dumps(input_dict,
  15. sort_keys=True,
  16. indent=4,
  17. separators=(',', ': '),
  18.  
  19. )
  20.  
  21.  
  22. class GenesisTradingEngineApi(object):
  23. """
  24. API wrapper
  25. """
  26.  
  27. # These are internal constants
  28. TASK_TYPES = 'BUY', 'SELL'
  29. MODES = 'MARKET', 'SMART'
  30. # this switch is for the case you are using a local test server
  31. HOST = 'localhost' if IS_LOCAL else '85.25.92.71'
  32. PORT = 8889
  33. BASE_API_URL = '/rest/api/auth/'
  34.  
  35. def __init__(self, key, secret):
  36. super(GenesisTradingEngineApi, self).__init__()
  37. self.__key = str(key)
  38. self.__secret = str(secret)
  39.  
  40. def create_task(self, login_id, wallet_username, exchange_id, base_cur_name, quote_cur_name, mode,
  41. task_type, price_limit, amount, time_limit, email_address=None):
  42. """
  43. Create a new task using the API
  44.  
  45.  
  46.  
  47. :param login_id: Login Id that you use for the graphical UI, too
  48. :param wallet_username: On which wallet this shall be accounted
  49. :param exchange_id: Poloniex, Bitfinex, Kraken, etc.
  50. :param base_cur_name: A currency like BTC, ETH, LTC or USD.
  51. :param quote_cur_name: A currency like BTC, ETH, LTC or USD.
  52. :param mode: SMART or MARKET
  53. :param task_type: BUY or SELL BTC.
  54. :param price_limit: Max price for buy; Min price for sell.
  55. :param amount: How many BTC to buy or sell
  56. :param time_limit: Validity of the task in seconds
  57. :param email_address: optional; add if you like to receive notifications to a certain address
  58. :raise ValueError: On invalid type or mode
  59. :type email_address: str
  60. :type time_limit: float
  61. :type amount: float
  62. :type price_limit: float
  63. :type task_type: str
  64. :type mode: str
  65. :type quote_cur_name: str
  66. :type base_cur_name: str
  67. :type exchange_id: str
  68. :type wallet_username: str
  69. :type login_id: str
  70. :rtype: dict
  71.  
  72. Response from Server:
  73. {
  74. "status": "success",
  75. "data": {
  76. "status": {"status": "pending"},
  77. "time_limit": 100,
  78. "task_type": "BUY",
  79. "wallet_username": "<your wallet_username>",
  80. "price_limit": 200.0,
  81. "base_cur_name": "BTC",
  82. "exchange_id": "Bitfinex",
  83. "time_created": 1439993169.540273,
  84. "alternate_exchange_ids": [],
  85. "amount": 0.05, "quote_cur_name": "USD",
  86. "age_created": 0.005042076110839844,
  87. "mode": "MARKET",
  88. "email_address": "your.email@address.com",
  89. "id": "Ra7f2e4804d50460abb0669c16050a4fe"
  90. }
  91. }
  92. """
  93.  
  94. if task_type not in self.TASK_TYPES:
  95. raise ValueError('Invalid task_type')
  96.  
  97. if mode not in self.MODES:
  98. raise ValueError('Invalid task mode')
  99.  
  100. if time_limit < 100:
  101. raise ValueError('Time limit must be at least 100sec')
  102.  
  103. # The key and the secret are constant now.
  104. api = 'liquidationtask'
  105.  
  106. params = [
  107.  
  108. ('exchange_id', exchange_id),
  109. ('base_cur_name', base_cur_name),
  110. ('quote_cur_name', quote_cur_name),
  111. ('task_type', task_type),
  112. ('wallet_username', wallet_username),
  113. ('mode', mode),
  114. ('amount', amount),
  115. ('time_limit', time_limit),
  116. ('price_limit', price_limit),
  117. ('email_address', email_address or ''),
  118. ('login_id', login_id)
  119. ]
  120.  
  121. return self._perform_request(api, params, 'POST')
  122.  
  123. def get_task_status(self, task_id):
  124. """
  125. Query the status of a certain task. Use the task id returned by create_task
  126. :param task_id:
  127. :return: dict with a properties of the task
  128. """
  129. result = self._perform_request('liquidationtask', [('task_id', task_id)])
  130. return result
  131.  
  132. def list_tasks(self, page=0):
  133. """
  134. List the last created tasks
  135. :param page:
  136. :return:
  137. """
  138. result = self._perform_request('liquidationtasklist', [('page', page)])
  139. return result
  140.  
  141. def list_balance(self, page=0):
  142. """
  143. Request your account balance. Returns a dict with the exchange-id as key which contains a dict with the
  144. currency names as keys.
  145. :param page:
  146. :return:
  147. """
  148. result = self._perform_request('liquidationbalancelist', [('page', page)])
  149. return result
  150.  
  151. def fund_history(self, exchange_id, cur_name, page=0):
  152. """
  153. List all deposits, withdrawals, trades and fees accounted to your balance.
  154. :param exchange_id:
  155. :param cur_name:
  156. :param page:
  157. :return:
  158. """
  159. result = self._perform_request('liquidationfundhistory',
  160. [('exchange_id', exchange_id),
  161. ('cur_name', cur_name),
  162. ('page', page)])
  163. return result
  164.  
  165. def _perform_request(self, api, params, method='GET'):
  166. """
  167. Generic method to query the api.
  168. The params is a list to preserve order.
  169.  
  170. :param api: endpoint to query
  171. :param params: list of key-value-tuples
  172. :param method: GET or POST at the moment.
  173. :return: a response dict
  174. """
  175. params.append(('tonce', int(time.time() * 1000)))
  176. params.append(('auth_key', self.__key))
  177.  
  178. url = 'http://' + self.HOST + ':' + str(self.PORT) + self.BASE_API_URL + api
  179. # Create a sha512 based signature
  180.  
  181. message = urllib.urlencode(params)
  182.  
  183. secret = base64.b64decode(self.__secret)
  184. hmac_obj = hmac.new(secret, message, hashlib.sha512)
  185. hmac_sign = base64.b64encode(hmac_obj.digest())
  186. # Add this value as HTTP header value
  187. headers = {'X-Signature': hmac_sign}
  188.  
  189. if method == 'GET':
  190. url += '?' + message
  191. request = requests.get(url=url, headers=headers)
  192. elif method == 'POST':
  193. request = requests.post(url=url, data=params, headers=headers)
  194. else:
  195. raise ValueError('Invalid request method')
  196. # The resulting HTTP code should be 200 on success
  197. assert request.status_code == 200, 'Wrong status code: %i' % request.status_code
  198. response = json.loads(request.content)
  199. assert response['status'] == 'success', 'Request failed'
  200. return response
  201.  
  202.  
  203. if __name__ == '__main__':
  204. # Create a dummy task
  205. with open('./sheffield_config.json') as data_file:
  206. config = json.load(data_file)
  207.  
  208.  
  209.  
  210. api = GenesisTradingEngineApi(config['KEY'], config['SECRET'])
  211.  
  212. history = api.fund_history(exchange_id='Poloniex', cur_name='BTC')
  213. pretty_print(history)
  214.  
  215. data = api.create_task(
  216. login_id='david@sheffieldcrypto.com',
  217. wallet_username='SheffieldCrypto',
  218. exchange_id='Poloniex',
  219. base_cur_name='SC',
  220. quote_cur_name='BTC',
  221. mode='MARKET',
  222. #if prediction()==0.5:
  223. task_type='SELL',
  224. price_limit=1000,
  225. amount=0.5,
  226. time_limit=100)
  227.  
  228. def prediction():
  229. return 0.5
  230.  
  231. # Get the task id from it
  232. task_id = data['data']['id']
  233.  
  234. # Query it's status
  235. status = api.get_task_status(task_id)
  236. pretty_print(status)
  237.  
  238. # Check your balance
  239. balance = api.list_balance()
  240. pretty_print(balance)
  241.  
  242. # Check all of your tasks.
  243. tasks = api.list_tasks()
  244. pretty_print(tasks)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement