TradingViewWebHook 직결 정책

저자:작은 꿈, 2020-08-03 09:58:19
태그:

관련 기사:https://www.fmz.com/bbs-topic/5969

HTTPS서버 자체에는 몇 가지 문제점이 있기 때문에, 대신 THREADINGHTTPSERVER를 사용하는 것을 고려하십시오. 참고:https://docs.python.org/3.7/library/http.server.htmlPython 3.7 버전이 필요합니다.

HTTPServer 문제에 대한 정보:https://www.zybuluo.com/JunQiu/note/1350528


'''
请求格式:http://x.x.x.x:xxxx/data?access_key=xxx&secret_key=yyy&type=buy&amount=0.001
策略机器人参数:
- 类型:加密字符串,AccessKey , SecretKey ,可以用FMZ平台的低权限的API KEY,或者自己生成KEY也可以。
- 类型:字符串,合约ID,ContractType
- 类型:数值,端口号,Port
'''

import re
import _thread
import json
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
from urllib.parse import parse_qs, urlparse

def url2Dict(url):
    query = urlparse(url).query  
    params = parse_qs(query)  
    result = {key: params[key][0] for key in params}  
    return result

class Executor(BaseHTTPRequestHandler):
    def do_GET(self):
        try:
            dictParam = url2Dict(self.path)
            Log("测试", dictParam)
        except Exception as e:
            Log("Provider do_GET error, e:", e)
    def do_POST(self):
        try:
            self.send_response(200)
            self.send_header("Content-type", "application/json")
            self.end_headers()
            dictParam = url2Dict(self.path)
            
            # 测试POST请求Body信息            
            data = self.rfile.read(200)   # 指定了读取长度
            Log("data:", data)            # 打印POST请求的数据,可以根据请求中的数据具体再让机器人执行对应的操作
            
            # 校验
            if len(dictParam) == 4 and dictParam["access_key"] == AccessKey and dictParam["secret_key"] == SecretKey:
                del dictParam["access_key"]
                del dictParam["secret_key"]
                Log("接收到请求", "参数:", dictParam, "#FF0000")
                '''
                map[access_key:xxx amount:0.001 secret_key:yyy type:buy]
                '''
                isSpot = True
                if exchange.GetName().find("Futures") != -1:
                    if ContractType != "":
                        exchange.SetContractType(ContractType)
                        isSpot = False 
                    else :
                        raise "未设置期货合约"
                                
                q = None
                if exchange.GetName() == "Futures_CTP" and UseMarketOrderForCTP == False:
                    q = ext.NewTaskQueue()
                
                if isSpot and dictParam["type"] == "buy":
                    exchange.Buy(-1, float(dictParam["amount"]))
                    Log(exchange.GetAccount())
                elif isSpot and dictParam["type"] == "sell":
                    exchange.Sell(-1, float(dictParam["amount"]))
                    Log(exchange.GetAccount())
                elif not isSpot and dictParam["type"] == "long":
                    exchange.SetDirection("buy")
                    if not q:
                        exchange.Buy(-1, float(dictParam["amount"]))
                    else :
                        q.pushTask(exchange, ContractType, "buy", float(dictParam["amount"]), lambda task, ret: Log(task["desc"], ret, "#FF0000"))
                    Log("持仓:", exchange.GetPosition())
                elif not isSpot and dictParam["type"] == "short":
                    exchange.SetDirection("sell")
                    if not q:
                        exchange.Sell(-1, float(dictParam["amount"]))
                    else :
                        q.pushTask(exchange, ContractType, "sell", float(dictParam["amount"]), lambda task, ret: Log(task["desc"], ret, "#FF0000"))
                    Log("持仓:", exchange.GetPosition())
                elif not isSpot and dictParam["type"] == "cover_long":
                    exchange.SetDirection("closebuy")
                    if not q:
                        exchange.Sell(-1, float(dictParam["amount"]))
                    else :
                        q.pushTask(exchange, ContractType, "closebuy", float(dictParam["amount"]), lambda task, ret: Log(task["desc"], ret, "#FF0000"))
                    Log("持仓:", exchange.GetPosition())
                elif not isSpot and dictParam["type"] == "cover_short":
                    exchange.SetDirection("closesell")
                    if not q:
                        exchange.Buy(-1, float(dictParam["amount"]))
                    else :
                        q.pushTask(exchange, ContractType, "closesell", float(dictParam["amount"]), lambda task, ret: Log(task["desc"], ret, "#FF0000"))
                    Log("持仓:", exchange.GetPosition())
                
                if q is not None:
                    while q.size() > 0:
                        q.poll()
                        Sleep(500)
            
            # 处理body数据
            if isDealBodyMsg:
                if exchange.GetName().find("Futures") != -1:
                    Log("data:", data.decode('utf-8'))  # 测试
                    if re.search(r'buy', data.decode('utf-8')):
                        Log("触发buy")
                        exchange.SetContractType(ct)
                        exchange.SetDirection("buy")
                        exchange.Buy(-1, amount)
                    elif re.search(r'sell', data.decode('utf-8')):
                        Log("触发sell")
                        exchange.SetContractType(ct)
                        exchange.SetDirection("sell")
                        exchange.Sell(-1, amount)
            
            # 写入数据应答
            self.wfile.write(json.dumps({"state": "ok"}).encode())
        except Exception as e:
            Log("Provider do_POST error, e:", e)


def createServer(host):
    try:
        server = ThreadingHTTPServer(host, Executor)
        Log("Starting server, listen at: %s:%s" % host)
        server.serve_forever()
    except Exception as e:
        Log("createServer error, e:", e)
        raise Exception("stop")

