파이썬을 사용하여 정해진 시간 시작 또는 중지 기기 양적 거래 로봇을 구현

저자:리디아, 창작: 2022-12-20 14:35:09, 업데이트: 2023-09-20 10:21:21

img

파이썬을 사용하여 정해진 시간 시작 또는 중지 기기 양적 거래 로봇을 구현

전 네트워크에 대한 강력하고 유연하고 사용하기 쉬운 양적 거래 플랫폼으로서 FMZ 양적 거래 플랫폼은 사용하기에는 매우 낮은 장벽이 있으며 로봇 프로그램이 적은 자원을 차지합니다. 그러나 우리는 여전히 로봇이 실행해야 할 때 시작하고 실행할 필요가 없을 때 멈출 수 있기를 바랍니다. 예를 들어, 오픈 시간이 아닌 시간은 상품 선물의 프로그램 및 양적 거래를 수행 할 때 하루 전체의 대부분을 차지합니다. 이러한 방식으로, 우리는 로봇이 오픈 시간에만 실행되고 돈을 절약하기 위해 매일 오픈 시간에만 실행되기를 바랍니다. 흥미롭지 않습니까? 이 요구 사항을 충족시키기 위해, 우리는 파이썬 언어를 사용하여 FMZ 퀀트 트레이딩 플랫폼에서 실행되는 전략 로봇을 작성할 수 있으며, 로봇이 FMZ 퀀트 트레이딩 플랫폼의 확장 API 인터페이스를 통해 로봇의 시작과 정지를 규칙적인 간격으로 제어 할 수 있습니다.

필요하다면 해보자!

사실, 전체 코드는 매우 간단합니다. FMZ 양자 거래 플랫폼 확장 API 인터페이스를 호출하는 예를 직접 사용할 수 있습니다.

주소:https://www.fmz.com/api#simple예제

예제에서 함수를 직접 사용하세요:def api (method, *args)우리가 호출해야 하는 인터페이스는 또한 매우 간단합니다. 다음 두 개의 인터페이스는 사용 됩니다 (FMZ 문서에서 찾을 수 있습니다)

  • 다시 시작Robot 로봇 인터페이스를 다시 시작하고 로봇 ID에 매개 변수를 입력합니다. 특정 사용id전화:api ('RestartRobot', id)

  • 정지Robot 로봇 인터페이스를 중지하기 위해, 매개 변수는 또한 로봇입니다ID- 그래요 로봇ID:

img

FMZ 양자 거래 플랫폼 확장 API를 호출하려면API KEYFMZ 양자 거래 플랫폼의 계정 관리에서 자신의 API 키를 생성할 수 있습니다. 우리는 통과API KEY전략적 매개 변수로 FMZ 양자 거래 플랫폼 계정을 얻는 스크린 샷API KEY:

img

나머지 부분은 타이밍 논리를 작성하는 것입니다. 또한 매우 간단합니다. 타이밍 매개 변수를 설정합니다.

["175708,14:55:33-15:10:33", ...]

은 더 많은 설정과 같은 것을 나타냅니다."175708,14:55:33-15:10:33"설정할 수 있습니다. 타이밍 매개 변수는 JSON 문자열이며 전략 코드에서 목록으로 분석됩니다. 목록의 각 요소는 로봇 시작/정지 설정의 집합입니다. 특히:

"175708,14:55:33-15:10:33"

이 부분들은 우수점으로 분리되어 있습니다. 우수점 앞에 있는 부분은175708로봇 ID이고, 오차 뒤에 있는 부분은 시작/정지 시간입니다. 위의 예제에서 ID 175708의 로봇은 14:55:33에 시작하여 15:10:33에 멈춥니다.

그 다음, 전략에서, 로봇은 계속 회전합니다. 각 라운드 회전은 먼저 현재 시간을 얻으며, 현재 시간과 타이밍 시간 사이의 비교에 따라 로봇의 시작이나 정지 여부를 판단합니다. 트리거되면 api (RestartRobot, id) 또는 api (StopRobot, id) 를 호출하여 로봇을 시작 및 중지합니다.

전체 전략 코드:

# -*- coding: utf-8 -*-
import time
import json

try:
    import md5
    import urllib2
    from urllib import urlencode
except:
    import hashlib as md5
    import urllib.request as urllib2
    from urllib.parse import urlencode

def api(method, *args):
    d = {
        'version': '1.0',
        'access_key': accessKey,
        'method': method,
        'args': json.dumps(list(args)),
        'nonce': int(time.time() * 1000),
        }

    d['sign'] = md5.md5(('%s|%s|%s|%d|%s' % (d['version'], d['method'], d['args'], d['nonce'], secretKey)).encode('utf-8')).hexdigest()
    return json.loads(urllib2.urlopen('https://www.fmz.com/api/v1', urlencode(d).encode('utf-8')).read().decode('utf-8'))

