okex v5sdk for go version

简介

OKEX go版本的v5sdk,仅供学习交流使用。 (文档持续完善中)

项目说明

REST调用

    // 设置您的APIKey
	apikey := APIKeyInfo{
		ApiKey:     "xxxx",
		SecKey:     "xxxx",
		PassPhrase: "xxxx",
	}

	// 第三个参数代表是否为模拟环境,更多信息查看接口说明
	cli := NewRESTClient("https://www.okex.win", &apikey, true)
	rsp, err := cli.Get(context.Background(), "/api/v5/account/balance", nil)
	if err != nil {
		return
	}

	fmt.Println("Response:")
	fmt.Println("\thttp code: ", rsp.Code)
	fmt.Println("\t总耗时: ", rsp.TotalUsedTime)
	fmt.Println("\t请求耗时: ", rsp.ReqUsedTime)
	fmt.Println("\t返回消息: ", rsp.Body)
	fmt.Println("\terrCode: ", rsp.V5Response.Code)
	fmt.Println("\terrMsg: ", rsp.V5Response.Msg)
	fmt.Println("\tdata: ", rsp.V5Response.Data)

更多示例请查看rest/rest_test.go

websocket订阅

私有频道

    ep := "wss://ws.okex.com:8443/ws/v5/private?brokerId=9999"

	// 填写您自己的APIKey信息
	apikey := "xxxx"
	secretKey := "xxxxx"
	passphrase := "xxxxx"

	// 创建ws客户端
	r, err := NewWsClient(ep)
	if err != nil {
		log.Println(err)
		return
	}

	// 设置连接超时
	r.SetDailTimeout(time.Second * 2)
	err = r.Start()
	if err != nil {
		log.Println(err)
		return
	}
	defer r.Stop()

	var res bool
	// 私有频道需要登录
	res, _, err = r.Login(apikey, secretKey, passphrase)
	if res {
		fmt.Println("登录成功!")
	} else {
		fmt.Println("登录失败!", err)
		return
	}

	
	var args []map[string]string
	arg := make(map[string]string)
	arg["ccy"] = "BTC"
	args = append(args, arg)

	start := time.Now()
	// 订阅账户频道
	res, _, err = r.PrivAccout(OP_SUBSCRIBE, args)
	if res {
		usedTime := time.Since(start)
		fmt.Println("订阅成功!耗时:", usedTime.String())
	} else {
		fmt.Println("订阅失败!", err)
	}

	time.Sleep(100 * time.Second)
	start = time.Now()
	// 取消订阅账户频道
	res, _, err = r.PrivAccout(OP_UNSUBSCRIBE, args)
	if res {
		usedTime := time.Since(start)
		fmt.Println("取消订阅成功!", usedTime.String())
	} else {
		fmt.Println("取消订阅失败!", err)
	}

更多示例请查看ws/ws_priv_channel_test.go

公有频道

    ep := "wss://ws.okex.com:8443/ws/v5/public?brokerId=9999"

	// 创建ws客户端
	r, err := NewWsClient(ep)
	if err != nil {
		log.Println(err)
		return
	}

	
	// 设置连接超时
	r.SetDailTimeout(time.Second * 2)
	err = r.Start()
	if err != nil {
		log.Println(err)
		return
	}

	defer r.Stop()

	
	var args []map[string]string
	arg := make(map[string]string)
	arg["instType"] = FUTURES
	//arg["instType"] = OPTION
	args = append(args, arg)

	start := time.Now()

	// 订阅产品频道
	res, _, err := r.PubInstruemnts(OP_SUBSCRIBE, args)
	if res {
		usedTime := time.Since(start)
		fmt.Println("订阅成功!", usedTime.String())
	} else {
		fmt.Println("订阅失败!", err)
	}

	time.Sleep(30 * time.Second)

	start = time.Now()

	// 取消订阅产品频道
	res, _, err = r.PubInstruemnts(OP_UNSUBSCRIBE, args)
	if res {
		usedTime := time.Since(start)
		fmt.Println("取消订阅成功!", usedTime.String())
	} else {
		fmt.Println("取消订阅失败!", err)
	}

