Go编写一个比特币交易自动出价程序
语言环境为>=go1.10
go语言环境不多说
实现目的能与BitMEX api进行交互自动交易,目前虚拟币平台很多,平台API实现也很容易.后续会加上其它平台和自动交易算法策略,具体看平台交易手续费性价比而定.
先从国内平台开始,以GO语言为例子,其他语言也有很多,主要是学习GO语言.
这里需要用到websocket,当然还有其他形式的请求API,这里以这种形式为例子,
先从火币开始,如果不知道API具体参数可查看官网.
先在我的GOPATH中的SRC目录中创建一个文件夹,为huobi,在这个文件夹中创建一个主程序main.go,单纯请求火币获取行情参数.
websocket使用第三方包使用,github.com/gorilla/websocket,比官方的net包多些功能.引入后创建类型拨号器,然后拨号
这是拨号器结构体,拨号器包含连接websocket的选项
type Dialer struct {
// NetDial specifies the dial function for creating TCP connections. If
// NetDial is nil, net.Dial is used.
NetDial func(network, addr string) (net.Conn, error) // Proxy specifies a function to return a proxy for a given
// Request. If the function returns a non-nil error, the
// request is aborted with the provided error.
// If Proxy is nil or returns a nil *URL, no proxy is used.
Proxy func(*http.Request) (*url.URL, error) // TLSClientConfig specifies the TLS configuration to use with tls.Client.
// If nil, the default configuration is used.
TLSClientConfig *tls.Config // HandshakeTimeout specifies the duration for the handshake to complete.
HandshakeTimeout time.Duration // ReadBufferSize and WriteBufferSize specify I/O buffer sizes. If a buffer
// size is zero, then a useful default size is used. The I/O buffer sizes
// do not limit the size of the messages that can be sent or received.
ReadBufferSize, WriteBufferSize int // Subprotocols specifies the client's requested subprotocols.
Subprotocols []string // EnableCompression specifies if the client should attempt to negotiate
// per message compression (RFC 7692). Setting this value to true does not
// guarantee that compression will be supported. Currently only "no context
// takeover" modes are supported.
EnableCompression bool // Jar specifies the cookie jar.
// If Jar is nil, cookies are not sent in requests and ignored
// in responses.
Jar http.CookieJar
}
根据需求创建好后拨号,包含字符串很请求协议,协议一般为nil
func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Response, error)
接下来进入API规则部分,对应火币,
完整代码
package main import (
"fmt"
"time"
"strconv" //字符串转换
"encoding/json" //JSON包
"github.com/gorilla/websocket" //go的websocket实现
"huobi/common"
"huobi/conf"
) func main() {
dialer := websocket.Dialer{/*根据需要设置字段*/} //类型拨号器
ws, _, err := dialer.Dial("wss://api.huobi.pro/ws", nil) //拨号,返回连接对象,响应和错误
if err != nil {
// handle error
} for { //因为是websocket,所以是不停的
if _,p,err := ws.ReadMessage();err == nil { //读取信息,这里是火币的规则
res := common.UnGzip(p) //解压数据
fmt.Println(string(res)) //输出字符串
resMap := common.JsonDecodeByte(res) //JSON解码
if v, ok := resMap["ping"];ok {
pingMap := make(map[string]interface{})
pingMap["pong"] = v //发送pong包,完成ping,pong
pingParams := common.JsonEncodeMapToByte(pingMap) //转成JSON
if err := ws.WriteMessage(websocket.TextMessage, pingParams); err == nil { //发送消息,TextMessage是整型,整数常量来标识两种数据消息类型
reqMap := new(common.ReqStruct)//创建结构体指针
reqMap.Id = strconv.Itoa(time.Now().Nanosecond())
reqMap.Req = conf.LtcTopic.KLineTopicDesc
reqBytes , err := json.Marshal(reqMap)
if err!=nil {
continue
}
if err := ws.WriteMessage(websocket.TextMessage,reqBytes); err == nil { //发送ID REQ
}else{
fmt.Errorf("send req response error %s",err.Error())
}
}else{
fmt.Errorf("huobi server ping client error %s",err.Error())
continue
}
}
if _, ok := resMap["rep"];ok {
var resStruct common.ResStruct
json.Unmarshal(res,&resStruct)
//resStruct.Status
fmt.Println(resStruct)//输出内容
}
}
}
}
如果无法访问还需设置代理
dialer := websocket.Dialer{Proxy:func(*http.Request) (*url.URL, error) {
return url.Parse("http://127.0.0.1:1080")
}, //类型拨号器
}
流程:
1.火币的API数据都是gzip压缩过的,所以一开始连接API接收数据需要把数据进行解压
2.解压完输出内容,输出完进行JSON的解析,然后把PING对应的值取出赋值给PING发送回去,这是火币心跳包检测,两次没发回去则断开连接
3.然后请求需要获取的币种格式,market.$symbol.kline.$period对应
"req": "market.btcusdt.kline.1min",
"id": "id10"
4.这是请求数据,然后会得到反馈
Go编写一个比特币交易自动出价程序的更多相关文章
- 如何编写一个编译c#控制台应用程序的批处理程序
如何编写一个编译c#控制台应用程序的批处理程序 2011-03-22 18:14 dc毒蘑菇 | 浏览 579 次 最近在网上看了一个教程,是学C#的,但是我的机子上装不上vs,所以想写一个批处理来编 ...
- JNI编程(一) —— 编写一个最简单的JNI程序
来自:http://chnic.iteye.com/blog/198745 忙了好一段时间,总算得了几天的空闲.貌似很久没更新blog了,实在罪过.其实之前一直想把JNI的相关东西整理一下的,就从今天 ...
- JNI编程(一) —— 编写一个最简单的JNI程序(转载)
转自:http://chnic.iteye.com/blog/198745 忙了好一段时间,总算得了几天的空闲.貌似很久没更新blog了,实在罪过.其实之前一直想把JNI的相关东西整理一下的,就从今天 ...
- 如何在linux下编写一个简单的Shell脚本程序
在了解了linux终端和其搭配的基本Shell(默认为bash)的基础下,我们就可以在终端中用vi/vim编辑器编写一个shell的脚本程序了 Shell既为一种命令解释解释工具,又是一种脚本编程语言 ...
- 编写一个基于HBase的MR程序,结果遇到一个错:ERROR security.UserGroupInformation - PriviledgedActionException as ,求帮助
环境说明:Ubuntu12.04,使用CDH4.5,伪分布式环境 Hadoop配置如下: core-site.xml: <configuration><property> ...
- C#编写一个较完整的记事本程序
开发环境 Visual Studio 2019 至少需安装 .NET桌面开发 创建项目并配置 创建窗体文件 配置项目名称及框架 设计界面 创建窗体文件,将控件摆放位置如下,参考系统自带的记事本程序 窗 ...
- 编写一个简单的java服务器程序
import java.net.*;import java.io.*; public class server{ ); //监听在80端口 Socket sock = server.accept(); ...
- sql server编写一个语句脚本自动清空各表数据以初始化数据库
问题:有时已有项目要移植,例如原来在广州地区使用的某系统,突然说惠州那边也要用这套一样的系统.或者,在demo环境下弄了一些测试数据.然后要清空全部表数据.如果表比较多的话,逐个表手工编写脚本就太麻烦 ...
- 通过编写一个简单的漏洞扫描程序学习Python基本语句
今天开始读<Python绝技:运用Python成为顶级黑客>一书,第一章用一个小例子来讲解Python的基本语法和语句.主要学习的内容有:1. 安装第三方库.2. 变量.字符串.列表.词典 ...
随机推荐
- 查询SQL Server 版本信息
select SERVERPROPERTY('ProductVersion') as ProductionVersion, SERVERPROPERTY('ProductLevel')as Produ ...
- client、offset、scroll系列
代码如下: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <tit ...
- ssh_exchange_identification: Connection closed by remote host
用服务器内网ip连接同子网服务器的时候显示ssh_exchange_identification: Connection closed by remote host 防火墙什么都关闭了,还是显示这个问 ...
- QT的lineidet的光标问题
http://blog.csdn.net/Howard_Liu1314/article/details/10456165
- Python学习---协程 1226
协程[是一个单线程],又称微线程,纤程.英文名Coroutine. 一句话说明什么是协程:协程是一种用户态的轻量级线程[程序员自己去切换线程] 协程条件: 必须在只有一个单线程里实现并发 修改共享数据 ...
- AngularJs学习笔记--Understanding Angular Templates
原版地址:http://docs.angularjs.org/guide/dev_guide.mvc.understanding_model angular template是一个声明规范,与mode ...
- WAS缓存问题
在项目中经常遇见这样的问题:修改应用的配置文件web.xml后,无论重启应用还是重启WebSphere服务器,都不能重新加载web.xml,导致修改的内容无效. 这个问题困扰了我好久,即使删除了${w ...
- JS中confirm弹出框
if(confirm("确定要删除该任务吗?")){ $.post("findTaskById.action",{taskId:taskId},function ...
- Mac 导入maven项目详解
1.打开Eclipse,选择Help->Install New SoftWare2.点击add 地址输入:http://m2eclipse.sonatype.org/sites/m2e,name ...
- MyBatis(9)整合spring
具体的感兴趣可以参考:MyBatis 此时此刻,没用的话不再多说了,直接开始代码工程吧! 整体的代码实现: 具体使用到的我们在进行细说 基本上理解一边就能会使用整合 准备工作: db.proper ...