The resource loading... loading...

Multi-robot market sharing solutions

Author: Inventors quantify - small dreams, Created: 2020-07-15 16:25:20, Updated: 2024-12-10 10:11:04

img

Multi-robot market sharing solutions

When using a digital currency quantified trading robot, when multiple robots are running on a server, if access to different exchanges, this is not a big problem, there is no problem with API request frequency. If multiple robots are needed to run simultaneously, and are doing the same exchange, the same transaction pair.

We can implement a market forwarding robot, access the exchange interface, access the market data, etc. with only this one robot. Other trading strategies can be done by the robot to the market forwarding the robot request data.

Examples of business forwarding robots

It is only responsible for accessing the exchange's trading interface to obtain data and provide trading to other robots.PythonIn this example, we only get K-line data and provide sharing, which can be extended to add depth data, aggregate market data, etc.

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)
        

Request the data robot policy code

The robot that requests data is a trading strategy robot, but we're testing it, just writing the request data (K-line data) and drawing the data out, and we can use it.JavaScriptTo compile, to draw a diagram, you need to select "Drawline class library". You can copy this class library in the policy square search, and after copying in the policy edit page, you can select a template reference.

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)
    }
}

Practical operation

  • The launch of the marketplace for delivery robotsimg

  • Starting the test robot, ID:206353img

  • Starting the test robot, ID:206359img

  • Starting the test robot, ID:206360img

This enables three or even N robots to share K-line data for a transaction. I'm glad to see you're doing well.


Related

More

The short-line king won selling the high-price strategyGood for you.

xunfeng91 666