"Tradingview" 표시기를 사용하여 FMZ 로봇과의 인터페이스

저자:선함, 2020-06-19 11:08:22, 업데이트: 2023-10-31 21:03:33

img

배경 소개

트레이딩뷰는 좋은 시장 코팅 도출 도구입니다.

pine스크립트는 또한 강력한 존재입니다!

백테스팅, 경보, 그리고 다양한 도킹은 매우 완벽한 금융 도구입니다.

하지만 우리를 괴롭히는 두 가지 문제가 있습니다.

  • 하나는 비싼 회원금 시스템입니다
  • 두번째는 신호가 직접 거래될 수 있는 거래소가 거의 없다는 것입니다. 두 개 또는 세 개인 것 같습니다.

오늘 우리 기사는 교환 도킹 문제를 해결하는 데 당신을 데려다줍니다.

시행

전체적인 아이디어는 다음과 같습니다.

TV ((TradingView)pine스크립트 -> 신호 경보webhook-> 지역webhook server전송 요청 -> FMZ bot는 동작 요청을 수신합니다

한 걸음 한 걸음 해보자

트레이딩뷰 웹사이트로 가세요:

https://www.tradingview.com/

다음으로, 우리는 먼저Alert자세한 내용은 아래 그림 참조

img

이 그림의 일부 측면에 관심을 기울여야합니다.Alert.

유효기간webhook주소, 그리고message콘텐츠는 잘 만들어져야 합니다.

유효기간은 한눈에 알 수 있고 유효기간이 끝나면 무효가 됩니다.

WebhookURL, 먼저 비어 두자, 우리는 로컬에서 그것을 채울 것입니다webhook서비스 완료

Message여기서, 우리가 명확한 설명을 하는 것이 가장 좋습니다.bot구별Alert messages.

저는 일반적으로 이렇게 설정합니다: XXX 전략, 주문량 및 거래 방향

지금까지, 트레이딩뷰 부분은 기본적으로 완료되었습니다!

다음으로, 현지인을 찾아보죠webhook서비스 작업 완료!

이런 종류의 작업을 하면 구글에서 많은 결과를 볼 수 있습니다. 이 기사는 이 부분을 건너뛰고, 스스로 할 수 있습니다.

여기 파이썬에 대한 간단한 프레임워크가 있습니다.

GitHub: https://github.com/shawn-sterling/gitlab-webhook-receiver

안전하고 걱정이 없고 편리하지만 문제도 있습니다.

이 작은 프레임, 그것은 될 것입니다!! 자살!! 이 문제에 주의를 기울여 주시기 바랍니다!

그래서 서버에 또 다른 스크립트를 작성했습니다. 로그에 die 또는 offline가 나타나면 다시 시작하겠습니다. 나중에, 저는 여전히 안전하지 않다고 느끼기 때문에 정기적으로 다시 시작하도록 설정했습니다.

또한, 트레이딩뷰는 포트 80만 인식합니다. 그래서 서비스 포트를 망쳐서는 안 됩니다.

지금까지, 우리는Message에서Alert다음으로, 어떻게 봇을 잡을까요?

FMZ의 인터페이스 API 문서를 참고했는지 모르겠네요.

img

우리는 API를 통해 우리의 작은 봇에 몇 가지 명령을 전달할 수 있습니다! 특정 요청 예는 여기 있습니다. 빨간색 상자는 우리가 필요로 하는 요청입니다.

img

여기도 준비 작업이 필요합니다. FMZ API (avatar->account settings->API 인터페이스) 시작된 로봇 (우리는 그 ID를 얻고 싶어, 그래서 우리는 먼저 새로운 ID를 만들), 일반적인 로봇의 URL의 번호는 ID입니다.

img

다음으로, 우리는 웹후크 서비스를 변환하여 메시지를 수신한 후 자동으로 FMZ 봇으로 전송됩니다.

마지막으로, 완료 된 양식을 작성하는 것을 잊지 마십시오.webhookTradingView Alert의 주소 (포맷: http://xx.xx.xx.xx:80)

다음은service코드를 바꾸어 놓았는데, 참고로 쓸 수 있습니다.

#!/usr/bin/python -tt
# -*- coding: UTF-8 -*-

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import json
import logging
import logging.handlers
import os
import re
import shutil
import subprocess
import time
import ssl
ssl._create_default_https_context = ssl._create_unverified_context

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


############################################################
##### You will likely need to change some of the below #####

# log file for this script
log_file = '/root/webhook/VMA/webhook.log'

# Bot api licence
accessKey = ''
secretKey = ''

# HTTP config
log_max_size = 25165824         # 24 MB
log_level = logging.INFO
#log_level = logging.DEBUG      # DEBUG is quite verbose

listen_port = 80

##### You should stop changing things unless you know what you are doing #####
##############################################################################

log = logging.getLogger('log')
log.setLevel(log_level)
log_handler = logging.handlers.RotatingFileHandler(log_file,
                                                   maxBytes=log_max_size,
                                                   backupCount=4)
f = logging.Formatter("%(asctime)s %(filename)s %(levelname)s %(message)s",
                      "%B %d %H:%M:%S")
log_handler.setFormatter(f)
log.addHandler(log_handler)


class webhookReceiver(BaseHTTPRequestHandler):

    def run_it(self, cmd):
        """
            runs a command
        """
        p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)
        log.debug('running:%s' % cmd)
        p.wait()
        if p.returncode != 0:
            log.critical("Non zero exit code:%s executing: %s" % (p.returncode,
                                                                  cmd))
        return p.stdout

    def bot_conmand(self, method, *args):
        """
            send conmand request to bot api
        """
        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'))

    def do_POST(self):
        """
            receives post, handles it
        """
        log.debug('got post')
        message = 'OK'
        self.rfile._sock.settimeout(5)
        data_string = self.rfile.read(int(self.headers['Content-Length']))
        log.info(data_string)
        self.send_response(200)
        self.send_header("Content-type", "text")
        self.send_header("Content-length", str(len(message)))
        self.end_headers()
        self.wfile.write(message)
        log.debug('TV connection should be closed now.')
        #log.info(self.bot_conmand('GetRobotList', -1, -1, -1)) # GetRobotList(offset, length, robotStatus int)Pass -1 to get all
        log.info(self.bot_conmand('CommandRobot', 169788, data_string))  # CommandRobot(robotId int64, cmd string)Send commands to the robot

    def log_message(self, formate, *args):
        """
            disable printing to stdout/stderr for every post
        """
        return


def main():
    """
        the main event.
    """
    try:
        server = HTTPServer(('', listen_port), webhookReceiver)
        log.info('started web server...')
        server.serve_forever()
    except KeyboardInterrupt:
        log.info('ctrl-c pressed, shutting down.')
        server.socket.close()

if __name__ == '__main__':
    main()

FMZ 플랫폼 거래 전략의 구현

위의 모든 설명 통신 구현, 우리의 보트 거래 전략 또한 우리의 수신 신호 프로세스를 수정하기 위해, 그에 따라 처리되어야 합니다.

예를 들어, 초기에 설계된 경고 메시지, 당신은 당신의 선호도와 특정 필요에 따라 재생할 수 있습니다.

코드는 다음과 같습니다. 정보를 얻고 필터링하고, 작업을 수행하고, 끝입니다.

function get_Command() { //Responsible function for interaction, interactively update relevant values in time, users can expand by themselves
     var way = null; //route
     var cmd = GetCommand(); // Get interactive command API
     var cmd_arr = cmd.split(",");

     if (cmd) {
         // Define the route
         if (cmd.indexOf("BUY,1") != -1) {
             way = 1;
         }
         if (cmd.indexOf("SELL,1") != -1) {
             way = 2;
         }
         if (cmd.indexOf("BUY,2") != -1) {
             way = 3;
         }
         if (cmd.indexOf("SELL,2") != -1) {
            way = 4;
         }
         // Branch selection operation
         switch (way) {
             case 1:
                 xxx
                 break;
             case 2:
                 xxx
                 break;
             case 3:
                 xxx
                 break;
             case 4:
                 xxx
                 break;
             default:
                 break;
         }
     }
}

이 기사는 끝났습니다. 도움이 되길 바랍니다.


관련

더 많은