다중 로봇 시장 공유 솔루션

저자:작은 꿈, 2020-07-15 16:25:20, 업데이트: 2023-09-27 19:36:39

img

다중 로봇 시장 공유 솔루션

디지털 통화 양화 거래 로봇을 사용할 때, 하나의 서버에 여러 로봇이 실행되어야 할 때, 서로 다른 거래소를 방문하면 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)
    }
}

실제 운영

  • 시장에서 보트 전송을 시작img

  • 테스트 로봇을 시작, ID:206353img

  • 테스트 로봇을 시작, ID:206359img

  • 테스트 로봇, ID:206360을 시작하십시오.img

이렇게 하면 세 개 또는 N 개 이상의 로봇이 거래에 대한 K 라인 데이터를 공유할 수 있습니다.


관련

더 많은

단선 왕승은 높은 가격에 전략을 판매합니다좋은 동쪽

펑91 666