ok_api.py

#!/usr/bin/python
# -*- coding: utf-8 -*-

import base64
import datetime
import hmac
import json
import requests
import threading
import time
import zlib

from retrying import retry
from websocket import WebSocketApp

CONTENT_TYPE = 'Content-Type'
OK_ACCESS_KEY = 'OK-ACCESS-KEY'
OK_ACCESS_SIGN = 'OK-ACCESS-SIGN'
OK_ACCESS_TIMESTAMP = 'OK-ACCESS-TIMESTAMP'
OK_ACCESS_PASSPHRASE = 'OK-ACCESS-PASSPHRASE'
APPLICATION_JSON = 'application/json'
BASE_URL = 'https://www.okex.com'
# WS_URL = 'ws://echo.websocket.org/'
WS_URL = 'wss://real.okex.com:8443/ws/v3'
API_KEY = ''
SECRET_KEY = ''
PASS_PHRASE = ''


class OkAPI:

    def __init__(self, client):

        self.client = client
        self.__baseUrl = BASE_URL
        self.__apikey = API_KEY
        self.__secretkey = SECRET_KEY
        self.__passphrase = PASS_PHRASE
        self.__sub_connect = None  # 订阅连接
        self.__ws_subs = []
        self.__direct = None

    def get_header(self, api_key, sign, timestamp, passphrase):
        header = dict()
        header[CONTENT_TYPE] = APPLICATION_JSON
        header[OK_ACCESS_KEY] = api_key
        header[OK_ACCESS_SIGN] = sign
        header[OK_ACCESS_TIMESTAMP] = str(timestamp)
        header[OK_ACCESS_PASSPHRASE] = passphrase
        return header

    def parse_params_to_str(self, params):
        url = '?'
        for key, value in params.items():
            url = url + str(key) + '=' + str(value) + '&'
        return url[0:-1]

    def timestamp(self):
        timestamp = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f')
        timestamp = timestamp[0:-3] + 'Z'
        return timestamp

    def transfer(self, instrument_id, fund, amount):

        path = '/api/account/v3/transfer'
        params = {'currency': fund, 'amount': amount, 'from': '1', 'to': '5',
                  'instrument_id': '{}-{}'.format(instrument_id, fund)}
        return self.httpPost(path, params)

    # -----------------------------交割合约api-----------------------------
    def f_ticker(self, instrument_id):
        path = '/api/futures/v3/instruments/{}/ticker'.format(instrument_id)
        return self.httpGet(path)

    def f_depth(self, instrument_id):
        path = '/api/futures/v3/instruments/{}/book'.format(instrument_id)
        params = {'instrument_id': instrument_id, 'size': 10}
        return self.httpGet(path, params)

    def f_position(self, instrument_id=None):
        path = '/api/futures/v3/{}/position'.format(instrument_id) if instrument_id else '/api/futures/v3/position'
        return self.httpGet(path)

    def f_instruments(self):
        path = '/api/futures/v3/instruments'
        return self.httpGet(path)

    def f_trade(self, instrument_id, side, price, amount, client_oid=''):
        path = '/api/futures/v3/order'
        params = {'instrument_id': instrument_id, 'type': side, 'price': price, 'size': amount, 'match_price': '0',
                  'client_oid': client_oid}
        return self.httpPost(path, params)

    def f_order_info(self, instrument_id, client_oid):
        path = '/api/futures/v3/orders/{}/{}'.format(instrument_id, client_oid)
        return self.httpGet(path)

    def f_kline(self, instrument_id, interval, end=''):
        path = '/api/futures/v3/instruments/{}/candles'.format(instrument_id)
        params = {'granularity': interval, 'end': end}
        return self.httpGet(path, params)

    def f_account(self, instrument_id):
        path = '/api/futures/v3/accounts/{}'.format(instrument_id)
        return self.httpGet(path)

    def f_cancel_order(self, instrument_id, client_oid):
        path = '/api/futures/v3/cancel_order/{}/{}'.format(instrument_id, client_oid)
        params = {'instrument_id': instrument_id, 'client_oid': client_oid}
        return self.httpPost(path, params)

    # -----------------------------永续合约api-----------------------------
    def sf_ticker(self, instrument_id):
        path = '/api/swap/v3/instruments/{}/ticker'.format(instrument_id)
        return self.httpGet(path)

    def sf_position(self, instrument_id=None):
        path = '/api/swap/v3/{}/position'.format(instrument_id) if instrument_id else '/api/swap/v3/position'
        return self.httpGet(path)

    def sf_trade(self, instrument_id, side, price, amount, client_oid=''):
        path = '/api/swap/v3/order'
        params = {'instrument_id': instrument_id, 'type': side, 'price': price, 'size': amount, 'match_price': '0',
                  'client_oid': client_oid}
        return self.httpPost(path, params)

    def sf_kline(self, instrument_id, interval, end=''):
        path = '/api/swap/v3/instruments/{}/candles'.format(instrument_id)
        params = {'granularity': interval, 'end': end}
        return self.httpGet(path, params)

    def sf_cancel_order(self, instrument_id, client_oid):
        path = '/api/swap/v3/cancel_order/{}/{}'.format(instrument_id, client_oid)
        params = {'instrument_id': instrument_id, 'client_oid': client_oid}
        return self.httpPost(path, params)

    # -----------------------------币币api-----------------------------
    def ticker(self, instrument_id):
        path = '/api/spot/v3/instruments/{}/ticker'.format(instrument_id)
        return self.httpGet(path)

    def tickers(self):
        path = '/api/spot/v3/instruments/ticker'
        return self.httpGet(path)

    def instruments(self):
        path = '/api/spot/v3/instruments'
        return self.httpGet(path)

    def trade(self, side, instrument_id, price, amount):
        path = '/api/spot/v3/orders'
        params = {'type': 'limit', 'side': side, 'instrument_id': instrument_id, 'size': amount, 'price': price,
                  'margin_trading': 1}
        return self.httpPost(path, params)

    def order(self, instrument_id, orderid):
        path = '/api/spot/v3/orders/' + orderid
        params = {'instrument_id': instrument_id}
        return self.httpGet(path, params)

    def orders(self):
        path = '/api/spot/v3/orders_pending'
        return self.httpGet(path)

    def kline(self, instrument_id, interval, start='', end=''):
        path = '/api/spot/v3/instruments/{}/candles'.format(instrument_id)
        params = {'granularity': interval, 'start': start, 'end': end}
        return self.httpGet(path, params)

    def account(self, instrument_id):
        path = '/api/spot/v3/accounts/' + instrument_id
        return self.httpGet(path)

    def cancel_order(self, instrument_id, orderid):
        path = '/api/spot/v3/cancel_orders/' + orderid
        params = {'instrument_id': instrument_id}
        return self.httpPost(path, params)

    # -----------------------------币币杠杆api-----------------------------
    def l_trade(self, side, instrument_id, price, amount):
        path = '/api/margin/v3/orders'
        params = {'type': 'limit', 'side': side, 'instrument_id': instrument_id, 'size': amount, 'price': price,
                  'margin_trading': 2}
        return self.httpPost(path, params)

    def l_borrow(self, instrument_id, currency, amount):
        path = '/api/margin/v3/accounts/borrow'
        params = {'instrument_id': instrument_id, 'currency': currency, 'amount': amount}
        return self.httpPost(path, params)

    def l_borrowed(self, instrument_id, status=0):
        path = '/api/margin/v3/accounts/{}/borrowed'.format(instrument_id)
        params = {'status': status}
        return self.httpGet(path, params)

    def l_repay(self, instrument_id, currency, amount, borrow_id=None):
        path = '/api/margin/v3/accounts/repayment'
        params = {'instrument_id': instrument_id, 'currency': currency, 'amount': str(amount)}
        if borrow_id:
            params['borrow_id'] = borrow_id
        return self.httpPost(path, params)

    def l_order(self, instrument_id, orderid):
        path = '/api/margin/v3/orders/' + orderid
        params = {'instrument_id': instrument_id}
        return self.httpGet(path, params)

    def l_accounts(self):
        path = '/api/margin/v3/accounts'
        return self.httpGet(path)

    def l_account(self, instrument_id):
        path = '/api/margin/v3/accounts/' + instrument_id
        return self.httpGet(path)

    def l_availability(self, instrument_id):
        path = '/api/margin/v3/accounts/{}/availability'.format(instrument_id)
        return self.httpGet(path)

    def l_cancel_order(self, instrument_id, orderid):
        path = '/api/margin/v3/cancel_orders/' + orderid
        params = {'instrument_id': instrument_id, 'order_id': orderid}
        return self.httpPost(path, params)

    def signature(self, timestamp, method, request_path, body, secret_key):
        if str(body) == '{}' or str(body) == 'None':
            body = ''
        message = str(timestamp) + str.upper(method) + request_path + str(body)
        mac = hmac.new(bytes(secret_key, encoding='utf8'), bytes(message, encoding='utf-8'), digestmod='sha256')
        d = mac.digest()
        return base64.b64encode(d)

    @retry(stop_max_attempt_number=3)
    def httpGet(self, path, data=None):
        if data:
            path = path + self.parse_params_to_str(data)
        url = self.__baseUrl + path
        timestamp = self.timestamp()
        header = self.get_header(self.__apikey, self.signature(timestamp, 'GET', path, '', self.__secretkey),
                                 timestamp, self.__passphrase)
        try:
            response = requests.get(url, headers=header, timeout=15)
        except Exception as e:
            print("Exception: ", e)
            raise Exception(e)

        return response.json()

    @retry(stop_max_attempt_number=3)
    def httpPost(self, path, data):
        url = self.__baseUrl + path
        body = json.dumps(data)
        timestamp = self.timestamp()
        header = self.get_header(self.__apikey, self.signature(timestamp, 'POST', path, body, self.__secretkey),
                                 timestamp, self.__passphrase)
        try:
            response = requests.post(url, data=body, headers=header)
        except Exception as e:
            raise Exception(e)

        return response.json()

    def httpDelete(self, path, data):
        if data:
            path = path + self.parse_params_to_str(data)
        url = self.__baseUrl + path
        timestamp = self.timestamp()
        header = self.get_header(self.__apikey, self.signature(timestamp, 'DELETE', path, '', self.__secretkey),
                                 timestamp, self.__passphrase)
        try:
            response = requests.delete(url, headers=header)
        except Exception as e:
            raise Exception(e)

        return response.json()

    def inflate(self, data):
        decompress = zlib.decompressobj(
            -zlib.MAX_WBITS  # see above
        )
        inflated = decompress.decompress(data)
        inflated += decompress.flush()
        return inflated

    def login(self, ws):
        ts = str(int(datetime.datetime.now().timestamp()))
        sign = self.signature(ts, 'GET', '/users/self/verify', None, self.__secretkey)
        sub = {'op': 'login', 'args': [self.__apikey, self.__passphrase, ts, sign.decode("utf-8")]}
        ws.send(json.dumps(sub))

    def on_open(self):
        print('ok_on_open', self.__ws_subs)
        self.login(self.__sub_connect)
        time.sleep(0.1)
        s = []
        for sub_config in self.__ws_subs:
            s.append('{}/{}:{}'.format(sub_config.trade_kind, sub_config.frequency,
                                       sub_config.instrument_id))
        self.__sub_connect.send(json.dumps({'op': 'subscribe', 'args': s}))

    def on_message(self, message):
        data = json.loads(self.inflate(message))
        print('ok_on_message', data)
        if 'table' in data:
            table = data['table']
            if table.find('spot/ticker') != -1:
                self.client.ws_ticker(data['data'])
            elif table.find('futures/ticker') != -1:
                self.client.ws_f_ticker(data['data'])
            elif table.find('spot/candle') != -1:
                self.client.ws_kline(data)
            elif table.find('futures/candle') != -1:
                self.client.ws_f_kline(data)
            elif table.find('swap/candle') != -1:
                self.client.ws_sf_kline(data)
            elif table.find('spot/trade') != -1:
                self.client.ws_trade(data['data'])
            elif table.find('spot/account') != -1:
                self.client.ws_account(data['data'])
            elif table.find('spot/margin_account') != -1:
                self.client.ws_l_account(data['data'])
            elif table.find('futures/account') != -1:
                self.client.ws_f_account(data['data'])
            elif table.find('swap/account') != -1:
                self.client.ws_sf_account(data['data'])
            elif table.find('spot/order') != -1:
                self.client.ws_order(data['data'])
            elif table.find('futures/order') != -1:
                self.client.ws_f_order(data['data'])
            elif table.find('swap/order') != -1:
                self.client.ws_sf_order(data['data'])
            elif table.find('futures/position') != -1:
                self.client.ws_f_position(data['data'])
            elif table.find('swap/position') != -1:
                self.client.ws_sf_position(data['data'])
            elif table.find('depth') != -1:
                self.client.ws_depth(data['data'])
            elif table.find('depth5') != -1:
                pass

        elif 'event' in data:
            print(data)
            if data['event'] == 'login':
                s = []
                for sub_config in self.__ws_subs:
                    s.append('{}/{}:{}'.format(sub_config.trade_kind, sub_config.frequency,
                                               sub_config.instrument_id))
                self.__sub_connect.send(json.dumps({'op': 'subscribe', 'args': s}))

    def on_close(self):
        print('ok_on_close', self.__sub_connect, self.__ws_subs)
        self.__sub_connect = None

        # if len(self.__ws_subs) > 0:
        #     time.sleep(1)
        #     self.__ws_sub_create()

    def on_error(self, error):
        print('ok_on_error', self.__sub_connect, error)

    def ws_sub(self, sub_list):
        s = []
        for sub_config in sub_list:
            if sub_config not in self.__ws_subs:
                self.__ws_subs.append(sub_config)
                s.append(sub_config)

        # if not self.__sub_connect:
        #     self.__ws_sub_create()

        if self.__sub_connect:
            w_s = []
            for sub in s:
                w_s.append('{}/{}:{}'.format(sub.trade_kind, sub.frequency, sub.instrument_id))
            self.__sub_connect.send(json.dumps({'op': 'subscribe', 'args': w_s}))
        else:
            # threading.stack_size(1024 * 1024 * 100)
            t = threading.Thread(target=self.__ws_sub_create)
            t.start()

    def ws_unsub(self, unsub_list):
        s = []
        for sub_config in unsub_list:
            s.append('{}/{}:{}'.format(sub_config.trade_kind, sub_config.frequency,
                                       sub_config.instrument_id))
            self.__ws_subs.remove(sub_config)
        self.__sub_connect.send(json.dumps({'op': 'unsubscribe', 'args': s}))

        # if len(self.__ws_subs) == 0:
        #     self.__sub_connect.close()

    def __ws_sub_create(self):
        try:
            self.__sub_connect = WebSocketApp(WS_URL,
                                              on_message=self.on_message,
                                              on_close=self.on_close,
                                              on_error=self.on_error)
            self.__sub_connect.on_open = self.on_open
            self.__sub_connect.run_forever(ping_interval=20)
        except Exception as e:
            print('异常了--ok--__ws_sub_create', e)
            time.sleep(5)
            self.__ws_sub_create()


