当前位置:网站首页>多机器人行情共享解决方案
多机器人行情共享解决方案
2020-11-06 20:21:00 【发明者量化】
多机器人行情共享解决方案
在使用数字货币量化交易机器人时,当一个服务器上要跑多个机器人,如果访问不同的交易所,此时问题不大,不会出现API请求频率问题。如果需要有多个机器人同时运行,并且都是做同一个交易所,同一个交易对的量化交易策略。这个时候就有API请求频率限制的问题了。那么如何在用最少的服务器的情况下解决多机器人访问接口的问题呢?
我们可以实现一个行情转发机器人,访问交易所接口获取行情等数据只用这一个机器人去完成。其它交易策略机器人向这个行情转发机器人请求数据即可。
行情转发机器人例子
只负责访问交易所行情接口获取数据,并且给其它机器人提供行情。使用Python编写,例子中我们只获取K线数据,并且提供共享,可以扩展增加深度数据,聚合行情数据等。
import _thread
import threading
import json
import math
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import parse_qs, urlparse
Records = None
lock = threading.RLock()
Counter = {}
def url2Dict(url):
query = urlparse(url).query
params = parse_qs(query)
result = {key: params[key][0] for key in params}
return result
class Provider(BaseHTTPRequestHandler):
def do_GET(self):
global Records, lock, Counter
try:
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
dictParam = url2Dict(self.path)
# Log("服务接收到请求,self.path:", self.path, "query 参数:", dictParam)
lock.acquire()
# 记录
if dictParam["robotId"] not in Counter:
Counter[dictParam["robotId"]] = {"NumberOfRequests" : 0}
Counter[dictParam["robotId"]]["NumberOfRequests"] += 1
lock.release()
# 写入数据应答
self.wfile.write(json.dumps(Records).encode())
except BaseException as e:
Log("Provider do_GET error, e:", e)
def createServer(host):
try:
server = HTTPServer(host, Provider)
Log("Starting server, listen at: %s:%s" % host)
server.serve_forever()
except BaseException as e:
Log("createServer error, e:", e)
raise Exception("stop")
def main():
global Records, Counter
LogReset(1)
try:
# _thread.start_new_thread(createServer, (("localhost", 9090), )) # 本机测试
_thread.start_new_thread(createServer, (("0.0.0.0", 9090), )) # VPS服务器上测试
Log("启动服务", "#FF0000")
except BaseException as e:
Log("启动服务失败!")
Log("错误信息:", e)
raise Exception("stop")
while True:
r = exchange.GetRecords()
if not r :
Log("K线行情获取失败", "#FF0000")
continue
else :
Records = r
# Counter
tbl = {
"type" : "table",
"title" : "统计信息",
"cols" : ["请求数据的机器人id", "请求次数"],
"rows" : [],
}
for k in Counter:
tbl["rows"].append([k, Counter[k]["NumberOfRequests"]])
LogStatus(_D(), "数据收集中!", "\n", "`" + json.dumps(tbl) + "`")
Sleep(500)
请求数据机器人策略代码
请求数据的机器人即为交易策略机器人,只不过我们测试用,只写请求数据(K线数据)并且把数据画出来,可以用JavaScript编写,为了画图,需要勾选「画线类库」可以在策略广场搜索复制这个类库,复制后在策略编辑页面中模板引用一栏即可勾选。
var FuncGetRecords = exchange.GetRecords
exchange.GetRecords = function() {
// 可以填写「行情转发机器人」所在设备的IP地址xxx.xxx.xxx.xxx
var ret = HttpQuery("http://xxx.xxx.xxx.xxx:9090?robotId=" + _G())
var records = null
try {
records = JSON.parse(ret)
} catch(e) {
Log(e)
records = null
}
return records
}
function main(){
LogReset(1)
while(1) {
var records = exchange.GetRecords()
LogStatus(_D(), "机器人ID:", _G())
if (!records) {
Log("获取数据失败!", "#FF0000")
Sleep(1000)
continue
}
Log(records)
$.PlotRecords(records, "K")
Sleep(1000)
}
}
实际运行
-
启动行情转发机器人

-
启动测试机器人,ID:206353

-
启动测试机器人,ID:206359

-
启动测试机器人,ID:206360

这样便实现了三个甚至N个机器人对某个交易对K线数据的共享。
抛砖引玉,欢迎留言。
版权声明
本文为[发明者量化]所创,转载请带上原文链接,感谢
https://my.oschina.net/u/3949465/blog/4705494
边栏推荐
- 安装Anaconda3 后,怎样使用 Python 2.7?
- Kitty中的动态线程池支持Nacos,Apollo多配置中心了
- Technical director, to just graduated programmers a word - do a good job in small things, can achieve great things
- 谁说Cat不能做链路跟踪的,给我站出来
- 如何在Windows Server 2012及更高版本中將域控制器降級
- 嘗試從零開始構建我的商城 (二) :使用JWT保護我們的資訊保安,完善Swagger配置
- Details of dapr implementing distributed stateful service
- Basic principle and application of iptables
- Cocos Creator 原始碼解讀:引擎啟動與主迴圈
- 【QT】 QThread部分原始碼淺析
猜你喜欢

Flink的DataSource三部曲之二:内置connector

条码生成软件如何隐藏部分条码文字

Don't go! Here is a note: picture and text to explain AQS, let's have a look at the source code of AQS (long text)

Technical director, to just graduated programmers a word - do a good job in small things, can achieve great things

Jmeter——ForEach Controller&Loop Controller

Using Es5 to realize the class of ES6

DevOps是什么

你的财务报告该换个高级的套路了——财务分析驾驶舱

DTU连接经常遇到的问题有哪些

词嵌入教程
随机推荐
Anomaly detection method based on SVM
大数据应用的重要性体现在方方面面
10 easy to use automated testing tools
Chainlink将美国选举结果带入区块链 - Everipedia
Existence judgment in structured data
Listening to silent words: hand in hand teaching you sign language recognition with modelarts
Elasticsearch database | elasticsearch-7.5.0 application construction
03_ Detailed explanation and test of installation and configuration of Ubuntu Samba
【QT】 QThread部分原始碼淺析
7.2.2 compressing static resources through gzipresourceresolver
C language 100 question set 004 - statistics of the number of people of all ages
深度揭祕垃圾回收底層,這次讓你徹底弄懂她
【新閣教育】窮學上位機系列——搭建STEP7模擬環境
高级 Vue 组件模式 (3)
nlp模型-bert从入门到精通(一)
vite + ts 快速搭建 vue3 專案 以及介紹相關特性
Use of vuepress
不吹不黑,跨平臺框架AspNetCore開發實踐雜談
Azure Data Factory(三)整合 Azure Devops 實現CI/CD
Computer TCP / IP interview 10 even asked, how many can you withstand?