def main():
    # 开启一个线程
    try:
        _thread.start_new_thread(createServer, (("0.0.0.0", Port), ))         # VPS服务器上测试           
    except Exception as e:        
        Log("错误信息:", e)
        raise Exception("stop")    
    if exchange.GetName().find("Futures") != -1:
        exchange.SetContractType(ContractType)
    Log("账户资产信息:", _C(exchange.GetAccount))
    while True:
        if exchange.GetName() == "Futures_CTP":
            if exchange.IO("status"):
                LogStatus(_D(), "CTP连接")
            else:
                LogStatus(_D(), "CTP未连接")
        else:
            LogStatus(_D())
        Sleep(2000)

더 많은

eth8888/upload/asset/2457669d9c32568732cb7.jpg 디스크를 열면 이 오류가 나타납니다.

eth8888/upload/asset/2457669d9c32568732cb7.jpg 디스크를 열면 이 오류가 나타납니다.

화산의 검선생님: 微信을 넣을 수 있나요?

화산의 검2021/11/21 11:53:33 CMD 199866 buy=0.1, 관리자가 이 메시지를 받았지만 로봇은 아무런 동작도 하지 않았습니다.

수퍼온V:maybeyeah. V:maybeyeah. V:maybeyeah. V:maybeyeah.

제1TV 신호의 전체적인 예제를 작성할 수 있고, 어떻게 'body'에 있는 정보를 얻을 수 있는가?

다이어트 퀀트선생님, 어떻게 하면 이중화폐를 더할 수 있을까요?

꿈은 8자리입니다.오케이, OKv5 모형판을 만들 수 있나요?

ssxxx선생님, 3.7 버전은 관리자 버전인가요? 어떻게 업데이트할 수 있나요? 2021-08-11 11:08:55 오류 트레이스백 (most recent call last): 파일 "", line 999, in __init_ctx__ 파일 "", line 4, in ImportError: cannot import name 'ThreadingHTTPServer' 2021-08-11 11:08:55 정보 상품 선물 거래 클래식 라이브러리 로딩 성공 2021-08-11 11:08:55 정보 사용 중인 호스트의 python 컴파일 환경의 python 버전은 3.5입니다.

qq3390214355한밤중에 봤는데 이해가 안되는데, 어떻게 연락할 수 있는지 다시 써주실 수 있나요?

첸나센선생님 안녕하세요, TV에서 직접 경고 거래 방향에 대한 전략 웹 주소는 어떻게 쓰나요? 감사합니다.

란브좋아요, 감사합니다 선생님, 제가 테스트해 보겠습니다!

란브선생님, 안녕하세요, 계약에 대한 코드를 좀 더 자세히 설명해 주시겠습니까?

작은 꿈FMZ API 문서는 마지막으로 OKEX 스위치 모형 디스크의 함수를 가지고 있다.

wbe3- 작은 튀김TV 신호를 수신하는 전략, 어떻게 아날로그 디스크를 전환합니까?

작은 꿈오류는 python에 관련된 모듈이 없기 때문입니다.

키986이 문제를 해결하지 않았나요?

eth8888이 문제를 해결했습니다.

작은 꿈TV를 감청할 수 있는 서비스를 만드는 것은 권장하지 않습니다. FMZ의 확장 API를 사용하세요.

작은 꿈이 전략은 상품 선물의 예로, 디지털 화폐를 실행하려면 계약 코드를 설정해야 합니다.

작은 꿈이 전략의 예는 직결된 것으로, 전략 로봇이 TV로부터 신호 요청을 듣기 위해 서비스를 구축하는 것입니다. `` # POST을 테스트합니다. data = self.rfile.read ((200) # 읽기 길이를 지정합니다 Log (("data:", data) # POST 요청의 데이터를 인쇄하여 요청의 데이터에 따라 로봇이 해당 작업을 수행하도록 할 수 있습니다. `` 이 코드는 이미 코드에 언급되어 있습니다. 여기 TV의 요청을 처리하는 body 정보입니다.

작은 꿈이 모든 것은 그들의 필요에 따라 전략을 수정하는 것입니다.

작은 꿈FMZ에서 OKEX 모형 디스크를 구성하는 API KEY, 그리고 코드에 `` ` 교환을 추가하면, IO (simulate, true) ` ` 교환이 완료됩니다.

작은 꿈이 글은 한글로 번역되어 있습니다.

첸나센감사합니다, 만약 제 웹후크 주소가 거래 방향이 구매라고 적혀있다면, 하지만 tv 전략 경보의 팁은 판매하는 것입니다.

작은 꿈https://www.fmz.com/bbs-topic/5969 기사와 전략에는 예가 있습니다.

작은 꿈https://www.fmz.com/api#exchange.setcontracttype... 함수 설명에 있습니다.

PY008계약 코드란 무엇입니까?

작은 꿈이 모든 것은 매우 무례합니다.

작은 꿈만약 거래소와 계약을 하고 있다면 TV의 웹후크 주소를 이렇게 적어주세요. 다른 계약: `` http://x.x.x.x:xxxx/data?access_key=xxx&secret_key=yyy&type=long&amount=1 `` 이 모든 것은 단지 하나의 계약에 불과합니다. `` http://x.x.x.x:xxxx/data?access_key=xxx&secret_key=yyy&type=cover_long&amount=1 `` 이 문서는 이 문장의 문장과 같은 문장입니다.