if __name__ == '__main__':
    from exchange.SubConfig import SubConfig
    from common.Common import Common

    o = OkAPI('')
    # o.__ws_sub_create()
    # ins = o.f_instruments()
    ins = o.f_ticker("XRP-USD-200925")
    print(ins)
    sub_list = []
    sub_config = SubConfig(Common.futures, "XRP-USD-200925", "", Common.frequency_tick)
    sub_list.append(sub_config)
    o.ws_sub(sub_list)

SubConfig.py

class SubConfig:
    trade_kind = None   # 交易类型(币币、交割、永续)
    symbol = None  # 币种
    contract_type = None  # 合约类型
    frequency = None  # 频率
    instrument_id = None  # 币种编号

    def __init__(self, trade_kind, symbol, contract_type, frequency):
        self.trade_kind = trade_kind
        self.symbol = symbol
        self.contract_type = contract_type
        self.frequency = frequency

    def __eq__(self, other):
        # print(self.props())
        # print(other.props())
        return self.__class__ == other.__class__ and self.props() == other.props()

    def props(self):
        pr = {}
        for name in dir(self):
            value = getattr(self, name)
            if not name.startswith('__') and not callable(value) and not name.startswith('_'):
                pr[name] = value
        return pr

okex_client.py

#!/usr/bin/python
# -*- coding: utf-8 -*-

