Chiến lược trọng tài xuyên giai đoạn của tiền kỹ thuật số dựa trên Bollinger Band

Tác giả:Lydia., Tạo: 2022-12-02 16:58:27, Cập nhật: 2023-09-20 09:33:29

img

Chiến lược trọng tài xuyên giai đoạn của tiền kỹ thuật số dựa trên Bollinger Band

I. Tóm lại

George Soros đã đưa ra một đề xuất quan trọng trong The Alchemy of Finance viết năm 1987: Tôi tin rằng giá thị trường luôn luôn sai trong ý nghĩa là chúng trình bày một cái nhìn thiên vị về tương lai. Giả thuyết hiệu quả thị trường chỉ là một giả thuyết lý thuyết. Trên thực tế, những người tham gia thị trường không phải lúc nào cũng hợp lý, và tại mỗi thời điểm, những người tham gia không thể hoàn toàn có được và giải thích khách quan tất cả thông tin. Hơn nữa, ngay cả khi đó là cùng một thông tin, phản hồi của mọi người cũng khác nhau. nghĩa là, giá tự nó đã chứa những kỳ vọng sai của những người tham gia thị trường, vì vậy về bản chất, giá thị trường luôn luôn sai. Đây có thể là nguồn lợi nhuận của các nhà điều khoản.

II. Nguyên tắc chiến lược

Theo các nguyên tắc trên, chúng ta có thể biết rằng trong một thị trường tương lai không hiệu quả, lý do tại sao tác động của thị trường đối với các hợp đồng giao hàng trong các giai đoạn khác nhau không phải lúc nào cũng đồng bộ và giá cả không hoàn toàn hiệu quả. Sau đó, dựa trên giá hợp đồng giao hàng của cùng một đối tượng giao dịch trong các giai đoạn khác nhau, nếu có sự khác biệt giá lớn giữa hai giá, chúng ta có thể mua và bán hợp đồng tương lai trong các giai đoạn khác nhau cùng một lúc để điều chỉnh chéo. Giống như hợp đồng tương lai hàng hóa, tiền kỹ thuật số cũng có danh mục hợp đồng điều chỉnh chéo. Ví dụ, trong sàn giao dịch OKEX, có: ETC tuần hiện tại, ETC tuần tới, ETC quý. Ví dụ, giả sử rằng chênh lệch giá giữa tuần hiện tại của ETC và quý của ETC vẫn ở khoảng 5 trong một thời gian dài. Nếu chênh lệch giá đạt 7 một ngày, chúng ta mong đợi rằng chênh lệch giá sẽ trở lại 5 trong tương lai. Sau đó chúng ta có thể bán ETC trong tuần đó và mua quý ETC cùng một lúc để giảm chênh lệch giá, ngược lại. Mặc dù chênh lệch giá này tồn tại, nhưng có nhiều sự không chắc chắn trong điều chỉnh thủ công do các hoạt động thủ công tốn thời gian, độ chính xác kém và tác động của thay đổi giá. Sự quyến rũ của điều chỉnh định lượng nằm trong việc nắm bắt các cơ hội điều chỉnh thông qua các mô hình định lượng và xây dựng các chiến lược giao dịch điều chỉnh, cũng như đặt lệnh giao dịch tự động cho sàn giao dịch thông qua các thuật toán được lập trình, để nắm bắt các cơ hội nhanh chóng và chính xác và kiếm lợi nhuận hiệu quả và ổn định.

III. Lý thuyết chiến lược

Bài viết này sẽ dạy bạn cách sử dụng Nền tảng giao dịch FMZ Quant và hợp đồng tương lai ETC trong sàn giao dịch OKEX để chứng minh cách nắm bắt các cơ hội điều chỉnh ngay lập tức, nắm bắt lợi nhuận có thể nhìn thấy mọi lúc và phòng ngừa rủi ro có thể gặp phải trong giao dịch tiền kỹ thuật số với một chiến lược điều chỉnh đơn giản.

Tạo ra một chiến lược điều chỉnh chéo giai đoạn cho tiền kỹ thuật số

Khó khăn: bình thường

Môi trường chiến lược

  • Đối tượng giao dịch: Ether Classic (ETC)
  • Dữ liệu chênh lệch: ETC tuần hiện tại - ETC quý (trừ bỏ thử nghiệm hợp nhất)
  • Thời gian giao dịch: 5 phút
  • Phù hợp vị trí: 1:1
  • Loại giao dịch: giai đoạn chéo cùng loại

