获取金融数据 OKEX - ChannelCMT/OFO GitHub Wiki
-----------------------------------By Patrick 黄瀚祺
可导入品种类型:Oanda、A股、商品期货、OKEX
vnpy_fxdayu: https://github.com/xingetouzi/vnpy_fxdayu
Mongodb: https://www.mongodb.com/download-center#community
安装说明: https://github.com/xingetouzi/vnpy_fxdayu/wiki/Windows环境安装
建议安装robomongo作为可视化数据库管理
import pandas as pd
from datetime import datetime,timedelta
import requests# OKEX V1
def getCandles(symbol, type, contract_type=None, size=None, since=None):
    params = {'symbol':symbol,'type':type,'contract_type':contract_type,'size':size,'since':since}
    if contract_type:  # url for future
        url = 'https://www.okex.me/api/v1/future_kline.do?'
    else:              # url for spot
        url = 'https://www.okex.me/api/v1/kline.do?'
        
    r = requests.get(url, params = params,timeout=10)
    text = eval(r.text)
    if contract_type:  
        df = pd.DataFrame(text, columns=["datetime", "open", "high", "low", "close", "volume","%s_volume"%symbol])
    else:
        df = pd.DataFrame(text, columns=["datetime", "open", "high", "low", "close", "volume"])
    df["datetime"] = df["datetime"].map(lambda x: datetime.fromtimestamp(x / 1000))
    # delta = datetime.timedelta(hours=8)
    # df.rename(lambda s: datetime.datetime.strptime(s, "%Y-%m-%d %H:%M:%S") + delta)  # Alter TimeZone 
    return df#.to_csv('a.csv')
getCandles('eos_usd','1min','quarter',size = 10)
# type available: 1min/3min/5min/15min/30min/1day/3day/1week/1hour/2hour/4hour/6hour/12hour
# size value up to 2000
# since value using timestamp, eg. since = 1417536000000| datetime | open | high | low | close | volume | eos_usd_volume | |
|---|---|---|---|---|---|---|---|
| 0 | 2019-01-02 20:05:00 | 2.566 | 2.566 | 2.553 | 2.556 | 52688 | 205910.302404 | 
| 1 | 2019-01-02 20:06:00 | 2.556 | 2.561 | 2.549 | 2.558 | 83348 | 326316.599080 | 
| 2 | 2019-01-02 20:07:00 | 2.557 | 2.558 | 2.553 | 2.556 | 14411 | 56375.567388 | 
| 3 | 2019-01-02 20:08:00 | 2.556 | 2.558 | 2.555 | 2.555 | 11335 | 44335.005101 | 
| 4 | 2019-01-02 20:09:00 | 2.555 | 2.556 | 2.554 | 2.556 | 8823 | 34531.485922 | 
| 5 | 2019-01-02 20:10:00 | 2.556 | 2.558 | 2.556 | 2.558 | 6889 | 26942.726571 | 
| 6 | 2019-01-02 20:11:00 | 2.558 | 2.559 | 2.557 | 2.558 | 11920 | 46586.684532 | 
| 7 | 2019-01-02 20:12:00 | 2.558 | 2.559 | 2.556 | 2.556 | 14503 | 56703.037824 | 
| 8 | 2019-01-02 20:13:00 | 2.557 | 2.558 | 2.556 | 2.558 | 3498 | 13679.271528 | 
| 9 | 2019-01-02 20:14:00 | 2.558 | 2.558 | 2.557 | 2.558 | 1963 | 7674.055766 | 
symbol = 'eos_usd'
data =getCandles(symbol,'1min','quarter',size = 10)
import pymongo
client = pymongo.MongoClient('localhost', 27017)
collection = client['FinData'][symbol]
collection.create_index([('datetime', pymongo.ASCENDING)], unique=True)
for index, row in data.iterrows():
    bar = {}
    bar['open'] = row.open
    bar['close'] = row.close
    bar['high'] = row.high
    bar['low'] = row.low
    bar['volume'] = row.volume
    bar['symbol'] = symbol
    bar['datetime'] = row.datetime
    bar['date'] = bar['datetime'].date().strftime('%Y%m%d')
    bar['time'] = bar['datetime'].time().strftime('%H:%M:%S')
    flt = {'datetime': bar['datetime']}
    collection.update_one(flt, {'$set':bar}, upsert=True)# OKEX V3(由于交易所将历史数据改了,所以作业采用V1来获取历史数据,这部分的代码仅供补充说明)
def getCandles(instrument_id, granularity, start=None, end=None):
    params = {'granularity':granularity}
    try:
        int(instrument_id[-2:])# url for future
        url = 'https://www.okex.me/api/futures/v3/instruments/'+instrument_id+'/candles?'
    except:              # url for spot
        url = 'https://www.okex.me/api/spot/v3/instruments/'+instrument_id+'/candles?'
    if start:
        params['start'] = start
    if end:
        params['end'] = end
    r = requests.get(url, params = params,timeout=10)
    text = eval(r.text)
    if 'futures'in url: 
        symbol = instrument_id[:3]
        df = pd.DataFrame(text, columns=["datetime", "open", "high", "low", "close", "volume","%s_volume"%symbol])
        df["datetime"] = df["datetime"].map(lambda x: datetime.fromtimestamp(x / 1000))
        df["datetime"] = df["datetime"].map(lambda x: x.strftime("%Y-%m-%d %H:%M:%S"))
        delta = timedelta(hours=8)
        df["datetime"] = df["datetime"].map(lambda x: datetime.strptime(x,"%Y-%m-%d %H:%M:%S")-delta)# Alter TimeZone 
    else:
        df = pd.DataFrame(text, columns=["time", "open", "high", "low", "close", "volume"])
        df["datetime"] = df["time"].map(lambda x: datetime.strptime(x,"%Y-%m-%dT%H:%M:%SZ"))
        del df["time"]
        
    return df#.to_csv('a.csv')
getCandles('btc-usd-181109','900','2018-11-03T00:00:00Z','2018-11-06T09:08:08Z').tail()
# granularity available: 60 180 300 900 1800 3600 7200 14400 21600 43200 86400 604800