1. 程式人生 > >量化交易:建立簽名、從okex平臺獲取ticker資料和k線資料

量化交易:建立簽名、從okex平臺獲取ticker資料和k線資料

import hashlib
import json
import pandas as pd
from urllib.request import Request, urlopen

pd.set_option('expand_frame_repr', False)  # 當列太多時不換行


def create_trade_sign(params, api_key, secret_key):
    """
    建立交易簽名
    :return: md5加密資料
    """
    sign = ''
    for key in sorted(params.keys()):
        sign += '&'
+ key + '=' + str(params[key]) return hashlib.md5(sign.encode('utf-8')).hexdigest() if __name__ == '__main__': symbol = 'btc2ckusd' params = {'symbol': symbol} api_key = "5561c051fa52ad68322b90b06646c10ddcda3529845" secret_key = "5b6a-6b13d-944c4-9017 # print(create_trade_sign(params, api_key, secret_key)) def get_url_data(url, retry_times=3): "
""API介面中獲取資料 :param url: API介面 :param retry_times:最大嘗試次數 :return: API json格式資料 """ while True: try: headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'} request = Request(url=url, headers=headers) b_data = urlopen(request, timeout=10).read() str_data = b_data.decode('utf-8') json_data = json.loads(str_data) return json_data except Exception as http_error: if retry_times > 0: return get_url_data(url, retry_times=retry_times-1) else: print('嘗試失敗次數過多,已經放棄,錯誤資訊:%s' % http_error) return None if __name__ == '__main__': url = 'https://www.okex.com/api/v1/ticker.do?symbol=ltc_usdt' # print(get_url_data(url)) url = 'https://www.okex.com/api/v1/kline.do?symbol=btc_usdt&type=30min' # print(get_url_data(url)) def get_ticker_from_okex(symbol_list): "
"" 從交易所獲取ticker資料 :param symbol_list: symbol列表 :return: ticker資料 """ df = pd.DataFrame() base_url = 'https://www.okex.com/api/v1/ticker.do?symbol=' for symbol in symbol_list: url = base_url + symbol json_data = get_url_data(url) if json_data is None: continue _df = pd.DataFrame(json_data, dtype='float') _df = _df[['ticker']].T _df['symbol'] = symbol df = df.append(_df, ignore_index=True) # df.to_hdf('data/okex_ticker.h5', key='all_data', mode='w') df = df[['symbol', 'last', 'buy', 'sell', 'high', 'low', 'vol']] return df if __name__ == '__main__': symbol_list = ['btc_usdt', 'ltc_usdt'] # print(get_ticker_from_okex(symbol_list)) def get_candle_from_okex(symbol, kline_type='1min'): url = 'https://www.okex.com/api/v1/kline.do?symbol=%s&type=%s' % (symbol, kline_type) # 構建url json_data = get_url_data(url) if json_data is None: return None df = pd.DataFrame(json_data, dtype='float') df.rename(columns={0: 'candle_begin_time', 1: 'Open', 2: 'High', 3: 'Low', 4: 'Close', 5: 'Volume'}, inplace=True) # 對df的每一列進行重新命名 df['candle_begin_time'] = pd.to_datetime(df['candle_begin_time'], unit='ms') df['candle_begin_time_beijing'] = df['candle_begin_time'] + pd.Timedelta(hours=8) del df['candle_begin_time'] df = df[['candle_begin_time_beijing', 'Open', 'High', 'Low', 'Close', 'Volume']] print(df) if __name__ == '__main__': symbol = 'btc_usdt' get_candle_from_okex(symbol)