RobotParams = json.loads(strRobotParams)

def main():
    global RobotParams 
    arrParams = []
    nowDay = 0
    strPush = ""
    if isPushMsg:
        strPush = "@"

    for i in range(len(RobotParams)):
        param = {}
        arr = RobotParams[i].split(",")
        if len(arr) != 2:
            raise Exception("String configuration error: delimiter,")
        param["id"] = arr[0]
        param["isProcessOpenThisDay"] = False
        param["isProcessCloseThisDay"] = False

        arr = arr[1].split("-")
        if len(arr) != 2:
            raise Exception("String configuration error: delimiter-")

        begin = arr[0]
        arrBegin = begin.split(":")
        if len(arrBegin) != 3:
            raise Exception("String configuration error: start time separator:")
        
        param["begin"] = {}
        param["begin"]["hour"] = float(arrBegin[0])
        param["begin"]["min"] = float(arrBegin[1])
        param["begin"]["sec"] = float(arrBegin[2])

        end = arr[1]
        arrEnd = end.split(":")
        if len(arrEnd) != 3:
            raise Exception("String configuration error: end time separator:")            
        
        param["end"] = {}
        param["end"]["hour"] = float(arrEnd[0])
        param["end"]["min"] = float(arrEnd[1])
        param["end"]["sec"] = float(arrEnd[2])
        arrParams.append(param)

    # Test
    Log("Output parameters", arrParams, "#FF0000")  

    while True:
        nowTime = time.localtime(time.time())
        nowHour = nowTime.tm_hour 
        nowMin = nowTime.tm_min
        nowSec = nowTime.tm_sec
        
        tbl = {
            "type" : "table", 
            "title" : "msg", 
            "cols" : ["id", "begin", "end", "Did you perform a start today", "Did you perform a stop today"],
            "rows" : []
        }

        for i in range(len(arrParams)):
            tbl["rows"].append([arrParams[i]["id"], json.dumps(arrParams[i]["begin"]), json.dumps(arrParams[i]["end"]), arrParams[i]["isProcessOpenThisDay"], arrParams[i]["isProcessCloseThisDay"]])
            if nowDay != nowTime.tm_mday:
                arrParams[i]["isProcessOpenThisDay"] = False
                arrParams[i]["isProcessCloseThisDay"] = False

            if arrParams[i]["isProcessOpenThisDay"] == False:
                if nowTime.tm_hour == arrParams[i]["begin"]["hour"] and nowTime.tm_min >= arrParams[i]["begin"]["min"] and nowTime.tm_sec >= arrParams[i]["begin"]["sec"]:
                    ret = api('RestartRobot', int(arrParams[i]["id"]))                    
                    arrParams[i]["isProcessOpenThisDay"] = True
                    Log("Robot ID:", arrParams[i]["id"], "Execution started, please log in to the platform to check if it started successfully", "Extended API return value:", ret, strPush)

            if arrParams[i]["isProcessCloseThisDay"] == False:
                if nowTime.tm_hour == arrParams[i]["end"]["hour"] and nowTime.tm_min >= arrParams[i]["end"]["min"] and nowTime.tm_sec >= arrParams[i]["end"]["sec"]:
                    ret = api('StopRobot', int(arrParams[i]["id"]))
                    arrParams[i]["isProcessCloseThisDay"] = True
                    Log("Robot ID:", arrParams[i]["id"], "Execution stopped, please log in to the platform to check if it stopped successfully", "Extended API return value:", ret, strPush)
        
        if nowDay != nowTime.tm_mday:
            nowDay = nowTime.tm_mday

        LogStatus(_D(), nowTime, "\n`" + json.dumps(tbl) + "`")
        Sleep(500)

로봇 파라미터 설정:

img

전략 실행:

스크린샷:

img img

전략 주소:https://www.fmz.com/strategy/184600

예를 들어, FMZ 양자 거래 플랫폼의 확장 API는 여전히 매우 강력합니다. 이러한 확장 API를 사용하여 FMZ 플랫폼을 기반으로 자신의 양적 거래 플랫폼을 구축하는 것은 문제가 없습니다. 타이밍 로봇은 설계가 간단하며, 시간에 시작하고 시간에 멈추는 것입니다. 시작이 성공했는지, 검사, 예외 재시험 등과 같은 메커니즘을 포함하지 않습니다. 관심이 있다면 기능을 추가하고 확장 할 수 있습니다. 이 전략은 참고용입니다.


관련

더 많은