更多示例请查看ws/ws_pub_channel_test.go

websocket交易

    ep := "wss://ws.okex.com:8443/ws/v5/private?brokerId=9999"

	// 填写您自己的APIKey信息
	apikey := "xxxx"
	secretKey := "xxxxx"
	passphrase := "xxxxx"

	var res bool
	var req_id string

	// 创建ws客户端
	r, err := NewWsClient(ep)
	if err != nil {
		log.Println(err)
		return
	}

	// 设置连接超时
	r.SetDailTimeout(time.Second * 2)
	err = r.Start()
	if err != nil {
		log.Println(err)
		return
	}

	defer r.Stop()

	res, _, err = r.Login(apikey, secretKey, passphrase)
	if res {
		fmt.Println("登录成功!")
	} else {
		fmt.Println("登录失败!", err)
		return
	}

	start := time.Now()
	param := map[string]interface{}{}
	param["instId"] = "BTC-USDT"
	param["tdMode"] = "cash"
	param["side"] = "buy"
	param["ordType"] = "market"
	param["sz"] = "200"
	req_id = "00001"

	// 单个下单
	res, _, err = r.PlaceOrder(req_id, param)
	if res {
		usedTime := time.Since(start)
		fmt.Println("下单成功!", usedTime.String())
	} else {
		usedTime := time.Since(start)
		fmt.Println("下单失败!", usedTime.String(), err)
	}

更多示例请查看ws/ws_jrpc_test.go

wesocket推送

websocket推送数据分为两种类型数据:普通推送数据深度类型数据

ws/wImpl/BookData.go

// 普通推送
type MsgData struct {
	Arg  map[string]string `json:"arg"`
	Data []interface{}     `json:"data"`
}

// 深度数据
type DepthData struct {
	Arg    map[string]string `json:"arg"`
	Action string            `json:"action"`
	Data   []DepthDetail     `json:"data"`
}

如果需要对推送数据做处理用户可以自定义回调函数:

  1. 全局消息处理的回调函数
    该回调函数会处理所有从服务端接受到的数据。
/*
	添加全局消息处理的回调函数
*/
func (a *WsClient) AddMessageHook(fn ReceivedDataCallback) error {
	a.onMessageHook = fn
	return nil
}

使用方法参见 ws/ws_test.go中测试用例TestAddMessageHook。

  1. 订阅消息处理回调函数
    可以处理所有非深度类型的数据,包括 订阅/取消订阅,普通推送数据。
/*
	添加订阅消息处理的回调函数
*/
func (a *WsClient) AddBookMsgHook(fn ReceivedMsgDataCallback) error {
	a.onBookMsgHook = fn
	return nil
}

使用方法参见 ws/ws_test.go中测试用例TestAddBookedDataHook。

  1. 深度消息处理的回调函数
    这里需要说明的是,Wsclient提供了深度数据管理和自动checksum的功能,用户如果需要关闭此功能,只需要调用EnableAutoDepthMgr方法。
/*
	添加深度消息处理的回调函数
*/
func (a *WsClient) AddDepthHook(fn ReceivedDepthDataCallback) error {
	a.onDepthHook = fn
	return nil
}

使用方法参见 ws/ws_pub_channel_test.go中测试用例TestOrderBooks。

  1. 错误消息类型回调函数
func (a *WsClient) AddErrMsgHook(fn ReceivedDataCallback) error {
	a.OnErrorHook = fn
	return nil
}

联系方式

邮箱:[email protected]
微信:caron_co

Similar Resources

A Golang cryptocurrency trading API & Library. Support Binance, BitMEX, Deribit, Bybit, Huobi DM, OKEX Futures and more.

A Golang cryptocurrency trading API & Library. Support Binance, BitMEX, Deribit, Bybit, Huobi DM, OKEX Futures and more.

CREX 中文 | English CREX 是一个用Golang语言开发的量化交易库。支持tick级别数字币期货平台的回测和实盘。实盘与回测无缝切换,无需更改代码。 回测 示例 @backtest 交易结果 开源策略 https://github.com/coinrust/trading-stra

Nov 18, 2022

