OKEx Cryptocurrency Automated Trading with Python: API Trading Methods (Part 2)

ยท

This section begins with an introduction to the base class.

Base Class Code

In the previous section, we discussed the need to design a base class, OkexBaseClient. This class is heavily inspired by a GitHub implementation and serves to encapsulate fundamental operations.

Initialization

The class requires:

Core Methods

  1. Signature Generation: Signs payloads using the secret key.
  2. Request Construction: Handles GET/POST request formatting.
  3. Payload Conversion: Converts data values to floats.
class OkexBaseClient(object):
    def __init__(self, key, secret, proxies=None):
        self.URL = "{0:s}://{1:s}/{2:s}".format(PROTOCOL, HOST, VERSION)
        self.KEY = key
        self.SECRET = secret
        self.PROXIES = proxies

    @property
    def _nonce(self):
        return str(int(time.time() * 1000))

    def _build_parameters(self, parameters):
        keys = sorted(parameters.keys())
        return '&'.join([f"{k}={parameters[k]}" for k in keys])

    def _sign_payload(self, payload):
        sign = '&'.join([f"{k}={payload[k]}" for k in sorted(payload.keys())])
        data = f"{sign}&secret_key={self.SECRET}"
        return hashlib.md5(data.encode("utf8")).hexdigest().upper()

    def _get(self, url, timeout=TIMEOUT):
        req = requests.get(url, timeout=timeout, proxies=self.PROXIES)
        if req.status_code // 100 != 2:
            logging.error("Request failed: %s", url)
        return req.json()

    def _post(self, url, params=None, needsign=True, headers=None, timeout=TIMEOUT):
        req_params = {'api_key': self.KEY}
        if params and needsign:
            req_params.update(params)
            req_params['sign'] = self._sign_payload(req_params)
        req = requests.post(url, data=urllib.urlencode(req_params), timeout=timeout, proxies=self.PROXIES)
        return req.json()

Sending GET Requests: A Practical Example

Fetching Contract Market Data

Step 1: Extend the Base Class

PROTOCOL = "https"
HOST = "www.okex.com/api"
VERSION = "v1"
PATH_TICKER = "future_ticker.do"

class OkexClient(OkexBaseClient):
    def ticker(self, symbol, contract_type):
        return self._get(self.url_for(PATH_TICKER, parameters={
            'symbol': symbol,
            'contract_type': contract_type
        }))

Step 2: Execute the Request

from client import OkexClient
client = OkexClient(None, None)
response = client.ticker('btc_usd', 'this_week')

Step 3: Interpret the Response

{
    "date": "1533958338",
    "ticker": {
        "sell": 6071.2,
        "buy": 6067.81,
        "last": 6067.81,
        "vol": 3116946,
        "high": 6496.21,
        "low": 5950
    }
}

๐Ÿ‘‰ Explore advanced trading strategies

FAQ

1. How do I handle Unix timestamps in Python?

Use Python's datetime module:

from datetime import datetime
timestamp = 1533958338
dt_object = datetime.fromtimestamp(timestamp)

2. What if my API request fails?

3. Can I use this for other cryptocurrencies?

Yes! Replace btc_usd with pairs like eth_usd or ltc_btc.

๐Ÿ‘‰ Learn more about API rate limits

Next Steps

In the next section, we'll implement full automation workflows for algorithmic trading.