Chiến lược logic

  • Điều kiện để mở các vị trí với đi dài chênh lệch giá: nếu tài khoản vãng lai không có vị trí và chênh lệch giá nhỏ hơn giới hạn dưới của boll, sau đó đi dài chênh lệch giá. nghĩa là mua các vị trí mở ETC cho tuần, bán các vị trí mở ETC cho quý.
  • Điều kiện để mở các vị trí với đi ngắn chênh lệch giá: nếu không có vị trí trong tài khoản vãng lai, và chênh lệch giá lớn hơn giới hạn trên của boll, sau đó đi ngắn chênh lệch giá. nghĩa là bán các vị trí mở ETC cho tuần, mua các vị trí mở ETC cho quý.
  • Điều kiện đóng các vị trí với đi dài sự khác biệt giá: nếu tài khoản vãng lai giữ các lệnh ETC dài trong tuần hiện tại và giữ các lệnh ngắn ETC quý, và sự khác biệt giá lớn hơn giới hạn giữa của boll, sau đó đóng dài sự khác biệt giá. nghĩa là bán các vị trí đóng ETC cho tuần, mua các vị trí đóng ETC cho quý.
  • Các điều kiện để đóng các vị trí với đi ngắn chênh lệch giá: nếu tài khoản vãng lai giữ lệnh ngắn ETC trong tuần hiện tại, và giữ lệnh dài ETC quý, và chênh lệch giá nhỏ hơn giới hạn giữa của boll, sau đó đóng ngắn chênh lệch giá. nghĩa là, mua các vị trí đóng ETC cho tuần, bán các vị trí đóng ETC cho quý.

IV. Viết một khuôn khổ chiến lược

Điều trên là một mô tả logic đơn giản về chiến lược điều khoản giao dịch xuyên giai đoạn của tiền kỹ thuật số.

function Data() {}  // Basic data function
Data.prototype.mp = function () {}  // Position function
Data.prototype.boll = function () {}  // Indicator function
Data.prototype.trade = function () {}  // Order placement function
Data.prototype.cancelOrders = function () {}  // Order withdrawal function
Data.prototype.isEven = function () {}  // Processing single contract function
Data.prototype.drawingChart = function () {}  // Drawing function

// Trading conditions
function onTick() {
    var data = new Data(tradeTypeA, tradeTypeB);  // Create a basic data object
    var accountStocks = data.accountData.Stocks;  // Account balance
    var boll = data.boll(dataLength, timeCycle);  // Calculate the technical indicators of boll
    data.trade();  // Calculate trading conditions to place an order
    data.cancelOrders();  // Cancel orders
    data.drawingChart(boll);  // drawing
    data.isEven();  // Processing of holding individual contract
}

//Entry function
function main() {
    while (true) {  // Enter the polling mode
        onTick();  // Execute onTick function
        Sleep(500);  // Sleep for 0.5 seconds
    }
}

V. Chiến lược viết

Khung chiến lược có thể dễ dàng được thiết lập theo ý tưởng chiến lược và quá trình giao dịch. Xử lý trước trước giao dịch. Nhận và tính toán dữ liệu. Đặt đơn đặt hàng và xử lý nó sau. Tiếp theo, chúng ta cần phải điền mã chi tiết cần thiết trong khuôn khổ chiến lược theo quy trình giao dịch thực tế và chi tiết giao dịch.

Xử lý trước trước giao dịch Bước 1: Xác định các biến toàn cầu cần thiết trong phạm vi toàn cầu.

//Declare a chart object for the configuration chart
var chart = { }

//Call Chart function and initialize the chart
var ObjChart = Chart ( chart )

//Declare an empty array to store price difference series
var bars = [ ]

//Declare a record history data timestamp variable
var oldTime = 0

Bước 2: Thiết lập các thông số bên ngoài của chiến lược.

// parameters
var tradeTypeA = "this_week"; // Arbitrage A Contract
var tradeTypeB = "quarter"; // Arbitrage B Contract
var dataLength = 10; //Indicator period length
var timeCycle = 1; // K-line period
var name = "ETC"; // Currencies
var unit = 1; // Order quantity