Golang API wrapper of OkEX

A complete golang wrapper for Okex V5 API. Pretty simple and easy to use. For more info about Okex V5 API read here.

Nov 15, 2022

A tool to determine the highest version number that's smaller than a target version number

semver-highest A tool to determine the highest version number that's smaller than a target version number. Installation go install github.com/marten-s

Oct 13, 2021

Go Version Manager

gvm By Josh Bussdieker (jbuss, jaja, jbussdieker) while working at Moovweb Currently lovingly maintained by Benjamin Knigge Pull requests and other an

Jan 9, 2023

A node.js version management utility for Windows. Ironically written in Go.

A node.js version management utility for Windows. Ironically written in Go.

The npm/Microsoft/Google recommended Node.js version manager for Windows. This is not the same thing as nvm. The original nvm is a completely separate

Jan 2, 2023

The pure golang implementation of nanomsg (version 1, frozen)

The pure golang implementation of nanomsg (version 1, frozen)

mangos NOTE: This is the legacy version of mangos (v1). Users are encouraged to use mangos v2 instead if possible. No further development is taking pl

Dec 7, 2022

libsvm go version

libsvm golang version libsvm golang version derived work based on LIBSVM 3.14. Info this lib based on LIBSVM java version, just translate java to go.

Sep 27, 2022

A Go interface to ZeroMQ version 4

A Go interface to ZeroMQ version 4. Warning Starting with Go 1.14, on Unix-like systems, you will get a lot of interrupted signal calls. See the top o

Dec 25, 2022

This is a Golang wrapper for working with TMDb API. It aims to support version 3.

This is a Golang wrapper for working with TMDb API. It aims to support version 3.

This is a Golang wrapper for working with TMDb API. It aims to support version 3. An API Key is required. To register for one, head over to themoviedb

Dec 27, 2022

"go build" wrapper to add version info to Golang applications

govvv The simple Go binary versioning tool that wraps the go build command. Stop worrying about -ldflags and go get github.com/ahmetb/govvv now. Build

Dec 16, 2022

Go Version Manager

gvm By Josh Bussdieker (jbuss, jaja, jbussdieker) while working at Moovweb Currently lovingly maintained by Benjamin Knigge Pull requests and other an

Jan 2, 2023

A live-updating version of the UNIX wc command.

A live-updating version of the UNIX wc command.

lwc A live-updating version of the UNIX wc command. Installation You can get a prebuilt binary for every major platform from the Releases page. Just e

Jul 26, 2022

A Go interface to ZeroMQ version 2

A Go interface to ZeroMQ version 2. Requires ZeroMQ version 2.1 or 2.2 For ZeroMQ version 4, see: http://github.com/pebbe/zmq4 For ZeroMQ version 3, s

May 26, 2021

A Go interface to ZeroMQ version 3

A Go interface to ZeroMQ version 3. For ZeroMQ version 4, see: http://github.com/pebbe/zmq4 For ZeroMQ version 2, see: http://github.com/pebbe/zmq2 In

Sep 24, 2022

Speak HTTP like a local. (the simple, intuitive HTTP console, golang version)

http-gonsole This is the Go port of the http-console. Speak HTTP like a local Talking to an HTTP server with curl can be fun, but most of the time it'

Jul 14, 2021

Markdown version of Reverse Engineering the source code of the BioNTech/Pfizer SARS-CoV-2 Vaccine

The big BNT162b2 archive All vaccine data here is sourced from this World Health Organization document. This describes the RNA contents of the BNT162b

Dec 2, 2022

Go version of Plan9 Acme Editor

Overview Go port of Rob Pike's Acme editor. Derived from ProjectSerenity but now increasingly divergent. ProjectSerenity was itself a transliteration

Dec 24, 2022

Golang Version Manager

g 注意:master分支可能处于开发之中并非稳定版本,请通过tag下载稳定版本的源代码,或通过release下载已编译的二进制可执行文件。 g是一个Linux、macOS、Windows下的命令行工具,可以提供一个便捷的多版本go环境的管理和切换。 特性 支持列出可供安装的go版本号 支持列出已安

Dec 30, 2022

