语言环境为>=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编写一个比特币交易自动出价程序的更多相关文章

  1. 如何编写一个编译c#控制台应用程序的批处理程序

    如何编写一个编译c#控制台应用程序的批处理程序 2011-03-22 18:14 dc毒蘑菇 | 浏览 579 次 最近在网上看了一个教程,是学C#的,但是我的机子上装不上vs,所以想写一个批处理来编 ...

  2. JNI编程(一) —— 编写一个最简单的JNI程序

    来自:http://chnic.iteye.com/blog/198745 忙了好一段时间,总算得了几天的空闲.貌似很久没更新blog了,实在罪过.其实之前一直想把JNI的相关东西整理一下的,就从今天 ...

  3. JNI编程(一) —— 编写一个最简单的JNI程序(转载)

    转自:http://chnic.iteye.com/blog/198745 忙了好一段时间,总算得了几天的空闲.貌似很久没更新blog了,实在罪过.其实之前一直想把JNI的相关东西整理一下的,就从今天 ...

  4. 如何在linux下编写一个简单的Shell脚本程序

    在了解了linux终端和其搭配的基本Shell(默认为bash)的基础下,我们就可以在终端中用vi/vim编辑器编写一个shell的脚本程序了 Shell既为一种命令解释解释工具,又是一种脚本编程语言 ...

  5. 编写一个基于HBase的MR程序,结果遇到一个错:ERROR security.UserGroupInformation - PriviledgedActionException as ,求帮助

    环境说明:Ubuntu12.04,使用CDH4.5,伪分布式环境 Hadoop配置如下: core-site.xml: <configuration><property>    ...

  6. C#编写一个较完整的记事本程序

    开发环境 Visual Studio 2019 至少需安装 .NET桌面开发 创建项目并配置 创建窗体文件 配置项目名称及框架 设计界面 创建窗体文件,将控件摆放位置如下,参考系统自带的记事本程序 窗 ...

  7. 编写一个简单的java服务器程序

    import java.net.*;import java.io.*; public class server{ ); //监听在80端口 Socket sock = server.accept(); ...

  8. sql server编写一个语句脚本自动清空各表数据以初始化数据库

    问题:有时已有项目要移植,例如原来在广州地区使用的某系统,突然说惠州那边也要用这套一样的系统.或者,在demo环境下弄了一些测试数据.然后要清空全部表数据.如果表比较多的话,逐个表手工编写脚本就太麻烦 ...

  9. 通过编写一个简单的漏洞扫描程序学习Python基本语句

    今天开始读<Python绝技:运用Python成为顶级黑客>一书,第一章用一个小例子来讲解Python的基本语法和语句.主要学习的内容有:1. 安装第三方库.2. 变量.字符串.列表.词典 ...

随机推荐

  1. Going Deeper with Convolutions(Inception v1)笔记

    目录 Abstract Introduction First of All Inception Depth Related Work Motivation and High Level Conside ...

  2. oam系统安装,windows操作系统注册列表影响系统安装

    windows注册列表可能会影响到系统的安装,本次安装oam10g版本,安装后没有问题,但是在配置oam和weblogic portal单点登录时在weblogic portal中访问oid和oam的 ...

  3. January 14 2017 Week 2nd Saturday

    Don't try so hard, the best things come when you least expect them to. 不要着急,最好的总会在最不经意时出现. The secon ...

  4. 为网页元素增加resize事件

    默认只有window支持resize事件,但有时我们需要为div等元素添加resize事件 代码见下面,原理是在元素内添加一个内嵌html,然后监听这个内嵌html的resize事件 import { ...

  5. ECharts属性设置

    theme = { // 全图默认背景 // backgroundColor: ‘rgba(0,0,0,0)’, // 默认色板 color: ['#ff7f50','#87cefa','#da70d ...

  6. 洛谷 P3175 [HAOI2015]按位或

    题目分析 与hdu4336 Card Collector相似,使用min-max容斥. 设\(\max(S)\)表示集合\(S\)中最后一位出现的期望时间. 设\(\min(S)\)表示集合\(S\) ...

  7. thrift C++ Centos 安装

    1.在官方下载thrift http://thrift.apache.org/download 这里下载thrift-0.11.0.tar.gz版本 2.如果想支持安装Cpp版本就需要先安装boost ...

  8. 【转】Android开发:shape和selector和layer-list的(详细说明)

    <shape>和<selector>在Android UI设计中经常用到.比如我们要自定义一个圆角Button,点击Button有些效果的变化,就要用到<shape> ...

  9. STS使用git下载项目代码

    在自己的eclipse 上安装git 插件,一般都自带了现在. 4.选择Clone URI 5.下一步输入刚才的复制的路劲,填写自己的github 账户名密码即可 6.选择要克隆的分支 7.设置本地g ...

  10. 【题解】洛谷P4391 [BOI2009] Radio Transmission(KMP)

    洛谷P4391:https://www.luogu.org/problemnew/show/P4391 思路 对于给定的字符串 运用KMP思想 设P[x]为前x个字符前缀和后缀相同的最长长度 则对于题 ...