8
Follow
1370
Followers
多机器人行情共享解决方案
Created 2020-07-15 16:25:20 Updated 2024-12-10 10:11:04
4
2681
多机器人行情共享解决方案
在使用数字货币量化交易机器人时,当一个服务器上要跑多个机器人,如果访问不同的交易所,此时问题不大,不会出现API请求频率问题。如果需要有多个机器人同时运行,并且都是做同一个交易所,同一个交易对的量化交易策略。这个时候就有API请求频率限制的问题了。那么如何在用最少的服务器的情况下解决多机器人访问接口的问题呢?
我们可以实现一个行情转发机器人,访问交易所接口获取行情等数据只用这一个机器人去完成。其它交易策略机器人向这个行情转发机器人请求数据即可。
行情转发机器人例子
只负责访问交易所行情接口获取数据,并且给其它机器人提供行情。使用Python编写,例子中我们只获取K线数据,并且提供共享,可以扩展增加深度数据,聚合行情数据等。
python
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编写,为了画图,需要勾选「画线类库」可以在策略广场搜索复制这个类库,复制后在策略编辑页面中模板引用一栏即可勾选。
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)
}
}
实际运行
这样便实现了三个甚至N个机器人对某个交易对K线数据的共享。
抛砖引玉,欢迎留言。
Related Recommendations
Robot WeChat message push implementation schemeGraphical Martingale Trading StrategyPython version iceberg commission strategyThe Logic of Crypto Currency Futures TradingBottom shape ZDZB strategySolution of numerical calculation accuracy problem in JavaScript strategy designTeach you to encapsulate a Python strategy into a local fileFMEX trading unlocks the optimal order volume optimization Part 2FMEX trading unlocks the optimal order volume optimizationAnalysis and Realization of Commodity Futures Volume Footprint Chart
Comment
All comments (2)
- 1