High-precision indoor positioning framework, version 3.

The Framework for Internal Navigation and Discovery (FIND) is like indoor GPS for your house or business, using only a simple smartphone or laptop. Th

Jan 1, 2023
Comments
  • Memory Leak Problem.

    Memory Leak Problem.

    In ws_cli.go file in the receive() function

    You have a never ending for loop and a defer in it, which causes memory leak.

    	ctx := context.Background()
    	ctx, cancel := context.WithTimeout(ctx, time.Millisecond*100)
    	defer cancel() // THIS IS THE PROBLEM CAUSES MEAMORY LEAK
    	select {
    	//
    	//	Discarding messages can easily lead to data processing errors
    	//
    	//case <-ctx.Done():
    	//	log.Println("Waiting timeout, message discarded - ", data)
    	case ch <- &Msg{Timestamp: timestamp, Info: data}:
    	}
    

    I do not know how to contribute to your code, just wanted to comment on that.

    Thx for the library

  • 请问深度校验中以下这段代码是何意

    请问深度校验中以下这段代码是何意

    arr := strings.Split(ask[0], ".") if len(arr) > 1 && len(arr[1]) > 2 { fmt.Println("ask数据异常,", checksum, "ask:", ask) t.Fatal() end <- struct{}{} return nil } else { fmt.Println("bid数据正常,", checksum, "ask:", ask) } 一些产品小数点后面有4位,谢谢请指教

  • go get 无法导入

    go get 无法导入

    使用 go get github.com/caronwang/OKEX_V5SDK_GO 下载依赖报错: go: github.com/caronwang/[email protected]: parsing go.mod: module declares its path as: v5sdk_go but was required as: github.com/caronwang/OKEX_V5SDK_GO

This is a Golang wrapper for working with TMDb API. It aims to support version 3.
This is a Golang wrapper for working with TMDb API. It aims to support version 3.

This is a Golang wrapper for working with TMDb API. It aims to support version 3. An API Key is required. To register for one, head over to themoviedb

Dec 27, 2022
The client of NodeStatus / Golang Version

NodeStatus-client-go The client of NodeStatus written in Golang 使用说明 请直接下载release下的对应平台的二进制文件。 运行时需传入客户端对应参数。 假设你的服务端地址是https://tz.mydomain.com,客户端用户名

Dec 26, 2022
The task given by Appointy completed to develop APIs for a basic version of Instagram.

✨ Instagram APIs ✨ The task given by Appointy completed to develop APIs for a basic version of Instagram. Create an User Get User by Id Create a Post

Oct 9, 2021
The task is to develop a basic version of a Instagram.
The task is to develop a basic version of a Instagram.

Golang-api-task Developer: Mukka Deepak The task is to develop a basic version of aInstagram. You are only required to develop the API for the system.

Oct 23, 2021
A serverless teeny-tiny version of Diomedes which sends alerts to Telegram. Written in Go.
A serverless teeny-tiny version of Diomedes which sends alerts to Telegram. Written in Go.

diomedes-search Get a notification on Telegram whenever your movie opens bookings in a theater of your choice. Pre-requisites Install AWS CLI (v2) by

Oct 11, 2022
Sdk-go - Go version of the Synapse SDK

synapsesdk-go Synapse Protocol's Go SDK. Currently in super duper alpha, do not

Jan 7, 2022
Go-archvariant - Go package for determining the maximum compatibility version of the current system

go-archvariant Go package for determining the maximum compatibility version of t

Feb 19, 2022
Golang API for Whatsapp API MultiDevice version
Golang API for Whatsapp API MultiDevice version

Go Whatsapp API Multi Device Version Required Mac OS: brew install vips export C

Jan 3, 2023
🐥 Sturdy is an open-source, real-time, version control platform for startups
🐥 Sturdy is an open-source, real-time, version control platform for startups

Welcome to Sturdy! ?? ?? Real-time code collaboration. Sturdy is an open-source version control platform that allows you to interact with your code at

Dec 24, 2022
Bump-version - Bump a given semantic version, following a given version fragment

bump-version Bump a given semantic version, following a given version fragment.

Feb 7, 2022