گرڈ ٹریڈنگ کی حکمت عملی

مصنف:نیکی, تخلیق: 2018-08-23 13:45:27, تازہ کاری:

اور نقصان" floatProfit، سب سے زیادہ منافع نقطہ:، منافعMax، شروع سٹاپ نقصان) ؛ // آؤٹ پٹ کی معلومات balanceAccount ((orgAccount، InitAccount) ؛ // توازن اکاؤنٹ if (StopLossMode == 0) { // سٹاپ نقصان موڈ پروسیسنگ کے مطابق، اگر سٹاپ نقصان موڈ 0 کے برابر ہے تو، پروگرام سٹاپ نقصان کے بعد باہر نکل جاتا ہے. Stop loss exit پھینک؛ // غلطی Stop Loss Exit حکمت عملی کو روکنے کے لئے پھینک. } دیگر { واپس سچ؛ // سٹاپ نقصان کے باہر نکلنے کے موڈ کے علاوہ، یعنی: سٹاپ نقصان کے بعد گرڈ دوبارہ کاسٹ. } } } if (EnableAccountCheck && EnableStopWin) { // اگر پتہ لگانے کا اکاؤنٹ آن ہے اور منافع لینے کو آن کیا گیا ہے if (floatProfit > StopWin) { // اگر فلوٹنگ منافع اور نقصان منافع لینے سے بڑا ہے لاگ ((موجودہ فلوٹنگ منافع اور نقصان, floatProfit, حاصل کرنے کا آغاز); // آؤٹ پٹ لاگ balanceAccount ((orgAccount، InitAccount) ؛ // بیلنسڈ اکاؤنٹ وصولی ابتدائی (منافع لیں) if (StopWinMode == 0) { // منافع لینے کے موڈ کے مطابق. پھینک فائدہ نکالیں؛ // منافع نکالنے کے بعد باہر نکلیں } دیگر { واپس سچ؛ // واپس سچ منافع لینے کے بعد، گرڈ کاسٹ کرنے کے لئے جاری } } } var distance = 0؛ // فاصلے کو ریکارڈ کرنے کے لئے ایک متغیر کا اعلان کریں if (EnableAccountCheck && AutoMove) { // اگر اکاؤنٹ کا پتہ لگانے کو آن کیا گیا ہے اور گرڈ خود بخود منتقل ہوتا ہے if (BuyFirst) { // اگر یہ ہے پہلے خریدنے اور پھر فروخت distance = ticker.Last - FirstPrice; // distance کو ایک قدر تفویض کریں: موجودہ قیمت مائنس پہلی قیمت، فاصلے کا حساب لگائیں } else { // دیگر حالات: پہلے فروخت کریں اور پھر خریدیں distance = FirstPrice - ticker.Last؛ // فاصلے کو ایک قدر تفویض کریں: پہلی قیمت مائنس موجودہ قیمت، فاصلے کا حساب لگائیں } var refish = false؛ // ٹیگ متغیر دوبارہ کاسٹ کرنے کے لئے کہ آیا if (!isHold && isTimeout()) { // اگر کوئی پوزیشن نہیں ہے (isHold غلط ہے) اور ٹائم آؤٹ (isTimeout true لوٹاتا ہے) لاگ ((کوئی پوزیشن بہت طویل عرصے تک منعقد نہیں، گرڈ منتقل کرنے کے لئے شروع) ؛
refish = true؛ // مارک دوبارہ کاسٹ } if (distance > MaxDistance) { // اگر موجودہ فاصلہ انٹرفیس پیرامیٹرز کے ذریعہ مقرر کردہ زیادہ سے زیادہ فاصلے سے زیادہ ہے تو ، نشان دوبارہ ڈال دیا جاتا ہے لاگ (("قیمت گرڈ وقفہ سے باہر بہت زیادہ ہے، گرڈ منتقل کرنے کے لئے شروع، موجودہ فاصلے: "، _N(فاصلہ، صحت سے متعلق) ، موجودہ قیمت:، ticker.Last) ؛ ریفش = سچ } if (refish) { // if refish is true، توازن فنکشن کو انجام دیں بیلنساکاؤنٹ ((orgاکاؤنٹ، InitAccount) ؛ true لوٹاتا ہے؛ // یہ کاسٹ فنکشن true لوٹاتا ہے } }

        var holdDirection, holdAmount = "--",                                       // Declare three variables, position direction, number of positions, position price
            holdPrice = "--";
        if (isHold) {                                                               // When holding a position
            if (RestoreProfit && ProfitAsOrg) {                                     // If you start to restore the last profit and the last profit is included in the average price
                if (BuyFirst) {                                                     // If it is buy first and then sell 
                    money_diff += LastProfit;                                       // Add the last profit to money_diff, that is, the last time the income is converted into the money difference
                                                                                    // (in the case of the first buy, the money difference is negative, that is, the cost), 
                                                                                    // which is equivalent to the opening cost.
                } else {                                                            // If it is sell first, then buy
                    money_diff -= LastProfit;                                       // The difference between buying and selling is positive, why - ?
                }
            }

            // Dealing with buying first and then selling
            holdAmount = amount_diff;                                               // The difference in the value of the coins is given to the number of
                                                                                    // positions (the difference in the coins is the position at the moment)
            holdPrice = (-money_diff) / amount_diff;                                // Calculate the average price of the position by dividing the difference between
                                                                                    // the money and the difference in the coins, 
                                                                                    // Note: If money_diff is negative, then amount_diff must be positive, so be sure 
                                                                                    // to add a minus sign before money_diff so that the calculated price is a positive number.
            // Dealing with selling first and then buying
            if (!BuyFirst) {                                                        // If it is selling first and then buying, it will trigger the update of the open position and 
                                                                                    // the average price of the position.
                holdAmount = -amount_diff;                                          // The coins difference is negative, so the counter is reversed
                holdPrice = (money_diff) / -amount_diff;                            // Calculate the average price of the position.
            }
            holdAmount = _N(holdAmount, 4);                                         // Positions, retain 4 decimal places.
            holdPrice = _N(holdPrice, Precision);                                   // The average price of the position, retaining the Precision decimal.
            holdDirection = BuyFirst ? "long" : "short";                            // According to the "first buy then sell" or "first sell then buy" to holdDirection assigned long or short
        } else {                                                                    // If isHold is false, assign "--" to holdDirection
            holdDirection = "--";
        }
        table = {                                                                   // Assign an object to the declared table variable to display the table information on the FMZ robot status bar
            type: 'table',                                                          // See the API documentation LogStatus function, here to initialize the type attribute 'table' for
                                                                                    // display in the status bar as a table
            title: 'Operating status',                                              // Title of the table
            cols: ['Use funds', 'Holding position', 'Position size', 'Average price of position', 'Total floating profit and loss', 'Current grid profit and loss', 
                   'Number of casting grids', 'Grid offset', 'Real placing order', 'Latest coin price'],   // The column name of the table
            rows: [                                                                                                                   // Progressive data for the table
                [_N(actualNeedMondy, 4), holdDirection, holdAmount, holdPrice, _N(floatProfitAll, 4) + ' ( ' + _N(floatProfitAll * 100 / actualNeedMondy, 4) + ' % )',
                 floatProfit, fishCount, (AutoMove && distance > 0) ? ((BuyFirst ? "up" : "down") + "Deviation: " + _N(distance) + " dollar") : "--", trader.RealLen(), ticker.Last]
                // One row of data
            ]
        };
        
    }                                                                               // Process some tasks every 5 seconds and update the robot status bar table object table 
    
    var orders = _C(trader.GetOrders);                                              // Get all unexecuted orders
    if (table) {                                                                    // If the table has been assigned a table object
        if (!EnableDynamic) {                                                       // If the dynamic order is not activated
            table.rows[0][8] = orders.length;                                       // Update the length of the pending order array in the first row and the 9th column of the status bar table.
        }
        LogStatus('`' + JSON.stringify(table) + '`');                               // Call the FMZ platform API LogStatus to display the status bar table of the settings
    }
    for (var idx = 0; idx < canNum; idx++) {                                        // Traverse the number of available grids nodes.
        var openPrice = _N((BuyFirst ? FirstPrice - (idx * PriceGrid) : FirstPrice + (idx * PriceGrid)), Precision);        // As the node index idx traverses, construct the opening price
                                                                                                                            // of each node (the direction is buying first, then sold, 
                                                                                                                            // or selling first and then buy) 
        var coverPrice = _N((BuyFirst ? openPrice + PriceDiff : openPrice - PriceDiff), Precision);     // Open and close position spread, that is, the profit margin of each node
        var state = fishTable[idx];                                                                     // Assignment status of the fishnet node
        var fishId = uuidTable[idx];                                                                    // Numbering
        
        // The judgment here is: filtering unfinished orders
        if (hasOrder(orders, fishId)) {                                                                 // If all unexecuted orders, there is an order with the ID fishId in the pending order array
            continue;                                                                                   // Skip this loop and continue the loop
        }

        if (fishId != -1 && IsSupportGetOrder) {                                                        // The grid node id is not equal to the initial value, that is, the order is placed, 
                                                                                                        // and the exchange supports GetOrder
            var order = trader.GetOrder(fishId);                                                        // Get the order for the fishId number
            // The judgment here is as follows: Filter the grid node where the order is not found, the following logic (state == STATE_WAIT_COVER), etc. will not trigger
            if (!order) {                                                                               // Failed to get an order if !order is true 
                Log("Failed to get order information, ID: ", fishId);                                   // Output log
                continue;                                                                               // Skip this loop and continue the loop
            }
            // The judgment here is as follows: Filtering the grid nodes that are in a suspended state, not completed, or not fully completed, 
            // the logic of the following judgment (state == STATE_WAIT_COVER) and so on will not be triggered.
            if (order.Status == ORDER_STATE_PENDING) {                                                  // If the order status is pending on the exchange
                //Log("Order status is not completed, ID: ", fishId);
                continue;                                                                               // Skip this loop and continue to loop
            }
        }

        if (state == STATE_WAIT_COVER) {                                                                // If the current node status is waiting to be closed
            var coverId = CoverFunc(coverPrice, (BuyFirst ? amountS[idx] : amountB[idx]), (BuyFirst ? 'Complete the buying order:' : 'Complete the selling order:'), openPrice, 'volume:',
                                   (BuyFirst ? amountB[idx] : amountS[idx]));
            // Call the closing function CoverFunc to send the closing order

            if (typeof(coverId) === 'number' || typeof(coverId) === 'string') {        // Determine if the value returned by the closing function is a value (returned directly by the FMZ API) 
                                                                                       // or a string (returned by the buy/Sell function of the trader object)
                fishTable[idx] = STATE_WAIT_CLOSE;                                     // The closing order has been send and the update status is: STATE_WAIT_CLOSE Waiting for the node task to complete
                uuidTable[idx] = coverId;                                              // Store the order number in the idx location corresponding to the uuidTable.
            }
        } else if (state == STATE_WAIT_OPEN || state == STATE_WAIT_CLOSE) {            // If the status is waiting for opening or waiting for completion
            var openId = OpenFunc(openPrice, BuyFirst ? amountB[idx] : amountS[idx]);  // Open the position order.
            if (typeof(openId) === 'number' || typeof(openId) === 'string') {          // Determine whether the order placing is successful
                fishTable[idx] = STATE_WAIT_COVER;                                     // Update status for waiting for closing
                uuidTable[idx] = openId;                                               // Record current node order ID
                if (state == STATE_WAIT_CLOSE) {                                       // If it is waiting for completion (it will only be triggered after the open position order is placed)
                    ProfitCount++;                                                     // Cumulative gaining profit times
                    var account = _C(exchange.GetAccount);                             // Get current account information
                    var ticker = _C(exchange.GetTicker);                               // Get current market information
                    var initNet = _N(((InitAccount.Stocks + InitAccount.FrozenStocks) * ticker.Buy) + InitAccount.Balance + InitAccount.FrozenBalance, 8);
                    // Calculate the initial net asset value
                    var nowNet = _N(((account.Stocks + account.FrozenStocks) * ticker.Buy) + account.Balance + account.FrozenBalance, 8);
                    // Calculate the current net asset value
                    var actualProfit = _N(((nowNet - initNet)) * 100 / initNet, 8);    // Calculated rate of return
                    if (AmountType == 0) {                                             // According to the same amount of buy and sell, the custom amount is different.
                        var profit = _N((ProfitCount * amount * PriceDiff) + LastProfit, 8);      // Calculation: the sum of the profit and loss of all profit nodes and the 
                                                                                                  // last time of the net profit and loss which is the total profit and loss
                        Log((BuyFirst ? 'Complete the sell order:' : 'Complete the buy order:'), coverPrice, 'volume:', (BuyFirst ? amountS[idx] : amountB[idx]), 'Closing position profit', profit);
                        // Output order completion information
                    } else {
                        Log((BuyFirst ? 'Complete the sell order:' : 'Complete the buy order:'), coverPrice, 'volume:', (BuyFirst ? amountS[idx] : amountB[idx]));
                    }
                }
            }
        }
    }
    Sleep(CheckInterval);                        // Grid logic is mainly while loop detection, each time a pause is checked, CheckInterval is: detection interval
}
return true;                                     // This time of the casting grid is completed, return true

}

