Giải thích chi tiết về chiến lược lệnh chờ BitMEX

Tác giả:Tốt, Tạo: 2019-01-16 15:28:13, Cập nhật: 2019-01-22 14:16:48

BitMEX đã trở thành nền tảng được lựa chọn cho giao dịch đòn bẩy tiền điện tử, nhưng các hạn chế giao dịch API của nó rất nghiêm ngặt và khiến các nhà giao dịch tự động cảm thấy rất bối rối.

1. Tính năng của BitMEX

Ưu điểm quan trọng nhất là thanh khoản giao dịch rất tích cực, đặc biệt là hợp đồng vĩnh cửu Bitcoin, số tiền giao dịch mỗi phút thường vượt quá một triệu hoặc thậm chí mười triệu đô la Mỹ; giao dịch lệnh chờ BitMEX có chính sách phí hoa hồng trả lại, mặc dù nó không nhiều, nhưng thu hút một số lượng lớn các giao dịch làm thị trường, làm cho độ sâu giá rất phong phú. giá mua và bán mới nhất thường có hơn một triệu đô la giá trị các lệnh chờ; vì điểm này, giá giao dịch thường dao động xung quanh đơn vị thay đổi tối thiểu là $ 0,50.

2.Biên giới hạn tần số BitMEX API

Tần suất yêu cầu của API REST được giới hạn ở 300 lần mỗi 5 phút, gần như bằng 1 lần mỗi giây, giới hạn này có thể được cho là rất nghiêm ngặt so với các nền tảng giao dịch khác. Sau khi vượt quá giới hạn, Rate limit exceeded sẽ được nhắc. Nếu bạn tiếp tục vượt quá giới hạn, IP có thể bị vô hiệu hóa trong một giờ. Nhiều lần vô hiệu hóa trong một thời gian ngắn sẽ dẫn đến một tuần bị vô hiệu hóa. Đối với mỗi yêu cầu API, BitMEX sẽ trả lại dữ liệu tiêu đề, dữ liệu tiêu đề được sử dụng để xem số lượng yêu cầu còn lại hiện tại. Trên thực tế, nếu API được sử dụng đúng cách, nó sẽ không vượt quá giới hạn tần suất và nói chung không cần phải kiểm tra.

3. Sử dụng websocket để có được báo giá thị trường

BitMEX REST API là hạn chế hơn. khuyến nghị chính thức là sử dụng giao thức websocket nhiều hơn, và đẩy nhiều loại dữ liệu hơn so với trao đổi trung bình. Hãy chú ý đến các điểm sau đây cho việc sử dụng cụ thể:

Nếu thời gian đẩy dữ liệu độ sâu quá dài, sẽ có một lỗi, không tương ứng với độ sâu thực tế. Các chi tiết đặt hàng đẩy là thiếu rất nhiều và hầu như không có sẵn. Có sự chậm trễ đáng kể trong việc đẩy thông tin tài khoản, tốt nhất là sử dụng API REST. Khi thị trường biến động quá lớn, thời gian đẩy sẽ đạt một vài giây. Mã sau sử dụng giao thức websocket để lấy thông tin thị trường và tài khoản trong thời gian thực, chủ yếu cho các chiến lược tạo thị trường.

var ticker  = {price:0, buy:0, sell:0, time:0} //Ticker information, the latest price, "buy one" price, "sell one" price, update time
//Account information, respectively, position, buying and selling price, buying and selling quantity, position status, order Id
var info = {position:0, buyPrice:0, sellPrice:0, buyAmount:0, sellAmount:0, buyState:0, sellState:0, buyId:0, sellId:0}
var buyListId = []//Global variables, pre-emptive buying id list, will described below
var sellListId = []
var APIKEY = 'your api id' //Need to fill in the BitMEX API ID here. Note that it is not a key, which is required for websocket protocol authentication.
var expires = parseInt(Date.now() / 1000) + 10
var signature = exchange.HMAC("sha256", "hex", "GET/realtime" + expires, "{{secretkey}}")//The secretkey will be automatically replaced at the bottom level and does not need to be filled in.
var bitmexClient = Dial("wss://www.bitmex.com/realtime", 60)
var auth = JSON.stringify({args: [APIKEY, expires, signature], op: "authKeyExpires"})//Authentication information, otherwise you cannot subscribe to the account
bitmexClient.write(auth)
bitmexClient.write('{"op": "subscribe", "args": ["position","execution","trade:XBTUSD"]}')//Subscribed to positions, order execution and perpetual contract real-time transaction
while(true){
    var data = bitmexClient.read()
    if(data){
        bitmexData = JSON.parse(data)
        if('table' in bitmexData && bitmexData.table == 'trade'){
            data = bitmexData.data
            ticker.price = parseFloat(data[data.length-1].price)//The latest transaction price, will push multiple transactions at a time, take one will be ok
            //You can get the "buy one" and "sell one" price according to the direction of the latest transaction, without subscribing to the depth.
            if(data[data.length-1].side == 'Buy'){
                ticker.sell = parseFloat(data[data.length-1].price)
                ticker.buy = parseFloat(data[data.length-1].price)-0.5
            }else{
                ticker.buy = parseFloat(data[data.length-1].price)
                ticker.sell = parseFloat(data[data.length-1].price)+0.5
            }
            ticker.time =  new Date(data[data.length-1].timestamp);//Update time, can be used to determine the delay
        }
    }else if(bitmexData.table == 'position'){
        var position = parseInt(bitmexData.data[0].currentQty)  
        if(position != info.position){
            Log('Position change: ', position, info.position, '#FF0000@')//Position change Log, and pushed to WeChat, remove @ means Do not push
            info.position = position  
        }
        info.position  = parseInt(bitmexData.data[0].currentQty)  
    }
}