from exchange.ok_api import OkAPI
from common.Client import Client
from common.Common import Common
from retrying import retry
import datetime
import time


class OkClient(Client):

    def __init__(self):
        super().__init__()
        self.exchange_name = 'ok'

        self.__api = OkAPI(self)
        self.__trade_side = {'1': Common.open_long, '2': Common.open_short, '3': Common.close_long,
                             '4': Common.close_short}
        self.__status = {'0': Common.status_open, '1': Common.status_part_filled, '2': Common.status_filled,
                         '3': Common.status_ordering, '4': Common.status_canceling, '-1': Common.status_canceled,
                         '-2': Common.status_failure}
        self.strategy = None
        self._f_balance = dict()
        self._ws_sub = dict()
        self._orders = dict()
        self._f_ws_sub = dict()
        self._last_kline = dict()

    def f_instrument_info(self):
        """
        参数名	参数类型	描述
        instrument_id	String	合约ID,如BTC-USD-180213,BTC-USDT-191227
        underlying	String	标的指数,如:BTC-USD
        base_currency	String	交易货币,如:BTC-USD中的BTC ,BTC-USDT中的BTC
        quote_currency	String	计价货币币种,如:BTC-USD中的USD ,BTC-USDT中的USDT
        settlement_currency	String	盈亏结算和保证金币种,如BTC
        contract_val	String	合约面值(美元)
        listing	String	上线日期
        delivery	String	交割日期
        tick_size	String	下单价格精度
        trade_increment	String	下单数量精度
        alias	String	本周 this_week
        次周 next_week
        季度 quarter
        次季度 bi_quarter
        is_inverse	String	true or false ,是否 币本位保证金合约
        contract_val_currency	String	合约面值计价币种 如 usd,btc,ltc,etc xrp eos
        """
        res = None
        result = []
        try:
            res = self.__api.f_instruments()
            for ins in res:
                amount_precision = int(ins['trade_increment'])
                price_precision = float(ins['tick_size'])
                ins_info = {
                    'exchange': self.exchange_name,
                    'symbol': ins['underlying'],
                    'instrument_id': ins['instrument_id'],
                    'amount_precision': amount_precision,
                    'price_precision': price_precision,
                    'contract_type': ins['alias']
                }
                result.append(ins_info)
        except Exception as e:
            print('f_instrument_info--异常--ok', e, res)
        return result

    @retry(stop_max_attempt_number=3)
    def f_trade(self, instrument_id, side, price, amount, client_oid=''):
        try:
            for k, v in self.__trade_side:
                if v == side:
                    side = k
                    break
            res = None
            num = 0
            while num < 3:
                res = self.__api.f_trade(instrument_id, side, price, amount, client_oid)
                if 'code' in res:
                    time.sleep(2)
                    if res['code'] == 32019:
                        num += 1
                        last, buy, sell = self.f_ticker(instrument_id)
                        price = last
                    else:
                        break
                else:
                    break
            print('f_trade-------res', res)
            order_id = res['client_oid']
            return order_id
        except Exception as e:
            time.sleep(1)
            raise Exception(e)

    def f_order_info(self, instrument_id, client_oid):
        try:
            res = self.__api.f_order_info(instrument_id, client_oid)
            print('f_order_info-------res', res)
            instrument_id = res['instrument_id']
            order_id = res['order_id']
            status = self.__status[res['state']]
            side = res['type']
            side = self.__trade_side[side]
            amount = int(res['size'])
            filled_amount = int(res['filled_qty'])
            fee = float(res['fee'])
            init_price = float(res['price'])
            price = float(res['price_avg'])
            client_oid = res['client_oid']
            data = {'instrument_id': instrument_id, 'order_id': order_id, 'status': status, 'side': side,
                    'amount': amount, 'filled_amount': filled_amount, 'price': price, 'init_price': init_price,
                    'fee': fee, 'client_oid': client_oid}
            return data
        except Exception as e:
            time.sleep(1)
            raise Exception(e)

    def f_cancel_order(self, instrument_id, order_id):
        try:
            res = self.__api.f_cancel_order(instrument_id, order_id)
            if not res['result']:
                raise Exception(res)
        except Exception as e:
            raise Exception(e)

    @retry(stop_max_attempt_number=3)
    def f_ticker(self, instrument_id):

        try:
            res = self.__api.f_ticker(instrument_id)
            last = float(res['last'])
            bid = float(res['best_bid'])
            ask = float(res['best_ask'])
            return last, bid, ask
        except Exception as e:
            time.sleep(1)
            raise Exception(e)

    def f_depth(self, instrument_id):

        try:
            res = self.__api.f_depth(instrument_id)
            data = {'bids': res['bids'], 'asks': res['asks']}
            return data
        except Exception as e:
            raise Exception(e)

    def f_kline(self, instrument_id, interval, number=300):
        try:
            if number <= 300:
                res = self.__api.f_kline(instrument_id, interval)
                res.reverse()
                return res
            else:
                result = list()
                end = datetime.datetime.utcnow().isoformat() + 'Z'
                flag = True
                while flag:
                    res = self.__api.f_kline(instrument_id, interval, end)
                    result.extend(res)
                    if len(result) >= number or len(res) < 300:
                        flag = False
                    else:
                        end = res[-1][0]
                        result.pop(-1)

                result.reverse()
                return result
        except Exception as e:
            raise Exception(e)

    def f_account(self, instrument_id):
        try:
            res = self.__api.f_account(instrument_id)
            contracts = res['contracts']
            contract = contracts[0]
            amount = float(contract['available_qty'])
            return amount
        except Exception as e:
            print('异常了-f_account', e)

    @retry(stop_max_attempt_number=3)
    def f_position(self, instrument_id):
        try:
            res = self.__api.f_position(instrument_id)
            res = res['holding']
            position = res[0]
            amount_l = int(position['long_avail_qty'])
            amount_s = int(position['short_avail_qty'])
            last = float(position['last'])
            data = {'long': amount_l, 'short': amount_s, 'last': last}
            return data
        except Exception as e:
            time.sleep(1)
            print('异常了-f_position', e)

    def ws_f_ticker(self, message):
        try:
            for i in message:
                instrument_id = i['instrument_id']
                data = {'instrument_id': instrument_id, 'last': i['last'], 'bid': i['best_bid'], 'ask': i['best_ask'],
                        'time': i['timestamp']}
                self.strategy.ws_ticker(self, data)
        except Exception as e:
            print('异常了-ws_f_ticker', e, message)

    def ws_f_kline(self, message):
        try:
            kline = message['table']
            l = len(kline) - 1
            interval = int(kline[14:l])
            message = message['data']
            for i in message:
                instrument_id = i['instrument_id']
                candle = i['candle']
                last_k = candle[0]

                data = {'exchange': self.exchange_name, 'instrument_id': instrument_id, 'interval': interval,
                        'time': last_k[0], 'open': float(last_k[1]), 'high': float(last_k[2]), 'low': float(last_k[3]),
                        'close': float(last_k[4])}
                self.strategy.ws_kline(self, data)

        except Exception as e:
            print('异常了-ws_f_kline', e, message)

    def ws_f_order(self, message):
        try:
            for i in message:
                instrument_id = i['instrument_id']
                order_id = i['order_id']
                status = self.__status[i['state']]
                side = i['type']
                side = self.__trade_side[side]
                amount = int(i['size'])
                filled_amount = int(i['filled_qty'])
                fee = float(i['fee'])
                init_price = float(i['price'])
                price = float(i['price_avg'])
                client_oid = i['client_oid']

                data = {'instrument_id': instrument_id, 'order_id': order_id, 'status': status, 'side': side,
                        'amount': amount, 'filled_amount': filled_amount, 'price': price, 'init_price': init_price,
                        'fee': fee, 'client_oid': client_oid}
                self._orders[instrument_id] = data
                self.strategy.ws_order(self, data)
        except Exception as e:
            print('异常了-ws_f_order', e, message)

    def ws_f_account(self, message):
        try:
            for i in message:
                for k, v in i.items():
                    contracts = v['contracts']
                    for avail in contracts:
                        self._f_balance[k] = float(avail['available_qty'])
                        # do something
            print('ws_f_account', self._f_balance)
        except Exception as e:
            print('异常了--ws_account', e, message)

    def ws_f_position(self, message):
        try:
            for i in message:
                instrument_id = i['instrument_id']
                data = {'instrument_id': instrument_id, 'long': int(i['long_avail_qty']),
                        'short': int(i['short_avail_qty']), 'last': float(i['last'])}
                self.strategy.ws_position(self, data)
        except Exception as e:
            print('异常了-ws_f_position', e, message)

    def get_instrument_id(self, instruments, symbol, contract_type):
        for instrument in instruments:
            if instrument['symbol'] == symbol and instrument['contract_type' == contract_type]:
                return instrument['instrument_id']

    def ws_f_sub(self, subs):
        instruments = self.f_instrument_info()
        for sub in subs:
            instrument_id = self.get_instrument_id(instruments, sub.symbol, sub.contract_type)
            sub.instrument_id = instrument_id
        self.__api.ws_sub(subs)

    def ws_f_unsub(self, unsubs):
        instruments = self.f_instrument_info()
        for unsub in unsubs:
            instrument_id = self.get_instrument_id(instruments, unsub.symbol, unsub.contract_type)
            unsub.instrument_id = instrument_id
        self.__api.ws_unsub(unsubs)


