通过接口获取欧易okx的行情数据,并存储到mysql数据库中

逻辑:首先,先通过接口获取okx的币种的数据,再把获取到的币种数据引用到行情数据里面查询对应的行情数据,最后把数据存储到mysql数据库中。

在这里插入图片描述

1、依赖

import requests
import mysql.connector
import pymysql

2、okx接口

base_url = "https://www.okx.com/api/v5/public/instruments?instType=SPOT"
base_url2 = f"https://www.okx.com/api/v5/market/history-index-candles?before=1714891889&bar=1D&instId={
      
      inst_id}"

3、mysql数据库数据库的连接

mydb = mysql.connector.connect(
    host="",
    user="",
    password="",
    database="",
    
)

4、币种接口的请求

def get_instruments():
    try:
        # 发送GET请求
        response = requests.get(base_url)
        # 如果响应状态码为200,表示请求成功
        if response.status_code == 200:
            # 返回JSON格式的响应内容
            return response.json()
        else:
            print("Failed to fetch instruments. Status code:", response.status_code)
            return None
    except Exception as e:
        print("Error occurred:", str(e))
        return None

5、行情数据请求

def get_instruments2(inst_id, query=None):
    try:
        # 发送GET请求
        response = requests.get(base_url2)
        # 如果响应状态码为200,表示请求成功
        if response.status_code == 200:
            # 返回JSON格式的响应内容
            return response.json()
        else:
            print("Failed to fetch instruments. Status code:", response.status_code)
            return None
    except Exception as e:
        print("Error occurred:", str(e))
        return None

6、获取币种的数据

# 获取行情产品类型信息
instruments_data = get_instruments()

7、循环获取币种的公共行情数据,并存储到数据库中

if "data" in instruments_data:
    for item in instruments_data["data"]:
        inst_id = item.get("instId")
        instruments_data2=get_instruments2(inst_id)
        data=instruments_data2["data"]
        quoteCcy=item.get("quoteCcy")
        print(quoteCcy)
        if quoteCcy=="USDT":
            print("instId:", data)
            for item in data:
                
                open_price, high_price, low_price, close_price,state,volume = item
                sql = "INSERT INTO `test`.`kline_data`(`coin`, `date`, `open_price`, `high_price`, `low_price`, `close_price`,`state`)  VALUES (%s, %s, %s, %s, %s, %s,%s)"
                val = (inst_id,) + tuple(item)
                mycursor.execute(sql, val)

            # 提交更改
            mydb.commit()

在这里插入图片描述
下载链接
https://www.lanzouh.com/b00taqlwbg
密码:CS