TradingViewWebHook alarm terhubung langsung ke robot FMZ

Penulis:Kebaikan, Dibuat: 2020-08-07 10:44:17, Diperbarui: 2023-10-10 21:09:42

img

Baru-baru ini semakin banyak pengguna TradingView telah menghubungkan sinyal grafik TradingView ke platform FMZ (FMZ.COMUntuk melakukan trading secara otomatis, Anda harus menggunakan sistem trading yang terintegrasi dengan sistem trading yang terintegrasi dengan sistem trading otomatis.TradingViewWebHook.

Solusi sebelumnya:https://www.fmz.com/digest-topic/5533.

Rencana sebelumnya adalah untuk memperluas antarmuka API FMZ Platform untuk mengirim instruksi ke robot. Hari ini, mari kita lihat solusi lain. Biarkan permintaan WebHook alarm TradingView dikirim langsung ke robot platform FMZ, sehingga dapat langsung mengirim instruksi dan memesan transaksi robot.

Kode sumber strategi robot

Strategi ini ditulis dalam Python. Setelah robot dibuat dan mulai menggunakan strategi ini, robot akan membuat thread, yang akan memulai layanan untuk memantau port set. Menunggu permintaan eksternal dan pemrosesan. Ketika saya mengujinya, itu diuji oleh host di server, dan perangkat di mana host terletak harus dapat diakses dari luar. Ketika robot mengeksekusi transaksi, ia menggunakan antarmuka pesanan pasar. selain itu strategi ini juga dapat dimodifikasi untuk menerapkanlimit orderUntuk mudah dimengerti dan disederhanakan, urutan pasar digunakan di sini, sehingga pertukaran harus mendukung urutan pasar.

'''
Request format: http://x.x.x.x:xxxx/data?access_key=xxx&secret_key=yyy&type=buy&amount=0.001
Strategy robot parameters:
- Type: Encrypted string, AccessKey, SecretKey, you can use the low-privileged API KEY of the FMZ platform, or you can generate the KEY yourself.
- Type: string, contract ID, ContractType
- Type: numeric value, port number, Port
'''

import _thread
import json
from http.server import HTTPServer, 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_POST(self):
        try:
            self.send_response(200)
            self.send_header("Content-type", "application/json")
            self.end_headers()
            dictParam = url2Dict(self.path)
            
            # check
            if len(dictParam) == 4 and dictParam["access_key"] == AccessKey and dictParam["secret_key"] == SecretKey:
                del dictParam["access_key"]
                del dictParam["secret_key"]
                Log("Request received", "parameter:", 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 "No futures contract set"
                
                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")
                    exchange.Buy(-1, float(dictParam["amount"]))
                    Log("Holding Position:", exchange.GetPosition())
                elif not isSpot and dictParam["type"] == "short":
                    exchange.SetDirection("sell")
                    exchange.Sell(-1, float(dictParam["amount"]))
                    Log("Holding Position:", exchange.GetPosition())
                elif not isSpot and dictParam["type"] == "cover_long":
                    exchange.SetDirection("closebuy")
                    exchange.Sell(-1, float(dictParam["amount"]))
                    Log("Holding Position:", exchange.GetPosition())
                elif not isSpot and dictParam["type"] == "cover_short":
                    exchange.SetDirection("closesell")
                    exchange.Buy(-1, float(dictParam["amount"]))
                    Log("Holding Position:", exchange.GetPosition())
            
            # Write data response
            self.wfile.write(json.dumps({"state": "ok"}).encode())
        except Exception as e:
            Log("Provider do_POST error, e:", e)


def createServer(host):
    try:
        server = HTTPServer(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():
    # Start a thread
    try:
        _thread.start_new_thread(createServer, (("0.0.0.0", Port), ))         # Test on VPS server        
    except Exception as e:        
        Log("Error message:", e)
        raise Exception("stop")    
    Log("Account asset information:", _C(exchange.GetAccount))
    while True:
        LogStatus(_D())
        Sleep(2000)

Parameter strategi:

img

Permintaan peringatan WebHook TradingView

Pengaturan permintaan alarm adalah:

http://xxx.xxx.xxx.xxx:80/data?access_key=e3809e173e23004821a9bfb6a468e308&secret_key=45a811e0009d91ad21154e79d4074bc6&type=sell&amount=0.1

Sejak TradingView mengirimPOSTpermintaan, layanan pemantauan harus memantauPOSTpermintaan, dan TradingView hanya memungkinkan port 80 untukhttp protocol.

  • xxx.xxx.xxx.xxxadalah alamat IP perangkat dari host di mana robot terletak. isi alamat IP khusus perangkat Anda sendiri, Anda perlu menyadari bahwa hal itu harus dapat diakses dari jaringan eksternal.

  • Peraturanaccess_keydansecret_keydapat dihasilkan sendiri, selamaaccess_keydansecret_keydalamWebHookpermintaan alarm adalah sama dengan yang dikonfigurasi pada parameter robot.

  • Type, arah perdagangan, membeli atau menjual, membuka atau menutup, perhatikan bahwa spot dan berjangka dibedakan. Jika itu berjangka, perhatikan bahwa kode kontrak berjangka harus diatur pada parameter robot, dan objek pertukaran yang dikonfigurasi harus berjangka.

  • amount, jumlah transaksi.

Uji berjalan

PenggunaanwexAppuntuk mensimulasikan tes pasar yang sebenarnya.

img img

Penghentian

Alamat lengkap strategi:https://www.fmz.com/strategy/221850

Peraturanaccess_keydansecret_keydalam skema hanya untuk identifikasi, dan tidak ada jaminan untuk menggunakanhttpDalam aplikasi praktis, pertimbangan keamanan harus ditambahkan danhttpskomunikasi harus digunakan.


Lebih banyak