4. Kỹ năng đặt lệnh

BitMEX chính thức khuyến cáo sử dụng bulk orderingorder modification để đặt hàng. bulk ordering có thể được thực hiện nhanh hơn do kiểm toán thời gian thực của BitMEX, kiểm tra rủi ro, tính toán biên, và khởi động. Do đó, tần suất của bulk ordering được tính là một phần mười tần suất bình thường. Hơn nữa, hoạt động đặt hàng của chúng tôi nên sử dụng phương pháp bulk orderingorder modification để giảm thiểu việc sử dụng API. Tình trạng đặt hàng truy vấn cũng cần tiêu thụ API bằng tần suất. Nó có thể đánh giá tình trạng đặt hàng theo vị trí thay đổi hoặc thay đổi lệnh thất bại.

đơn đặt hàng hàng loạt không giới hạn số lượng đặt hàng (không thể quá nhiều), trên thực tế, một đơn đặt hàng cũng có thể sử dụng giao diện đơn đặt hàng hàng loạt. Do hoạt động sửa đổi đơn đặt hàng, chúng ta có thể đơn đặt hàng trước một số đơn đặt hàng mà giá lệch rất nhiều, các đơn đặt hàng này sẽ không được thực hiện, nhưng khi chúng ta cần đặt đơn đặt hàng, chúng ta chỉ cần sửa đổi giá và số lượng của đơn đặt hàng được đặt. khi sửa đổi đơn đặt hàng xảy ra thất bại, nó cũng có thể được sử dụng như một tín hiệu cho đơn đặt hàng được thực hiện.

Dưới đây là mã thực hiện cụ thể:

// Cancel all orders and reset global variables
function cancelAll(){
    exchange.IO("api","DELETE","/api/v1/order/all","symbol=XBTUSD")//Call IO extension revocation
    info = {position:0, buyPrice:0, sellPrice:0, buyAmount:0, sellAmount:0, buyState:0, sellState:0, buyId:0, sellId:0}
    buyListId = []
    sellListId = []
}
//placing alternate order
function waitOrders(){
    var orders = []
    if(buyListId.length<4){
        //When the number of inspections is insufficient, place another "bulk"
        for(var i=0;i<7;i++){
            //Due to BitMEX restrictions, the price can not be excessively excessive, the order quantity can not be too small, and the "execInst" parameter guarantees that only the market making transaction can be executed.
            orders.push({symbol:'XBTUSD', side:'Buy', orderQty:100, price:ticker.buy-400+i, execInst:'ParticipateDoNotInitiate'})
        }
    }
    if(sellListId.length<4){
        for(var i=0;i<7;i++){
            orders.push({symbol:'XBTUSD', side:'Sell', orderQty:100, price:ticker.buy+400+i, execInst:'ParticipateDoNotInitiate'})
        }
    }
    if(orders.length>0){
        var param = "orders=" + JSON.stringify(orders);
        var ids = exchange.IO("api", "POST", "/api/v1/order/bulk", param);//Bulk orders submitted here
        for(var i=0;i<ids.length;i++){
            if(ids.side == 'Buy'){
                buyListId.push(ids.orderID)
            }else{
                sellListId.push(ids.orderID)
            }
        }
    }
}
//Modify order function
function amendOrders(order, direction, price, amount, id){
    var param = "orders=" + JSON.stringify(order);
    var ret = exchange.IO("api", "PUT", "/api/v1/order/bulk", param);//Modify one order at a time
    //Modification occurs error
    if(!ret){
        var err = GetLastError()
        //overloaded unmodified strategy, need to recycle the order id
        if(err.includes('The system is currently overloaded')){
            if(id){
                if(direction == 'buy'){
                    buyListId.push(id)
                }else{
                    sellListId.push(id)
                }
            }
            Sleep(1000)
            return
        }
        //Illegal order status, indicating that the order to be modified has been completely executed
        else if(err.includes('Invalid ordStatus')){
            Log(order, direction)
            if(direction == 'buy'){
                info.buyId = 0
                info.buyState = 0
                info.buyAmount = 0
                info.buyPrice = 0
            }else{
                info.sellId = 0
                info.sellState = 0
                info.sellAmount = 0
                info.sellPrice = 0
            }
            //Since the push is not timely, update the position with the "rest" protocol here.
            pos = _C(exchange.GetPosition)
            if(pos.length>0){
                info.position = pos[0].Type == 0 ? pos[0].Amount : -pos[0].Amount
            }else{
                info.position = 0
            }
        }
        //Unknown error cannot be modified, all orders are cancelled, reset once
        else if(err.includes('Invalid orderID')){
            cancelAll()
            Log('Invalid orderID,reset once')
        }
        //Exceed the frequency limit, you can continue to try after hibernation
        else if(err.includes('Rate limit exceeded')){
            Sleep(2000)
            return
        }
        //The account is banned, all orders are revoked, and sleep is awaiting recovery for a long time.
        else if(err.includes('403 Forbidden')){
            cancelAll()
            Log('403,reset once')
            Sleep(5*60*1000)
        }
    }else{
        //Modify order successfully
        if(direction == 'buy'){
            info.buyState = 1
            info.buyPrice = price
            info.buyAmount = amount
        }else{
            info.sellState = 1
            info.sellPrice = price
            info.sellAmount = amount
        }
    }
}
//0.5 price change
function fixSize(num){
    if(num>=_N(num,0)+0.75){
        num = _N(num,0)+1
    }else if(num>=_N(num,0)+0.5){
        num=_N(num,0)+0.5
    }else{
        num=_N(num,0)
    }
    return num
}
//Trading function
function trade(){
    waitOrders()//Check if you need a replacement order
    var buyPrice = fixSize(ticker.buy-5) //For demonstration purposes only, specific transactions should be written by yourself.
    var sellPrice = fixSize(ticker.sell+5)
    var buyAmount =  500
    var sellAmount = 500
    //Modify from an alternate order when there is no order
    if(info.buyState == 0  && buyListId.length > 0){
        info.buyId = buyListId.shift()
        amendOrders([{orderID:info.buyId, price:buyPrice, orderQty:buyAmount}],'buy', group, buyPrice, buyAmount, info.buyId)
    }
    if(info.sellState == 0 && sellListId.length > 0){
        info.sellId = sellListId.shift()
        amendOrders([{orderID: info.sellId, price:sellPrice, orderQty:sellAmount}],'sell', group, sellPrice, sellAmount, info.sellId )
    }
    //Existing orders need to change price
    if(buyPrice !=  info.buyPrice && info.buyState == 1){
        amendOrders([{orderID:info.buyId, price:buyPrice, orderQty:buyAmount}],'buy', group, buyPrice, buyAmount)
    }
    if(sellPrice != info.sellPrice && info.sellState == 1){
        amendOrders([{orderID:info.sellId, price:sellPrice, orderQty:sellAmount}],'sell', group, sellPrice, sellAmount)
    }
}

5. Những người khác

Máy chủ của BitMEX nằm trong máy chủ của Amazon ở Dublin, Ireland. Khả năng ping của máy chủ dưới 1ms khi bạn chọn một máy chủ đám mây AWS ở Dublin, nhưng khi vẫn có sự chậm trễ trong việc đẩy, vấn đề quá tải không thể được giải quyết. Ngoài ra, khi tài khoản được đăng nhập, đại lý máy chủ không thể được đặt tại Hoa Kỳ và các nơi khác không cho phép giao dịch tiền điện tử. Do quy định, tài khoản sẽ bị cấm.

Mã trong bài viết này đã được sửa đổi từ chiến lược cá nhân của tôi và không đảm bảo là hoàn toàn chính xác để tham khảo. Việc sử dụng cụ thể mã thị trường nên được thực hiện trong chức năng chính, mã liên quan đến giao dịch được đặt trước chức năng chính và chức năng giao dịch được đặt trong báo giá thị trường đẩy.


Thêm nữa

gmgphilKết nối WS tạo ra lỗi: ReferenceError: ID 'data' không xác định tại...

Cỏ nhỏmột lỗi mã, vấn đề đã được khắc phục