if __name__ == '__main__':
    client = OkClient()
    instrument_info = client.f_instrument_info()
    print(instrument_info)

common.Client.py

#!/usr/bin/python
# -*- coding: utf-8 -*-


class Client(object):

    def __init__(self):
        # print('%s-----函数---%s' % (str(self), sys._getframe().f_code.co_name))
        pass

    def loadData(self, data):
        pass

    def get_balance(self, coin, amount=0):
        pass

    def get_l_balance(self, coin, fund, balance_coin):
        pass

    def get_ticker(self, coin, fund):
        pass

    def ws_sub(self, strategy, coin, fund, subs):
        pass

    def ws_unsub(self, strategy, coin, fund, subs):
        pass

    def ticker(self, pair):
        pass

    def coin_pair(self):
        pass

    def ws_ticker(self, message):
        pass

    def ws_account(self, message):
        pass

    def ws_l_account(self, message):
        pass

    def account(self, coin):
        pass

    def buy(self, coin, fund, price, amount):
        pass

    def sell(self, coin, fund, price, amount):
        pass

    def order(self, coin, fund, orderid):
        pass

    def ws_order(self, message):
        pass

    def ws_trade(self, message):
        pass

    def orders(self, coin, fund, status):
        pass

    def kline(self, coin, fund, interval, start, end):
        pass

    def ws_kline(self, message):
        pass

    def cancelOrder(self, coin, fund, orderid):
        pass

    def l_accounts(self):
        pass

    def l_account(self, coin, fund):
        pass

    def l_buy(self, coin, fund, price, amount):
        pass

    def l_sell(self, coin, fund, price, amount):
        pass

    def l_order(self, coin, fund, orderid):
        pass

    def l_cancelOrder(self, coin, fund, orderid):
        pass

    def l_borrow(self, coin, fund, borrow_coin, amount):
        pass

    def l_borrowed(self, coin, fund, status=0):
        pass

    def l_repay(self, coin, fund, repay_coin):
        pass

    def l_availability(self, coin, fund):
        pass

    def ws_depth(self, message):
        pass

    def ws_f_ticker(self, message):
        pass

    def ws_f_kline(self, message):
        pass

    def ws_f_order(self, message):
        pass

    def ws_f_account(self, message):
        pass

    def ws_f_position(self, message):
        pass

    def __del__(self):
        pass
        # print('%s-----函数---%s' % (str(self), sys._getframe().f_code.co_name))

