当前位置:网站首页>多机器人行情共享解决方案
多机器人行情共享解决方案
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
边栏推荐
- ThreadLocal原理大解析
- [译] 5个Vuex插件,给你的下个VueJS项目
- python过滤敏感词记录
- 微信小程序:防止多次点击跳转(函数节流)
- Top 10 best big data analysis tools in 2020
- PLC模拟量输入和数字量输入是什么
- C language 100 question set 004 - statistics of the number of people of all ages
- 我们编写 React 组件的最佳实践
- Elasticsearch database | elasticsearch-7.5.0 application construction
- Dapr實現分散式有狀態服務的細節
猜你喜欢

怎么理解Python迭代器与生成器?

人工智能学什么课程?它将替代人类工作?

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)

有关PDF417条码码制的结构介绍

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

【新閣教育】窮學上位機系列——搭建STEP7模擬環境

從小公司進入大廠,我都做對了哪些事?

嘘!异步事件这样用真的好么?

简直骚操作,ThreadLocal还能当缓存用

mac 下常用快捷键,mac启动ftp
随机推荐
技術總監7年經驗,告訴大家,【拒絕】才是專業
Azure Data Factory(三)整合 Azure Devops 實現CI/CD
6.9.2 session flashmapmanager redirection management
03_ Detailed explanation and test of installation and configuration of Ubuntu Samba
10 easy to use automated testing tools
制造和新的自动化技术是什么?
7.2.2 compressing static resources through gzipresourceresolver
【效能優化】納尼?記憶體又溢位了?!是時候總結一波了!!
從小公司進入大廠,我都做對了哪些事?
简直骚操作,ThreadLocal还能当缓存用
选择站群服务器的有哪些标准呢?
Chainlink将美国选举结果带入区块链 - Everipedia
Gradient understanding decline
Technical director, to just graduated programmers a word - do a good job in small things, can achieve great things
Python自动化测试学习哪些知识?
6.8 multipartresolver file upload parser (in-depth analysis of SSM and project practice)
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)
事半功倍:在没有机柜的情况下实现自动化
Jmeter——ForEach Controller&Loop Controller
Elasticsearch database | elasticsearch-7.5.0 application construction