资源加载中... loading...

原始双均线策略

Author: ianzeng123, Date: 2024-07-16 16:30:48
Tags:


/*backtest
start: 2024-01-03 09:00:00
end: 2024-07-16 14:01:00
period: 1h
basePeriod: 15m
exchanges: [{"eid":"Futures_CTP","currency":"FUTURES"}]
args: [["Instruments","SA888"]]
*/


var _q = $.NewTaskQueue();
var openNumber = 0 //开仓次数
var winNumber = 0 //成功次数
var lossNumber = 0 //失败次数
var cumProfit = 0 //累计利润
var cumLoss = 0 //累计损失
var holdSymbol = '' //持仓品种
var holdAmount = 0 //持仓数量
var holdPrice = 0 //持仓价格
var holdProfit = 0 //持仓利润
var holdDir = '' //持仓方向
var winRate = 0 //胜率
var plRatio = 0 //盈亏比
var InitBalance = 0 //未开仓金额


function main(){
    SetErrorFilter("login|ready|流控|连接失败|初始|Timeout");
    
    var pretime = 0
    var checklock = true
    while (true) {
        if(exchange.IO("status")) {
            var symbolDetail = _C(exchange.SetContractType, Instruments)
            var record = exchange.GetRecords()

            var lastPrice = record[record.length - 1].Close
            var shortMean = TA.MA(record, shortPeriod)
            var longMean = TA.MA(record, longPeriod)
            var longSignal = shortMean[shortMean.length - 2] > longMean[longMean.length - 2]
            var shortSignal = shortMean[shortMean.length - 2] < longMean[longMean.length - 2]

            // 检查主力合约
            var DRecords = exchange.GetRecords(PERIOD_D1)
            var curTime = DRecords[DRecords.length - 1].Time
            var mainSymbol = symbolDetail.InstrumentID;

            var curPos = exchange.GetPosition()
            var unit = 5

            if(checklock){
                var initAccount = _q.GetAccount(exchange);
                var initMargin = JSON.parse(exchange.GetRawJSON()).CurrMargin;
                InitBalance = initAccount.Balance + initMargin;
            }

            // 开仓
            if(curPos && curPos.length == 0 && (longSignal || shortSignal)){
                _q.pushTask(exchange, mainSymbol, (longSignal ? "buy" : "sell"), unit, function(task, ret) {
                    if(ret){
                        checklock = false
                        openNumber += 1
                    }
                });
            }

            // 移仓+平仓
            if(curPos && curPos.length > 0){
                holdPrice = curPos[0].Price
                holdAmount = curPos[0].Amount
                holdProfit = (curPos[0].Type % 2) == 0 ? (lastPrice - holdPrice) * holdAmount * symbolDetail.VolumeMultiple : (holdPrice - lastPrice) * holdAmount * symbolDetail.VolumeMultiple
                holdDir = curPos[0].Type % 2 == 0 ? "多" : "空"
                holdSymbol = curPos[0].ContractType


                // 移仓
                var moveSignal = pretime != curTime && holdSymbol != mainSymbol
                
                if (moveSignal) {
                    _q.pushTask(exchange, holdSymbol, "coverall", holdAmount, function(task, ret) {
                        if (ret) {
                            Log(holdSymbol, "移仓平仓成功 #ff0000");
                            pretime = curTime
                            curaddNumber = 0 //本轮加仓次数归零
                            var afterAccount = _q.GetAccount(exchange);
                            var afterMargin = JSON.parse(exchange.GetRawJSON()).CurrMargin;
                            var afterBalance = afterAccount.Balance + afterMargin;

                            var curprofit = afterBalance - InitBalance

                            if(curprofit > 0){
                                cumProfit += curprofit
                                winNumber += 1
                            }else{
                                cumLoss += curprofit
                                lossNumber += 1
                            }

                            curaddNumber = 0
                            holdSymbol = '' 
                            holdAmount = 0 
                            holdPrice = 0 
                            holdProfit = 0 
                            holdDir = '' 
                            openPrice = 0 
                            checklock = true
                        }
                    })
                }

                //平仓
                var coverLongSignal = shortSignal && holdDir == '多'
                var coverShortSignal = longSignal && holdDir == '空'

                if(coverLongSignal || coverShortSignal){
                    _q.pushTask(exchange, mainSymbol, "coverall", 0, function(task, ret) {
                        if(ret){
                            var afterAccount = _q.GetAccount(exchange);
                            var afterMargin = JSON.parse(exchange.GetRawJSON()).CurrMargin;
                            var afterBalance = afterAccount.Balance + afterMargin;

                            var curprofit = afterBalance - InitBalance

                            if(curprofit > 0){
                                cumProfit += curprofit
                                winNumber += 1
                            }else{
                                cumLoss += curprofit
                                lossNumber += 1
                            }
                            curaddNumber = 0
                            holdSymbol = '' 
                            holdAmount = 0 
                            holdPrice = 0 
                            holdProfit = 0 
                            holdDir = '' 
                            checklock = true
                        }
                    })
                }
            }

            var tblStatus = {
                type: "table",
                title: "持仓信息",
                cols: ["合约名称", "持仓方向", "持仓均价", "持仓数量", "持仓盈亏"],
                rows: []
            };


            var tblStrategy = {
                type: "table",
                title: "策略评价",
                cols: ["开仓次数", "成功次数", "累计利润", "失败次数", "累计亏损", "胜率", "盈亏比"],
                rows: []
            };

            if(openNumber){
                winRate = winNumber / openNumber
            }

            winRate = openNumber ? winNumber / openNumber : 0

            if(cumLoss == 0 && cumProfit != 0 ) plRatio = 1
            if(cumLoss != 0 && cumProfit == 0) plRatio = -1
            if(cumProfit && cumLoss) plRatio = cumProfit / cumLoss

            tblStatus.rows.push([holdSymbol, holdDir, holdPrice, holdAmount, holdProfit]);
            tblStrategy.rows.push([openNumber, winNumber, cumProfit, lossNumber, cumLoss, winRate, Math.abs(plRatio)]);
            var now = new Date();

            lastStatus = '`' + JSON.stringify([tblStatus, tblStrategy]) + '`\n' + '`' + ' 当前时间: ' + _D() + ', 星期' + ['日', '一', '二', '三', '四', '五', '六'][now.getDay()] + ", 交易任务: " + _q.size();
            LogStatus(lastStatus);
            _q.poll();

            Sleep(LoopInterval * 1000);


        }

    }


}





    



template: strategy.tpl:40:21: executing "strategy.tpl" at <.api.GetStrategyListByName>: wrong number of args for GetStrategyListByName: want 7 got 6