common.Common.py

class Common(object):

    server_host = '0.0.0.0'
    server_port = 5000

    trade_side_buy = 'buy'
    trade_side_sell = 'sell'

    trade_type_limit = 'limit'
    trade_type_market = 'market'
    trade_type_up = 'up'
    trade_type_down = 'down'
    trade_type_updown = 'up_down'
    trade_type_downup = 'down_up'

    trade_source_spot = 'spot'
    trade_source_lever = 'lever'

    trend_short = 'short'
    trend_long = 'long'
    trend_long_short = 'long_short'

    open_long = 'open_long'
    open_short = 'open_short'
    close_long = 'close_long'
    close_short = 'close_short'

    status_open = 'open'
    status_part_filled = 'part_filled'
    status_filled = 'filled'
    status_part_canceled = 'part_canceled'
    status_canceling = 'canceling'
    status_canceled = 'canceled'
    status_failure = 'failure'
    status_ordering = 'ordering'
    status_expired = 'expired'
    status_closed = 'closed'

    kline_1m = 'm_1'
    kline_3m = 'm_3'
    kline_5m = 'm_5'
    kline_15m = 'm_15'
    kline_30m = 'm_30'
    kline_1h = 'h_1'
    kline_2h = 'h_2'
    kline_4h = 'h_4'
    kline_6h = 'h_6'
    kline_1d = 'd_1'
    kline_1w = 'w_1'

    db_host = 'localhost'
    db_port = 27017
    db = 'coin'
    db_spot = 'spot'
    db_lever = 'lever'
    db_future = 'future'
    db_future_auto = 'future_auto'
    db_spot_auto = 'spot_auto'
    db_lever_auto = 'lever_auto'
    db_coin_pair = 'coin_pair'
    db_future_coin_pair = 'future_coin_pair'
    db_fc = 'fc'
    db_analyze = 'analyze'
    db_etf = 'etf'

    switch_start = 'start'
    switch_pause = 'pause'
    switch_stop = 'stop'

    # ------trade_kind------
    spot = 'spot'   # 币币
    futures = 'futures'     # 交割
    swap = 'swap'   # 永续
    # ------frequency------
    frequency_tick = "ticker"
    frequency_1min = "candle60s"
    frequency_3min = "candle180s"
    frequency_5min = "candle300s"
    frequency_15min = "candle900s"
    frequency_30min = "candle1800s"
    frequency_1hour = "candle3600s"
    frequency_2hour = "candle7200s"
    frequency_4hour = "candle14400s"
    frequency_6hour = "candle21600s"
    frequency_12hour = "candle43200s"
    frequency_1day = "candle86400s"
    frequency_1week = "candle604800s"
    frequency_depth = "depth"

    interval_1min = "60"
    interval_3min = "180"
    interval_5min = "300"
    interval_15min = "900"
    interval_30min = "1800"
    interval_1hour = "3600"
    interval_2hour = "7200"
    interval_4hour = "14400"
    interval_6hour = "21600"
    interval_12hour = "43200"
    interval_1day = "86400"
    interval_1week = "604800"

    # ------币币------
    ws_order = 'order'
    ws_account = 'account'
    ws_ticker = 'ticker'
    ws_kline = 'kline'
    ws_trade = 'trade'
    ws_depth = 'depth'
    # ------交割合约------
    ws_f_order = 'f_order'
    ws_f_account = 'f_account'
    ws_f_ticker = 'f_ticker'
    ws_f_kline = 'f_kline'
    ws_f_position = 'f_position'
    # ------永续合约------
    ws_sf_order = 'sf_order'
    ws_sf_account = 'sf_account'
    ws_sf_ticker = 'sf_ticker'
    ws_sf_kline = 'sf_kline'
    ws_sf_position = 'sf_position'

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