Bước 3: Xác định chức năng xử lý dữ liệu Chức năng dữ liệu cơ bản: Dữ liệu ((() Tạo một constructor, Dữ liệu, và xác định thuộc tính nội bộ của nó. bao gồm: dữ liệu tài khoản, dữ liệu vị trí, dấu thời gian dữ liệu K-line, giá mua / bán của hợp đồng A / B và chênh lệch giá arbitrage dương / âm.

// Basic data
function Data(tradeTypeA, tradeTypeB) { // Pass in arbitrage A contract and arbitrage B contract
    this.accountData = _C(exchange.GetAccount); // Get account information
    this.positionData = _C(exchange.GetPosition); // Get position information
    var recordsData = _C(exchange.GetRecords); // Get K-line data
    exchange.SetContractType(tradeTypeA); // Subscription arbitrage A contract
    var depthDataA = _C(exchange.GetDepth); // Depth data of arbitrage A contract
    exchange.SetContractType(tradeTypeB); // Subscription arbitrage B contract
    var depthDataB = _C(exchange.GetDepth); // Depth data of arbitrage B contract
    this.time = recordsData[recordsData.length - 1].Time; // Time of obtaining the latest data
    this.askA = depthDataA.Asks[0].Price; // Sell one price of Arbitrage A contract
    this.bidA = depthDataA.Bids[0].Price; // Buy one price of Arbitrage A contract
    this.askB = depthDataB.Asks[0].Price; // Sell one price of Arbitrage B contract
    this.bidB = depthDataB.Bids[0].Price; // Buy one price of Arbitrage B contract
    // Positive arbitrage price differences (Sell one price of contract A - Buy one price of contract B)
    this.basb = depthDataA.Asks[0].Price - depthDataB.Bids[0].Price;
    // Negative arbitrage price differences (Buy one price of contract A - Sell one price of contract B)
    this.sabb = depthDataA.Bids[0].Price - depthDataB.Asks[0].Price;
}

Nhận chức năng vị trí: mp ()) Đi qua toàn bộ mảng vị trí và trả về số lượng vị trí của hợp đồng và hướng được chỉ định. Nếu không, trả về false

// Get positions
Data.prototype.mp = function (tradeType, type) {
    var positionData = this.positionData; // Get position information
    for (var i = 0; i < positionData.length; i++) {
        if (positionData[i].ContractType == tradeType) {
            if (positionData[i].Type == type) {
                if (positionData[i].Amount > 0) {
                    return positionData[i].Amount;
                }
            }
        }
    }
    return false;
}

K-line và chức năng chỉ số: boll() Một chuỗi K-line mới được tổng hợp theo dữ liệu chênh lệch giá arbitrage dương / chênh lệch giá arbitrage âm. Dữ liệu theo dõi trên, theo dõi giữa và theo dõi dưới được tính bằng chỉ số boll được trả về.

// Synthesis of new K-line data and boll indicator data
Data.prototype.boll = function (num, timeCycle) {
    var self = {}; // Temporary objects
    // Median value of positive arbitrage price difference and negative arbitrage price difference
    self.Close = (this.basb + this.sabb) / 2;
    if (this.timeA == this.timeB) {
        self.Time = this.time;
    } // Compare two depth data timestamps
    if (this.time - oldTime > timeCycle * 60000) {
        bars.push(self);
        oldTime = this.time;
    } // Pass in the price difference data object into the K-line array according to the specified time period
    if (bars.length > num * 2) {
        bars.shift(); // Control the length of the K-line array
    } else {
        return;
    }
    var boll = TA.BOLL(bars, num, 2); // Call the boll indicator in the talib library
    return {
        up: boll[0][boll[0].length - 1], // boll indicator upper track
        middle: boll[1][boll[1].length - 1], // boll indicator middle track
        down: boll[2][boll[2].length - 1] // boll indicator down track
    } // Return a processed boll indicator data
}

Chức năng giao dịch: giao dịch Đưa tên hợp đồng lệnh và loại lệnh, sau đó đặt lệnh với phần thưởng, và trả lại kết quả sau khi đặt lệnh.

// place the order
Data.prototype.trade = function (tradeType, type) {
    exchange.SetContractType(tradeType); // Resubscribe to a contract before placing an order
    var askPrice, bidPrice;
    if (tradeType == tradeTypeA) { // If the order is placed in contract A
        askPrice = this.askA; // set askPrice
        bidPrice = this.bidA; // set bidPrice
    } else if (tradeType == tradeTypeB) { // If the order is placed in contract B
        askPrice = this.askB; // set askPrice
        bidPrice = this.bidB; // set bidPrice
    }
    switch (type) { // Match order placement mode
        case "buy":
            exchange.SetDirection(type); // Set order placement mode
            return exchange.Buy(askPrice, unit);
        case "sell":
            exchange.SetDirection(type); // Set order placement mode
            return exchange.Sell(bidPrice, unit);
        case "closebuy":
            exchange.SetDirection(type); // Set order placement mode
            return exchange.Sell(bidPrice, unit);
        case "closesell":
            exchange.SetDirection(type); // Set order placement mode
            return exchange.Buy(askPrice, unit);
        default:
            return false;
    }
}

Hủy lệnh Chức năng: hủy lệnh() Ngoài ra, giả được trả về nếu có một đơn đặt hàng chưa hoàn thành, và đúng được trả về nếu không có đơn đặt hàng chưa hoàn thành.

// Cancel order
Data.prototype.cancelOrders = function () {
    Sleep(500); // Delay before cancellation, because some exchanges, you know what I mean
    var orders = _C(exchange.GetOrders); // Get an array of unfilled orders
    if (orders.length > 0) { // If there are unfilled orders
        for (var i = 0; i < orders.length; i++) { //Iterate through the array of unfilled orders
            exchange.CancelOrder(orders[i].Id); //Cancel unfilled orders one by one
            Sleep(500); //Delay 0.5 seconds
        }
        return false; // Return false if an unfilled order is cancelled
    }
    return true; // Return true if there are no unfilled orders
}

Khai thác giữ một hợp đồng duy nhất: isEven() Trong trường hợp một bước trong giao dịch trọng tài, chúng tôi sẽ chỉ đơn giản là đóng tất cả các vị trí.

// Handle holding a single contract
Data.prototype.isEven = function () {
    var positionData = this.positionData; // Get position information
    var type = null; // Switch position direction
    // If the remaining 2 of the position array length is not equal to 0 or the position array length is not equal to 2
    if (positionData.length % 2 != 0 || positionData.length != 2) {
        for (var i = 0; i < positionData.length; i++) { // Iterate through the position array
            if (positionData[i].Type == 0) { // If it is a long order
                type = 10; // Set order parameters
            } else if (positionData[i].Type == 1) { // If it is a short order
                type = -10; // Set order parameters
            }
            // Close all positions
            this.trade(positionData[i].ContractType, type, positionData[i].Amount);
        }
    }
}

Chức năng vẽ: vẽBản đồ ()) Gọi phương pháp ObjChart Add (), vẽ dữ liệu thị trường và dữ liệu chỉ số cần thiết trong biểu đồ: đường dẫn trên, đường dẫn giữa, đường dẫn dưới, chênh lệch giá chênh lệch dương / âm.

// Drawing
Data.prototype.drawingChart = function (boll) {
    var nowTime = new Date().getTime();
    ObjChart.add([0, [nowTime, boll.up]]);
    ObjChart.add([1, [nowTime, boll.middle]]);
    ObjChart.add([2, [nowTime, boll.down]]);
    ObjChart.add([3, [nowTime, this.basb]]);
    ObjChart.add([4, [nowTime, this.sabb]]);
    ObjChart.update(chart);
}

Bước 4: Trong hàm nhập main ((), thực hiện mã xử lý trước giao dịch, chỉ chạy một lần sau khi chương trình được khởi động, bao gồm:

  • SetErrorFilter (()) để lọc thông tin không quan trọng trong bảng điều khiển
  • exchange.IO ( https://www.squadhelp.com/name/exchange.io?lp=d) ()) để thiết lập đồng tiền kỹ thuật số được giao dịch
  • ObjChart reset ( ) để xóa biểu đồ trước được vẽ trước khi bắt đầu chương trình
  • LogProfitReset (()) để xóa thông tin thanh trạng thái trước khi bắt đầu chương trình
//entry function
function main() {
    // Filter the unimportant information in the console
    SetErrorFilter("429|GetRecords:|GetOrders:|GetDepth:|GetAccount|:Buy|Sell|timeout|Futures_OP");
    exchange.IO("currency", name + '_USDT'); //Set the digital currency to be traded
    ObjChart.reset(); // Clear the previous chart drawn before starting the program
    LogProfitReset(); // Clear the status bar information before starting the program
}

Sau khi xác định quá trình xử lý trước giao dịch ở trên, bước tiếp theo là nhập chế độ thăm dò và thực hiện hàm onTick ()) nhiều lần. Nó cũng thiết lập thời gian ngủ cho thăm dò Sleep (), bởi vì API của một số sàn giao dịch tiền kỹ thuật số có giới hạn truy cập tích hợp trong một khoảng thời gian nhất định.

//entry function
function main() {
    // Filter the unimportant information in the console
    SetErrorFilter("429|GetRecords:|GetOrders:|GetDepth:|GetAccount|:Buy|Sell|timeout|Futures_OP");
    exchange.IO("currency", name + '_USDT'); //Set the digital currency to be traded
    ObjChart.reset(); //Clear the previous chart drawn before starting the program
    LogProfitReset(); //Clear the status bar information before starting the program
    while (true) { // Enter the polling mode
        onTick(); // Execute onTick function
        Sleep(500); // Sleep for 0.5 seconds
    }
}

Nhận và tính toán dữ liệu Bước 1: Nhận đối tượng dữ liệu cơ bản, số dư tài khoản và dữ liệu chỉ số boll để sử dụng trong logic giao dịch.

// Trading conditions
function onTick() {
    var data = new Data(tradeTypeA, tradeTypeB); // Create a basic data object
    var accountStocks = data.accountData.Stocks; // Account balance
    var boll = data.boll(dataLength, timeCycle); // Get boll indicator data
    if (!boll) return; // Return if there is no boll data
}

Đặt đơn đặt hàng và xử lý theo dõi Bước 1: Thực hiện giao dịch mua và bán theo logic chiến lược trên. Đầu tiên, đánh giá xem các điều kiện giá và chỉ số có hợp lệ hay không, sau đó đánh giá xem các điều kiện vị trí có hợp lệ hay không và cuối cùng thực hiện chức năng lệnh giao dịch ()

// Trading conditions
function onTick() {
    var data = new Data(tradeTypeA, tradeTypeB); // Create a basic data object
    var accountStocks = data.accountData.Stocks; // Account balance
    var boll = data.boll(dataLength, timeCycle); // Get boll indicator data
    if (!boll) return; // Return if there is no boll data
    // Explanation of the price difference
    // basb = (Sell one price of contract A - Buy one price of contract B)
    // sabb = (Buy one price of contract A - Sell one price of contract B)
    if (data.sabb > boll.middle && data.sabb < boll.up) { // If sabb is higher than the middle track
        if (data.mp(tradeTypeA, 0)) { // Check whether contract A has long orders before placing an order
            data.trade(tradeTypeA, "closebuy"); // Contract A closes long position
        }
        if (data.mp(tradeTypeB, 1)) { // Check whether contract B has short orders before placing an order
            data.trade(tradeTypeB, "closesell"); // Contract B closes short position
        }
    } else if (data.basb < boll.middle && data.basb > boll.down) { // If basb is lower than the middle track
        if (data.mp(tradeTypeA, 1)) { // Check whether contract A has short orders before placing an order
            data.trade(tradeTypeA, "closesell"); // Contract A closes short position
        }
        if (data.mp(tradeTypeB, 0)) { // Check whether contract B has long orders before placing an order
            data.trade(tradeTypeB, "closebuy"); // Contract B closes long position
        }
    }
    if (accountStocks * Math.max(data.askA, data.askB) > 1) { // If there is balance in the account
        if (data.basb < boll.down) { // If basb price difference is lower than the down track
            if (!data.mp(tradeTypeA, 0)) { // Check whether contract A has long orders before placing an order
                data.trade(tradeTypeA, "buy"); // Contract A opens long position
            }
            if (!data.mp(tradeTypeB, 1)) { // Check whether contract B has short orders before placing an order
                data.trade(tradeTypeB, "sell"); // Contract B opens short position
            }
        } else if (data.sabb > boll.up) { // If sabb price difference is higher than the upper track
            if (!data.mp(tradeTypeA, 1)) { // Check whether contract A has short orders before placing an order
                data.trade(tradeTypeA, "sell"); // Contract A opens short position
            }
            if (!data.mp(tradeTypeB, 0)) { // Check whether contract B has long orders before placing an order
                data.trade(tradeTypeB, "buy"); // Contract B opens long position
            }
        }
    }
}

Bước 2: Sau khi đặt lệnh, cần phải giải quyết các tình huống bất thường như lệnh chưa được giải quyết và giữ một hợp đồng duy nhất.

// Trading conditions
function onTick() {
    var data = new Data(tradeTypeA, tradeTypeB); // Create a basic data object
    var accountStocks = data.accountData.Stocks; // Account balance
    var boll = data.boll(dataLength, timeCycle); // Get boll indicator data
    if (!boll) return; // Return if there is no boll data
    // Explanation of the price difference
    //basb = (Sell one price of contract A - Buy one price of contract B)
    // sabb = (Buy one price of contract A - Sell one price of contract B)
    if (data.sabb > boll.middle && data.sabb < boll.up) { // If sabb is higher than the middle track
        if (data.mp(tradeTypeA, 0)) { // Check whether contract A has long orders before placing an order
            data.trade(tradeTypeA, "closebuy"); // Contract A closes long position
        }
        if (data.mp(tradeTypeB, 1)) { // Check whether contract B has short orders before placing an order
            data.trade(tradeTypeB, "closesell"); // Contract B closes short position
        }
    } else if (data.basb < boll.middle && data.basb > boll.down) { // If basb is lower than the middle track
        if (data.mp(tradeTypeA, 1)) { // Check whether contract A has short orders before placing an order
            data.trade(tradeTypeA, "closesell"); // Contract A closes short position
        }
        if (data.mp(tradeTypeB, 0)) { // Check whether contract B has long orders before placing an order
            data.trade(tradeTypeB, "closebuy"); // Contract B closes long position
        }
    }
    if (accountStocks * Math.max(data.askA, data.askB) > 1) { // If there is balance in the account
        if (data.basb < boll.down) { // If basb price difference is lower than the down track
            if (!data.mp(tradeTypeA, 0)) { // Check whether contract A has long orders before placing an order
                data.trade(tradeTypeA, "buy"); // Contract A opens long position
            }
            if (!data.mp(tradeTypeB, 1)) { // Check whether contract B has short orders before placing an order
                data.trade(tradeTypeB, "sell"); // Contract B opens short position
            }
        } else if (data.sabb > boll.up) { // If sabb price difference is higher than the upper track
            if (!data.mp(tradeTypeA, 1)) { // Check whether contract A has short orders before placing an order
                data.trade(tradeTypeA, "sell"); // Contract A opens short position
            }
            if (!data.mp(tradeTypeB, 0)) { // Check whether contract B has long orders before placing an order
                data.trade(tradeTypeB, "buy"); // Contract B opens long position
            }
        }
    }
    data.cancelOrders(); // cancel orders
    data.drawingChart(boll); // drawing
    data.isEven(); // Handle holding individual contracts
}

VI. Chiến lược hoàn chỉnh

Như ở trên, chúng tôi đã tạo ra một chiến lược giao dịch đơn giản của tiền kỹ thuật số hoàn toàn thông qua hơn 200 dòng mã.

// Global variable
// Declare a chart object for the configuration chart
var chart = {
    __isStock: true,
    tooltip: {
        xDateFormat: '%Y-%m-%d %H:%M:%S, %A'
    },
    title: {
        text: 'transaction profit and loss curve (detailed)'
    },
    rangeSelector: {
        buttons: [{
            type: 'hour',
            count: 1,
            text: '1h'
        }, {
            type: 'hour',
            count: 2,
            text: '3h'
        }, {
            type: 'hour',
            count: 8,
            text: '8h'
        }, {
            type: 'all',
            text: 'All'
        }],
        selected: 0,
        inputEnabled: false
    },
    xAxis: {
        type: 'datetime'
    },
    yAxis: {
        title: {
            text: 'price difference'
        },
        opposite: false,
    },
    series: [{
        name: "upper track",
        id: "line1,up",
        data: []
    }, {
        name: "middle track",
        id: "line2,middle",
        data: []
    }, {
        name: "down track",
        id: "line3,down",
        data: []
    }, {
        name: "basb",
        id: "line4,basb",
        data: []
    }, {
        name: "sabb",
        id: "line5,sabb",
        data: []
    }]
};
var ObjChart = Chart(chart); // Drawing object
var bars = []; // Storage price difference series
var oldTime = 0; // Record historical data timestamp

// parameters
var tradeTypeA = "this_week"; // Arbitrage A contract
var tradeTypeB = "quarter"; // Arbitrage B contract
var dataLength = 10; //Indicator period length
var timeCycle = 1; // K-line period
var name = "ETC"; // Currencies
var unit = 1; // Order quantity

// basic data
function Data(tradeTypeA, tradeTypeB) { // Pass in arbitrage A contract and arbitrage B contract
    this.accountData = _C(exchange.GetAccount); // Get account information
    this.positionData = _C(exchange.GetPosition); // Get position information
    var recordsData = _C(exchange.GetRecords); //Get K-line data
    exchange.SetContractType(tradeTypeA); // Subscribe to arbitrage A contract
    var depthDataA = _C(exchange.GetDepth); // Arbitrage A contract depth data
    exchange.SetContractType(tradeTypeB); // Subscribe to arbitrage B contract
    var depthDataB = _C(exchange.GetDepth); // Arbitrage B contract depth data
    this.time = recordsData[recordsData.length - 1].Time; // Time to get the latest data
    this.askA = depthDataA.Asks[0].Price; // Sell one price of arbitrage A contract
    this.bidA = depthDataA.Bids[0].Price; // Buy one price of arbitrage A contract
    this.askB = depthDataB.Asks[0].Price; // Sell one price of arbitrage B contract
    this.bidB = depthDataB.Bids[0].Price; // Buy one price of arbitrage B contract
    // Positive arbitrage price difference (Sell one price of contract A - Buy one price of contract B)
    this.basb = depthDataA.Asks[0].Price - depthDataB.Bids[0].Price;
    // Negative arbitrage price difference (Buy one price of contract A - Sell one price of contract B)
    this.sabb = depthDataA.Bids[0].Price - depthDataB.Asks[0].Price;
}

// Get position
Data.prototype.mp = function (tradeType, type) {
    var positionData = this.positionData; // Get position information
    for (var i = 0; i < positionData.length; i++) {
        if (positionData[i].ContractType == tradeType) {
            if (positionData[i].Type == type) {
                if (positionData[i].Amount > 0) {
                    return positionData[i].Amount;
                }
            }
        }
    }
    return false;
}

// Synthesis of new K-line data and boll indicator data
Data.prototype.boll = function (num, timeCycle) {
    var self = {}; // Temporary objects
    // Median value of between positive arbitrage price difference and negative arbitrage price difference
    self.Close = (this.basb + this.sabb) / 2;
    if (this.timeA == this.timeB) {
        self.Time = this.time;
    } // Compare two depth data timestamps
    if (this.time - oldTime > timeCycle * 60000) {
        bars.push(self);
        oldTime = this.time;
    } // Pass in the price difference data object into the K-line array according to the specified time period
    if (bars.length > num * 2) {
        bars.shift(); // Control the length of the K-line array
    } else {
        return;
    }
    var boll = TA.BOLL(bars, num, 2); // Call the boll indicator in the talib library
    return {
        up: boll[0][boll[0].length - 1], // boll indicator upper track
        middle: boll[1][boll[1].length - 1], // boll indicator middle track
        down: boll[2][boll[2].length - 1] // boll indicator down track
    } // Return a processed boll indicator data
}

// Place an order
Data.prototype.trade = function (tradeType, type) {
    exchange.SetContractType(tradeType); // Resubscribe to a contract before placing an order
    var askPrice, bidPrice;
    if (tradeType == tradeTypeA) { // If the order is placed in contract A
        askPrice = this.askA; // Set askPrice
        bidPrice = this.bidA; // Set bidPrice
    } else if (tradeType == tradeTypeB) { // If the order is placed in contract B
        askPrice = this.askB; // Set askPrice
        bidPrice = this.bidB; // Set bidPrice
    }
    switch (type) { // Match order placement mode
        case "buy":
            exchange.SetDirection(type); // Set order placement mode
            return exchange.Buy(askPrice, unit);
        case "sell":
            exchange.SetDirection(type); // Set order placement mode
            return exchange.Sell(bidPrice, unit);
        case "closebuy":
            exchange.SetDirection(type); // Set order placement mode
            return exchange.Sell(bidPrice, unit);
        case "closesell":
            exchange.SetDirection(type); // Set order placement mode
            return exchange.Buy(askPrice, unit);
        default:
            return false;
    }
}

// Cancel orders
Data.prototype.cancelOrders = function () {
    Sleep(500); // Delay before cancellation, because some exchanges, you know what I mean
    var orders = _C(exchange.GetOrders); //Get an array of unfilled orders
    if (orders.length > 0) { // If there are unfilled orders
        for (var i = 0; i < orders.length; i++) { //Iterate through the array of unfilled orders
            exchange.CancelOrder(orders[i].Id); //Cancel unfilled orders one by one
            Sleep(500); //Sleep for 0.5 seconds
        }
        return false; // Return false if an unfilled order is cancelled
    }
    return true; //Return true if there are no unfilled orders
}

// Handle holding individual contracts
Data.prototype.isEven = function () {
    var positionData = this.positionData; // Get position information
    var type = null; // Switch position direction
    // If the remaining 2 of the position array length is not equal to 0 or the position array length is not equal to 2
    if (positionData.length % 2 != 0 || positionData.length != 2) {
        for (var i = 0; i < positionData.length; i++) { // Iterate through the position array
            if (positionData[i].Type == 0) { // If it is a long order
                type = 10; // Set order parameters
            } else if (positionData[i].Type == 1) { // If it is a short order
                type = -10; // Set order parameters
            }
            // Close all positions
            this.trade(positionData[i].ContractType, type, positionData[i].Amount);
        }
    }
}

// Drawing
Data.prototype.drawingChart = function (boll) {
    var nowTime = new Date().getTime();
    ObjChart.add([0, [nowTime, boll.up]]);
    ObjChart.add([1, [nowTime, boll.middle]]);
    ObjChart.add([2, [nowTime, boll.down]]);
    ObjChart.add([3, [nowTime, this.basb]]);
    ObjChart.add([4, [nowTime, this.sabb]]);
    ObjChart.update(chart);
}

// Trading conditions
function onTick() {
    var data = new Data(tradeTypeA, tradeTypeB); // Create a basic data object
    var accountStocks = data.accountData.Stocks; // Account balance
    var boll = data.boll(dataLength, timeCycle); // Get boll indicator data
    if (!boll) return; // Return if there is no boll data
    // Explanation of price difference
    // basb = (Sell one price of contract A - Buy one price of contract B)
    // sabb = (Buy one price of contract A - Sell one price of contract B)
    if (data.sabb > boll.middle && data.sabb < boll.up) { // If sabb is higher than the middle track
        if (data.mp(tradeTypeA, 0)) { // Check whether contract A has long orders before placing an order
            data.trade(tradeTypeA, "closebuy"); // Contract A closes long position
        }
        if (data.mp(tradeTypeB, 1)) { // Check whether contract B has short orders before placing an order
            data.trade(tradeTypeB, "closesell"); // Contract B closes short position
        }
    } else if (data.basb < boll.middle && data.basb > boll.down) { // If basb is lower than the middle track
        if (data.mp(tradeTypeA, 1)) { // Check whether contract A has short orders before placing an order
            data.trade(tradeTypeA, "closesell"); // Contract A closes short position
        }
        if (data.mp(tradeTypeB, 0)) { // Check whether contract B has long orders before placing an order
            data.trade(tradeTypeB, "closebuy"); // Contract B closes long position
        }
    }
    if (accountStocks * Math.max(data.askA, data.askB) > 1) { // If there is a balance in the account
        if (data.basb < boll.down) { // If basb price difference is lower than the down track
            if (!data.mp(tradeTypeA, 0)) { // Check whether contract A has long orders before placing an order
                data.trade(tradeTypeA, "buy"); // Contract A opens long position
            }
            if (!data.mp(tradeTypeB, 1)) { // Check whether contract B has short orders before placing an order
                data.trade(tradeTypeB, "sell"); // Contract B opens short position
            }
        } else if (data.sabb > boll.up) { // If sabb price difference is higher than the upper track
            if (!data.mp(tradeTypeA, 1)) { // Check whether contract A has short orders before placing an order
                data.trade(tradeTypeA, "sell"); // Contract A opens short position
            }
            if (!data.mp(tradeTypeB, 0)) { // Check whether contract B has long orders before placing an order
                data.trade(tradeTypeB, "buy"); // Contract B opens long position
            }
        }
    }
    data.cancelOrders(); // Cancel orders
    data.drawingChart(boll); // Drawing
    data.isEven(); // Handle holding individual contracts
}

//Entry function
function main() {
    // Filter unimportant information in the console
    SetErrorFilter("429|GetRecords:|GetOrders:|GetDepth:|GetAccount|:Buy|Sell|timeout|Futures_OP");
    exchange.IO("currency", name + '_USDT'); //Set the digital currency to be traded
    ObjChart.reset(); //Clear the previous chart drawn before starting the program
    LogProfitReset(); //Clear the status bar information before starting the program
    while (true) { // Enter polling mode
        onTick(); // Execute the onTick function
        Sleep(500); // Sleep for 0.5 seconds
    }
}

Địa chỉ chiến lược:https://www.fmz.com/strategy/104964

VII. Tóm tắt

Chiến lược trong bài viết này chỉ là một ví dụ. Bot thực sự không đơn giản, nhưng bạn có thể làm theo ví dụ và sử dụng trí tưởng tượng hoang dã của riêng bạn. Lý do là bất kể thị trường tương lai trao đổi tiền kỹ thuật số nào, biên của nó không phải là tiền pháp lý. Hiện nay, hầu hết các loại tiền kỹ thuật số đã giảm khoảng 70% kể từ đầu năm. Đó là nói rằng chiến lược luôn là kiếm tiền, nhưng giá tiền đang giảm. Nhìn chung, thị trường tiền kỹ thuật số dường như đã tách khỏi blockchain. Giống như hoa tulip lúc đó, giá luôn xuất phát từ kỳ vọng và niềm tin của mọi người, và niềm tin xuất phát từ giá...


Có liên quan

Thêm nữa