اہم تقریب (main function) { // حکمت عملی کا بنیادی کام، پروگرام یہاں سے شروع ہوتا ہے. اگر (ResetData) { // RestData انٹرفیس پیرامیٹر ہے، تو ڈیفالٹ درست ہے، اور یہ کنٹرول کرتا ہے کہ آیا تمام اعداد و شمار کو اسٹارٹ اپ پر صاف کیا جاتا ہے۔ تمام ڈیفالٹ کی طرف سے صاف ہوتے ہیں۔ LogProfitReset(); // تمام آمدنی کو صاف کرنے کے لئے API لاگ پروفیٹ ری سیٹ فنکشن کو چلائیں. لاگ ری سیٹ ((); // تمام نوشتہ جات کو صاف کرنے کے لئے API لاگ ری سیٹ فنکشن کو چلائیں. } // exchange.SetMaxDigits(Precision) // ختم، اس کی بجائے exchange.SetPrecision استعمال کریں. exchange.SetPrecision(Precision، 3) // exchange.SetPrecision(2, 3؛ // قیمت اعشاریہ جگہ کی درستگی کو 2 ہندسوں پر مقرر کریں، اور مختلف قسم کے آرڈر سائز اعشاریہ جگہ کی درستگی 3 ہندسوں پر ہے. // صحت سے متعلق انٹرفیس پیرامیٹرز.

if (typeof(AmountType) === 'undefined') {        // Order quantity type, 0: "Buy and sell the same amount", 1: "Custom amount", detect if the parameter is undefined, the default setting is 0.
    AmountType = 0;                              // Typeof will detect the type of AmountType. If undefined is "undefined", assign a value of 0 to AmountType.
}
if (typeof(AmountDot) === 'undefined') {         // The maximum number of digits of the order quantity decimal point AmountDot is undefined, set AmountDot to 3.
    AmountDot = 3;                               // In fact, it has been set by exchange.SetPrecision(Precision, 3), and it will be truncated at the bottom.
}
if (typeof(EnableDynamic) === 'undefined') {     // Check if the dynamic pending order parameter is enabled. If EnableDynamic is undefined, set to false will not be enabled.
    EnableDynamic = false;
}
if (typeof(AmountCoefficient) === 'undefined') { // If not defined, the default setting is "*1"
    AmountCoefficient = "*1";
}
if (typeof(EnableAccountCheck) === 'undefined') {// If not defined, the Enable Money Verification parameter is set to true, which is turned on.
    EnableAccountCheck = true;
}
BuyFirst = (OpType == 0);                        // Assign value to BuyFirst according to the setting of OpType, OpType sets the grid type, 0: buy first and then sell, 1: sell first and then buy
IsSupportGetOrder = exchange.GetName().indexOf('itstamp') == -1;    // Check the name of the exchange, whether it is Bitstamp or not
if (!IsSupportGetOrder) {
    Log(exchange.GetName(), "Does not support GetOrder, may affect the stability of the strategy.");
}

SetErrorFilter("502:|503:|S_U_001|unexpected|network|timeout|WSARecv|Connect|GetAddr|no such|reset|http|received|refused|EOF|When");
// SetErrorFilter  Filter error messages 

exchange.SetRate(1); 
Log('Exchange rate conversion has been disabled, the current currency is', exchange.GetBaseCurrency());    // Disable exchange rate conversion

if (!RestoreProfit) {     //  If the last profit is restored to false, then LastProfit will be assigned a value of 0, that is, it will not be restored.
    LastProfit = 0;
}

var orgAccount = _C(exchange.GetAccount);     // Get account information, here record the initial account information when the strategy starts running, 
                                              // used to calculate some income, such as: overall floating profit and loss. 
                                              // There are several parameters in this strategy that are passed to this variable.
var fishCount = 1;                            // time of casting grids initial is 1
while (true) {                                // Strategy main loop
    if (!fishing(orgAccount, fishCount)) {    // casting grid function fishing
        break;
    }
    fishCount++;                              // Number of casting grids accumulated
    Log("the number of", fishCount, "casting girds...");      // Output Casting grids information.
    FirstPriceAuto = true;                    // Reset first price is automatically true
    Sleep(1000);                              // Polling interval 1000 milliseconds
}

}


مزید