0bps

Strategy vault / Tools & templates

OKEx V5 Candlestick Data Paging Query Example Python Version

Since the OKEX V5 API allows a maximum of 100 candlesticks per call, pagination is required. Therefore, an example is provided on how to paginate requests to the candlestick API to obtain 1,440 candlestick data…

Author
发明者量化-小小梦
Complexity
Starter · 69 lines
Parameters
0

OKEX V5 KLine data paging query example

Since the OKEX V5 API allows a maximum of 100 candlesticks per call, pagination is required. Therefore, an example is provided on how to paginate requests to the candlestick API to obtain 1,440 candlestick data points.

function main() {
    // Access API to retrieve data
    var r = GetRecords("ETH-USDT-SWAP", "1H")   // For example, obtainETH UPerpetual contract in base currency1HourKLine Data

    // Output data
    Log("KLine Data:", r)
    Log("KNumber of line data:", r.length)

    // Plot output
    $.PlotRecords(r, "K")

    // Simple verification
    for (var i = 0 ; i < r.length - 1 ; i++) {
        if (r[i + 1].Time - r[i].Time != 1000 * 60 * 60) {
            Log(_D(r[i + 1].Time), _D(r[i].Time), r[i + 1].Time - r[i].Time)
        }
    }
}

IMG

mainThe function is an example; other functions can be extracted for direct use.

Source Python

import json
import urllib.request

def encodeParams(params):
    ret = ""
    index = 0 
    for key in params:
        if index == 0:
            ret += key + "=" + str(params[key])
        else :
            ret += "&" + key + "=" + str(params[key])
        index += 1
    return ret 

def GetRecords(symbol, period):
    arr = []
    after = 0
    while True:
        params = {
            "instId": symbol,
            "bar": period,
            "limit": 100,
        }
        if after != 0 :
            params["after"] = after
        query = encodeParams(params)        
        try :
            headers = {
                'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
                'Accept-Language':'zh-CN,zh;q=0.9',
                'Connection':'keep-alive',
                'Cookie':'uuid_tt_dd=10_35489889920-1563497330616-876822; ...... ',
                'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'
            }           

            url = "https://www.okex.com/api/v5/market/candles?" + query
            req = urllib.request.Request(url=url,headers=headers)
            r = json.loads(urllib.request.urlopen(req).read().decode('utf-8'))["data"]
            for i in range(len(r)):
                record = {}
                record["Time"] = int(r[i][0])
                record["High"] = float(r[i][2])
                record["Open"] = float(r[i][1])
                record["Low"] = float(r[i][3])
                record["Close"] = float(r[i][4])
                record["Volume"] = float(r[i][5])
                arr.append(record)
                after = record["Time"]
            if len(arr) >= 1440 or len(r) == 0:
                break
        except Exception as e:
            Log(e)
            return 
        Sleep(1000)
    arr.reverse()    
    return arr 
    
def main():
    r = GetRecords("ETH-USDT-SWAP", "1H")
    
    Log("KLine Data:", r)
    Log("KNumber of line data:", len(r))
    
    ext.PlotRecords(r, "K")
    
    for i in range(len(r) - 1):
        if r[i + 1]["Time"] - r[i]["Time"] != 1000 * 60 * 60:
            Log(_D(r[i + 1]["Time"] / 1000), _D(r[i]["Time"] / 1000), r[i + 1]["Time"] - r[i]["Time"])

Published by 发明者量化-小小梦 on the FMZ strategy square · last modified 2021-09-16. Collected in the Quant Trading Vault. Unvalidated research: re-test with your own data and costs before trusting it.

Build this with AgenKit

A spec is not a trading system. Paste this into your coding agent and AgenKit runs a specialist team — architecture, test-first build, risk gates, review — with paper trading on by default.

in Claude Code, Cursor, Codex & 4 more
/agenkit build a tested, production-ready module from strategies/OKEx-V5-Candlestick-Data-Paging-Query-Example-Python-Version.md
  1. npx agenkit install engineering-kit in your project
  2. Paste the command into your agent and approve each phase
  3. Get tests, backtest, risk controls and a paper-trading switch

Understand it first

Before you run this, read the lesson behind the idea and how to backtest it honestly. Specs like this one are the survivors of an unknown number of trials; deflate their results accordingly.

Related specs

esc

Try , , or .

↑↓ move↵ open