Hand in hand to teach you how to transform "commodity futures Plan Commission tool" into a one-day strategy

Keywords: Blockchain less

In the last article, we learned How to write a commodity futures plan entrustment tool , this is a semi manual trading strategy. So how can we implement an automatic plan delegation strategy? In this issue, let's implement and transform this tool into an automatic trading strategy.

 

Strategic thinking

Similarly, the mechanism of automatically generating stop loss, stop gain and backhand entrustment tasks after an order is entrusted is used. Only the first entrustment order is triggered by the deviation degree between the 1-minute level average and the current price. The regression strategy is used to close the position before closing. The strategy is not complicated.

 

Strategy implementation details

Data preparation in policy polling logic

// Market quotation
exchange.SetContractType(_EntrustSymbol)    // Set the contract. For example, set the parameter "EntrustSymbol" to rb2001
var ticker = _C(exchange.GetTicker)         // Get tick data
var records = _C(exchange.GetRecords)       // Obtain the K-line data. Set the K-line period to 1 minute. Here, obtain the K-line data of 1 minute period
$.PlotRecords(records, "K")                 // Draw a K line
var nowTs = new Date().getTime()            // Get the current time, timestamp.

Get the data for later calculation.

 

It is necessary to calculate the average line after opening every morning. First, it is necessary to determine the time stamp of the first K-line in the current unit of day

for (var j = records.length - 1; j > -1; j--) {
    var ts = records[j].Time
    if (ts % (1000 * 60 * 60 * 24) == 3600000) {    // 60 * 60 * 1000 = 3600000
        if (oneDayBeginTS != ts) {
            oneDayBeginTS = ts
            Log("A new day begins!")
            // Clear task queue
            IsEntrust = false // This is a global variable flag set to mark whether the delegation has been triggered at present. It is reset at the beginning of the new day
        }
        break
    }
}

This code is to traverse the K-line data in reverse order, and judge the first K-line bar that conforms to ts% (1000 * 60 * 60 * 24) = = 3600000. ts is the time stamp of the K-line, and ts and 1000 * 60 * 60 * 24 are used to find out how many milliseconds have passed in a day. When this value is equal to 3600000, it is judged as the start of the new opening time, because it is opening at 9:00 in the morning, 60 * 60 * 1000 = 3600000, when the time passes 3600000 milliseconds (1 hour), it is exactly 9:00 Beijing time. To get the time stamp of the first K-line bar opened every day: oneDayBeginTS = ts

 

Then calculate the mean line:

var sum = 0
var count = 0
var avg = 0
for (var n = 0 ; n < records.length; n++) {
    if (records[n].Time >= oneDayBeginTS) {
        sum += records[n].Close
        count++
        if (n == records.length - 1) {
            avg = sum / count
            $.PlotLine("avg", avg, records[n].Time)   # Draw the moving average.
        }
    }
}

 

Calculate ATR

Using the 5-day ATR index as a reference for the degree of deviation, first calculate the ATR:

var records_Day = _C(exchange.GetRecords, PERIOD_D1)   // Get the daily K-line
if (records_Day.length <= 5) {   // The number of K lines must meet the ATR cycle, otherwise it will return directly.
    LogStatus("collect K Line")
    Sleep(2000)
    return 
}
var atr = TA.ATR(records_Day, 5)         // Calculate ATR index
var _Dis = atr[atr.length - 2] * 0.5     // Obtain the ATR index value of the previous BAR, which can be multiplied by a coefficient as the adjustment

 

Close before closing

if (nowTs + 1000 * 60 > oneDayBeginTS + 1000 * 60 * 60 * 6) {
    p.CoverAll()
    _TaskQueue = []
}

The opening time of oneDayBeginTS + 1000 * 60 * 60 * 69:00 will be 6 hours later, i.e. 15:00, and nowTs + 1000 * 60 will be one minute ahead of schedule. When the conditions of nowTs + 1000 * 60 > onedaybegints + 1000 * 60 * 60 * 6 are met, i.e. the closing time is less than 1 minute, the closing will be started. Proud of the powerful function of the commodity futures trading library, you can directly call the full flat function p.CoverAll() to close all positions. If you are not familiar with commodity futures trading class library, you can see the class library code. The code is open source.

 

Trigger delegation conditions

if (Math.abs(records[records.length - 1].Close - avg) > _Dis && !IsEntrust) {
    var task = {
        taskType : ENTRUST,
        taskSymbol : _EntrustSymbol,
        taskPrice : records[records.length - 1].Close, 
        taskAmount : _EntrustAmount,
        taskDirection : records[records.length - 1].Close - avg > 0 ? "sell" : "buy",
        taskTrigger : records[records.length - 1].Close - avg > 0 ? 1 : -1,          // Greater than trigger              
        taskFinished : false
    }    

    Log("Notice that you create a delegate task", task, "#FF0000")
    _TaskQueue.push(task)
    IsEntrust = true
}

As you can see, it's similar to the way the delegate task code was created in the previous article. The condition math.abs (records [records. Length - 1]. Close - AVG) >.
If the delegated task triggers execution, it will automatically create some columns of stop gain, stop loss and backhand tasks as in the previous article.

 

Back test test

Back test configuration:

 

Back test results:

Back test log:

The return from back testing is not very high, but the transaction frequency is relatively high. If there is a refund of handling fees, it may be considered.
Strategies are teaching strategies, ideas are only for reference, it is worth learning a few small details, such as time control.

Policy address: https://www.fmz.com/strategy/176022

Posted by skiingguru1611 on Mon, 24 Feb 2020 02:31:25 -0800