Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python2.7
- import base64
- import hashlib
- import hmac
- import json
- import time
- import urllib
- import requests
- IS_LOCAL = False
- def pretty_print(input_dict):
- print json.dumps(input_dict,
- sort_keys=True,
- indent=4,
- separators=(',', ': '),
- )
- class GenesisTradingEngineApi(object):
- """
- API wrapper
- """
- # These are internal constants
- TASK_TYPES = 'BUY', 'SELL'
- MODES = 'MARKET', 'SMART'
- # this switch is for the case you are using a local test server
- HOST = 'localhost' if IS_LOCAL else '85.25.92.71'
- PORT = 8889
- BASE_API_URL = '/rest/api/auth/'
- def __init__(self, key, secret):
- super(GenesisTradingEngineApi, self).__init__()
- self.__key = str(key)
- self.__secret = str(secret)
- def create_task(self, login_id, wallet_username, exchange_id, base_cur_name, quote_cur_name, mode,
- task_type, price_limit, amount, time_limit, email_address=None):
- """
- Create a new task using the API
- :param login_id: Login Id that you use for the graphical UI, too
- :param wallet_username: On which wallet this shall be accounted
- :param exchange_id: Poloniex, Bitfinex, Kraken, etc.
- :param base_cur_name: A currency like BTC, ETH, LTC or USD.
- :param quote_cur_name: A currency like BTC, ETH, LTC or USD.
- :param mode: SMART or MARKET
- :param task_type: BUY or SELL BTC.
- :param price_limit: Max price for buy; Min price for sell.
- :param amount: How many BTC to buy or sell
- :param time_limit: Validity of the task in seconds
- :param email_address: optional; add if you like to receive notifications to a certain address
- :raise ValueError: On invalid type or mode
- :type email_address: str
- :type time_limit: float
- :type amount: float
- :type price_limit: float
- :type task_type: str
- :type mode: str
- :type quote_cur_name: str
- :type base_cur_name: str
- :type exchange_id: str
- :type wallet_username: str
- :type login_id: str
- :rtype: dict
- Response from Server:
- {
- "status": "success",
- "data": {
- "status": {"status": "pending"},
- "time_limit": 100,
- "task_type": "BUY",
- "wallet_username": "<your wallet_username>",
- "price_limit": 200.0,
- "base_cur_name": "BTC",
- "exchange_id": "Bitfinex",
- "time_created": 1439993169.540273,
- "alternate_exchange_ids": [],
- "amount": 0.05, "quote_cur_name": "USD",
- "age_created": 0.005042076110839844,
- "mode": "MARKET",
- "email_address": "your.email@address.com",
- "id": "Ra7f2e4804d50460abb0669c16050a4fe"
- }
- }
- """
- if task_type not in self.TASK_TYPES:
- raise ValueError('Invalid task_type')
- if mode not in self.MODES:
- raise ValueError('Invalid task mode')
- if time_limit < 100:
- raise ValueError('Time limit must be at least 100sec')
- # The key and the secret are constant now.
- api = 'liquidationtask'
- params = [
- ('exchange_id', exchange_id),
- ('base_cur_name', base_cur_name),
- ('quote_cur_name', quote_cur_name),
- ('task_type', task_type),
- ('wallet_username', wallet_username),
- ('mode', mode),
- ('amount', amount),
- ('time_limit', time_limit),
- ('price_limit', price_limit),
- ('email_address', email_address or ''),
- ('login_id', login_id)
- ]
- return self._perform_request(api, params, 'POST')
- def get_task_status(self, task_id):
- """
- Query the status of a certain task. Use the task id returned by create_task
- :param task_id:
- :return: dict with a properties of the task
- """
- result = self._perform_request('liquidationtask', [('task_id', task_id)])
- return result
- def list_tasks(self, page=0):
- """
- List the last created tasks
- :param page:
- :return:
- """
- result = self._perform_request('liquidationtasklist', [('page', page)])
- return result
- def list_balance(self, page=0):
- """
- Request your account balance. Returns a dict with the exchange-id as key which contains a dict with the
- currency names as keys.
- :param page:
- :return:
- """
- result = self._perform_request('liquidationbalancelist', [('page', page)])
- return result
- def fund_history(self, exchange_id, cur_name, page=0):
- """
- List all deposits, withdrawals, trades and fees accounted to your balance.
- :param exchange_id:
- :param cur_name:
- :param page:
- :return:
- """
- result = self._perform_request('liquidationfundhistory',
- [('exchange_id', exchange_id),
- ('cur_name', cur_name),
- ('page', page)])
- return result
- def _perform_request(self, api, params, method='GET'):
- """
- Generic method to query the api.
- The params is a list to preserve order.
- :param api: endpoint to query
- :param params: list of key-value-tuples
- :param method: GET or POST at the moment.
- :return: a response dict
- """
- params.append(('tonce', int(time.time() * 1000)))
- params.append(('auth_key', self.__key))
- url = 'http://' + self.HOST + ':' + str(self.PORT) + self.BASE_API_URL + api
- # Create a sha512 based signature
- message = urllib.urlencode(params)
- secret = base64.b64decode(self.__secret)
- hmac_obj = hmac.new(secret, message, hashlib.sha512)
- hmac_sign = base64.b64encode(hmac_obj.digest())
- # Add this value as HTTP header value
- headers = {'X-Signature': hmac_sign}
- if method == 'GET':
- url += '?' + message
- request = requests.get(url=url, headers=headers)
- elif method == 'POST':
- request = requests.post(url=url, data=params, headers=headers)
- else:
- raise ValueError('Invalid request method')
- # The resulting HTTP code should be 200 on success
- assert request.status_code == 200, 'Wrong status code: %i' % request.status_code
- response = json.loads(request.content)
- assert response['status'] == 'success', 'Request failed'
- return response
- if __name__ == '__main__':
- # Create a dummy task
- with open('./sheffield_config.json') as data_file:
- config = json.load(data_file)
- api = GenesisTradingEngineApi(config['KEY'], config['SECRET'])
- history = api.fund_history(exchange_id='Poloniex', cur_name='BTC')
- pretty_print(history)
- data = api.create_task(
- login_id='david@sheffieldcrypto.com',
- wallet_username='SheffieldCrypto',
- exchange_id='Poloniex',
- base_cur_name='SC',
- quote_cur_name='BTC',
- mode='MARKET',
- #if prediction()==0.5:
- task_type='SELL',
- price_limit=1000,
- amount=0.5,
- time_limit=100)
- def prediction():
- return 0.5
- # Get the task id from it
- task_id = data['data']['id']
- # Query it's status
- status = api.get_task_status(task_id)
- pretty_print(status)
- # Check your balance
- balance = api.list_balance()
- pretty_print(balance)
- # Check all of your tasks.
- tasks = api.list_tasks()
- pretty_print(tasks)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement