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. 变量.字符串.列表.词典 ...
随机推荐
- 【Leetcode】【Medium】Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters. For example, ...
- .net 面向对象程序设计深入](3)UML
1.活动图简介 定义:是阐明了业务用例实现的工作流程. 业务工作流程说明了业务为向所服务的业务主角提供其所需的价值而必须完成的工作. 业务用例由一系列活动组成,它们共同为业务主角生成某些工件. 工作流 ...
- Maven学习总结(一)——pom.xml文件配置详解
<build>标签:<plugins>给出构建过程中所用到的插件 <plugins> <plugin> <groupId>org.apach ...
- Redis 4.0+安装及配置
系统环境:CentOS 7.3 官方下载最新版:https://redis.io/download:或直接终端下载解析安装: $ wget http://download.redis.io/relea ...
- February 8 2017 Week 6 Wednesday
Goals determine what you are going to be. 目标决定你将成为什么样的人. Owning some goals in life means you will ha ...
- SVN安装操作流程
SVN 安装操作流程 1.服务端安装流程 1.1 双击打开svn-server安装包 1.2 点击Next 1.3 勾选上“I accert the terms in the License Agre ...
- SAP CRM One Order跟踪和日志工具CRMD_TRACE_SET
事务码CRMD_TRACE_SET激活跟踪模式: 在跟踪模式下运行One Order场景.运行完毕后,使用事务码CRMD_TRACE_EVAL: 双击参数,就能看到参数明细: 点Callstack也能 ...
- ERP系统架构
分布式.服务化的ERP系统架构设计 ERP之痛 曾几何时,我混迹于电商.珠宝行业4年多,为这两个行业开发过两套大型业务系统(ERP).作为一个ERP系统,系统主要功能模块无非是订单管理.商品管理.生产 ...
- mongoDB 固定集合(capped collection)
固定集合(Capped Collection)是一种尺寸固定的“循环”集合,可提供高效的创建.读取.删除等操作.这里所指的“循环”的意思是,当分配给集合的文件尺寸耗尽时,就会自动开始删除最初的文档,不 ...
- BZOJ5293:[BJOI2018]求和(LCA,差分)
Description master 对树上的求和非常感兴趣.他生成了一棵有根树,并且希望多次询问这棵树上一段路径上所有节点深度的k 次方和,而且每次的k 可能是不同的.此处节点深度的定义是这个节点 ...