Loading ...

根据商品期货计划委托工具实现一个短线策略(教学)

Author: 小小梦, Date: 2019-11-25 11:15:23
Tags:

策略相关文章: https://www.fmz.com/bbs-topic/4654 https://www.fmz.com/bbs-topic/4697


/*backtest
start: 2019-03-01 00:00:00
end: 2019-11-23 21:09:00
period: 1m
exchanges: [{"eid":"Futures_CTP","currency":"FUTURES"}]
args: [["_EntrustSymbol","rb2001"],["_StopLossDiffPrice",10],["_StopWinDiffPrice",10],["_BackhandDiffPrice",10],["_IsBackHand",true]]
*/

// 全局变量
var _TaskQueue = []
var ENTRUST = 0
var STOPLOSS = 1
var STOPPROFIT = 2 
var BACKHAND = 3
var dictTaskType = ["委托任务", "止损任务", "止盈任务", "反手任务"]

var q = $.NewTaskQueue()
var p = $.NewPositionManager()
var IsEntrust = false

function closeTask (taskType) {
    for (var i = 0; i < _TaskQueue.length; i++) {
        if (taskType == _TaskQueue[i].taskType) {
            _TaskQueue[i].taskFinished = true
            Log("关闭任务:", dictTaskType[taskType])
        }
    }
}

// 任务处理对象
var oneDayBeginTS = 0
function TaskQueueProcess () {
    // 获取行情
    exchange.SetContractType(_EntrustSymbol)
    var ticker = _C(exchange.GetTicker)
    var records = _C(exchange.GetRecords)
    $.PlotRecords(records, "K")
    var nowTs = new Date().getTime()

    // 寻找每日的第一根bar
    for (var j = records.length - 1; j > -1; j--) {
        var ts = records[j].Time
        if (ts % (1000 * 60 * 60 * 24) == 3600000) {    // 60 * 60 * 1000
            if (oneDayBeginTS != ts) {
                oneDayBeginTS = ts
                Log("新的一天开始!")
                // 清空任务队列
                IsEntrust = false 
            }
            break
        }
    }

    // 检测收盘,重置
    if (nowTs + 1000 * 60 > oneDayBeginTS + 1000 * 60 * 60 * 6) {
        p.CoverAll()
        _TaskQueue = []
    }

    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)
            }
        }
    }

    // 计算ATR 
    var records_Day = _C(exchange.GetRecords, PERIOD_D1)
    if (records_Day.length <= 5) {
        LogStatus("收集K线")
        Sleep(2000)
        return 
    }
    var atr = TA.ATR(records_Day, 5)
    var _Dis = atr[atr.length - 2] * 0.5
    
    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,          // 大于触发              
            taskFinished : false
        }    

        Log("请注意,创建委托任务", task, "#FF0000")
        _TaskQueue.push(task)
        IsEntrust = true
    }

    for (var i = 0; i < _TaskQueue.length; i++) {
        var task = _TaskQueue[i]
        if (task.taskFinished == false && task.taskType == ENTRUST && task.taskTrigger * ticker.Last >= task.taskTrigger * task.taskPrice) {
            q.pushTask(exchange, task.taskSymbol, task.taskDirection, task.taskAmount, function(tradeTask, ret) {
                Log(tradeTask.desc, ret, "委托完成")
                if (ret) {
                    // 回调,创建后续任务
                    if (task.taskPrice != -1) {     // 创建止损任务
                        var newTask = {
                            taskType : STOPLOSS,
                            taskSymbol : task.taskSymbol,
                            taskPrice : task.taskDirection == "buy" ? task.taskPrice - _StopLossDiffPrice : task.taskPrice + _StopLossDiffPrice, 
                            taskAmount : task.taskAmount,
                            taskDirection : task.taskDirection == "buy" ? "closebuy" : "closesell",                    
                            taskTrigger : task.taskDirection == "buy" ? -1 : 1,              // -1低于 价格触发
                            taskFinished : false
                        }
                        _TaskQueue.push(newTask)
                        Log("创建止损任务", newTask, "#FF0000")
                    }
                    if (task.taskPrice != -1) {   // 创建止盈任务
                        var newTask = {
                            taskType : STOPPROFIT,
                            taskSymbol : task.taskSymbol,
                            taskPrice : task.taskDirection == "buy" ? task.taskPrice + _StopWinDiffPrice : task.taskPrice - _StopWinDiffPrice, 
                            taskAmount : task.taskAmount,
                            taskDirection : task.taskDirection == "buy" ? "closebuy" : "closesell",                    
                            taskTrigger : task.taskDirection == "buy" ? 1 : -1,               // 1高于 价格触发
                            taskFinished : false
                        }
                        _TaskQueue.push(newTask)
                        Log("创建止盈任务", newTask, "#FF0000")
                    }
                }
            })
            task.taskFinished = true
            break        
        } else if (task.taskFinished == false && task.taskType == STOPLOSS && ticker.Last * task.taskTrigger >= task.taskPrice * task.taskTrigger) {    
            q.pushTask(exchange, task.taskSymbol, task.taskDirection, task.taskAmount, function(tradeTask, ret) {
                Log(tradeTask.desc, ret, "止损完成")
                // 关闭止盈任务
                closeTask(STOPPROFIT)
                if (ret) {
                    // 回调,创建后续任务
                    if (task.taskPrice != -1 && _IsBackHand) {
                        var newTask = {
                            taskType : BACKHAND,
                            taskSymbol : task.taskSymbol,
                            taskPrice : task.taskDirection == "closebuy" ? task.taskPrice - _BackhandDiffPrice : task.taskPrice + _BackhandDiffPrice, 
                            taskAmount : task.taskAmount,
                            taskDirection : task.taskDirection == "closebuy" ? "sell" : "buy",                    
                            taskTrigger : task.taskDirection == "closebuy" ? -1 : 1,   // -1 小于时触发, 1大于时触发
                            taskFinished : false
                        }
                        _TaskQueue.push(newTask)
                        Log("创建反手任务", newTask, "#FF0000")
                    }
                }
            })
            task.taskFinished = true
            break
        } else if (task.taskFinished == false && task.taskType == STOPPROFIT && ticker.Last * task.taskTrigger >= task.taskPrice * task.taskTrigger) {    
            q.pushTask(exchange, task.taskSymbol, task.taskDirection, task.taskAmount, function(tradeTask, ret) {
                Log(tradeTask.desc, ret, "止盈完成")
                // 关闭止损任务
                closeTask(STOPLOSS)
            })
            task.taskFinished = true
            break
        } else if (task.taskFinished == false && task.taskType == BACKHAND && ticker.Last * task.taskTrigger >= task.taskPrice * task.taskTrigger) {    
            q.pushTask(exchange, task.taskSymbol, task.taskDirection, task.taskAmount, function(tradeTask, ret) {
                Log(tradeTask.desc, ret, "反手完成")
            })
            task.taskFinished = true
            break
        }
    }
    q.poll()
}

function main() {
    while (true) {
        if (exchange.IO("status")) {
            TaskQueueProcess()
            // 状态栏显示
            LogStatus(_D(), "已连接")
        } else {
            LogStatus(_D(), "未连接")
        }
        Sleep(500)
    }
}




More