The resource loading... loading...

It takes you into the world of quantization -- MACD two-way operation, sliding stop-loss code analysis.

Author: Inventors quantify - small dreams, Created: 2016-04-22 13:53:14, Updated: 2023-06-14 10:38:59

It takes you into the world of quantization -- MACD two-way operation, sliding stop-loss code analysis.

In the previous article, we learned about the simplified quantitative strategies for 30 lines of code, and in this article, the author will take the beginners step by step closer to exploring the fun of designing quantitative strategies. The article continues, this time it is still a spot transaction in BTC, the author is completely ignorant of finance, investments, securities, etc.; he doesn't even understand the process of trading futures. It's also a matter of being confused, confused, confused by unknown names and terms, (and it's also a little bit understood! a little bit understood!); filling one's brain with your own Baidu, searching for information etc. After reading the relevant content, I had the basic concepts in mind, combined with my little understanding of the JS language, I wrote a simple one. Initially I did not understand what the K line, the equator, the MACD indicator is. In simple terms, the K-line is a record of market trends over a period of time, which makes it easy to observe market dynamics. The average line is the indicator used in the previous article, and like the MACD indicator, it reflects market trends. These two indicators have different concepts, algorithms, formulae, and so on. For those who do not understand, please check Baidu.

The code has the following global variables, the old rules, first one by one explanation, the old bird can ignore.

Variable name The initial value Explained
Interval 2000 This variable is the round-trip cycle, the amount of time the program pauses to wait, the unit is a millisecond, 1000 milliseconds is 1 second, so the initial value of this variable is 2 seconds.
STATE_FREE 0 This is a state representation variable, which represents the empty space.
STATE_BUY 1 This is a state variable that indicates multi-headed holdings.
STATE_SELL 2 The state variable indicates that the position is empty.
ORDER_INVALID 3 Holding state variable, indicating not holding.
ORDER_VALID 4 It means that the stock is...
state STATE_FREE State variable, initialized with empty state.
SignalDelay 0 Initially planned, the signal was delayed and temporarily useless.
stopProfit 0.002 This variable is more important, the stop loss rate, for example, capital * stop loss rate ((0.002)) indicates a maximum loss of 0.002 times the capital, the loss ceiling.
step 0.5 The step length value of the sliding stop loss. It is used for raising, lowering and grading the stop loss price.
opAmount 1 Fixed operating volume.
profit 0 I'm sorry to hear that.

Global objects, used to record hold information, contain some methods, mainly to achieve sliding stop loss.

    var holdOrder = {//持仓信息对象
	    orderState: ORDER_INVALID,// 持仓状态
	    price: 0, //持仓均价
	    amount: 0, //持仓量
	    time: null, // 操作时间
	    stopPrice: 0, // 止损价
	    level: 1,   //止损等级
	    updateCurrentProfit: function(lastPrice,amount){//更新当前盈亏
	        if(state === STATE_SELL){//当前 空头持仓
	        	return (lastPrice - this.price) * amount;
	        }
	        if(state === STATE_BUY){//当前 多头持仓
	        	return - (lastPrice - this.price) * amount;
	        }
	    },
	    SetStopPrice: function(ticker,stopState){//更新止损价
	    	if(stopState === STATE_FREE){ //更新止损时状态 为空闲
	    		return this.stopPrice;
	    	}
	    	if(stopState === STATE_BUY){ //更新止损时状态 为多仓
	            if(this.orderState === ORDER_INVALID){
	        	    return this.stopPrice;
	            }
	            if(this.stopPrice === 0){//初始 止损价为0 时 
	            	this.stopPrice = this.price * ( 1 - stopProfit );
	            }
	            if( ticker.Last <= this.price ){ //最后成交价 小于等于  持仓均价时
	                this.stopPrice = this.price * ( 1 - stopProfit );
	                this.level = 1;
	            }else{//其它情况
	        	    if( ticker.Last - this.price > this.level * step ){//超出当前等级   设置滑动止损
	                    this.stopPrice = this.price * (1 - stopProfit) + (ticker.Last - this.price );
	                    //更新止损价为滑动后的止损价
	                    this.level++;//上调止损等级
	        	    }else{//其它
	        	    	this.stopPrice = this.stopPrice;//保持当前止损价不变
	        	    }
	            }
	    	}else if( stopState === STATE_SELL){//空头持仓类似
	    		if(this.orderState === ORDER_INVALID){
	        	    return this.stopPrice;
	            }
	            if(this.stopPrice === 0){
	            	this.stopPrice = this.price * ( 1 + stopProfit );
	            }
	            if( ticker.Last >= this.price ){
	                this.stopPrice = this.price * ( 1 + stopProfit );
	                this.level = 1; 
	            }else{
	        	    if( this.price - ticker.Last > this.level * step ){
	                    this.stopPrice = this.price * (1 + stopProfit) - ( this.price - ticker.Last );
	                    this.level++;
	        	    }else{
	        	    	this.stopPrice = this.stopPrice;
	        	    }
	            }
	    	}
	        return this.stopPrice;//返回止损价
	    },
	    initHoldOrder: function(){//平仓后  用于 初始化持仓信息的  函数
	        this.orderState = ORDER_INVALID;
	        this.price = 0;
	        this.amount = 0;
	        this.time = null;
	        this.stopPrice = 0;
	        this.level = 1;
	    }
	};
  • The code is uploaded to Github: Click heregithubI'm not sure.
  • If you are not a member of the official QQ group, please join: 309368835 Inventors Quantify.

Below we'll get a quick preview of the functions that will be used.

function MACD_Cross(){//检测MACD指标,交叉状态的函数
    var records = exchange.GetRecords();//获取K线数据
    while(!records || records.length < 45){ //K线数据不能为null,要大于45个柱,不符合标准 循环获取直到符合
    	records = exchange.GetRecords();
    	Sleep(Interval);
    }
    var macd = TA.MACD(records,12,26,9);//调用指标函数, 参数为MACD 默认的参数。
    var dif = macd[0];  //dif线
    var dea = macd[1];  //dea线
    var column = macd[2]; // MACD柱
    var len = records.length;  //K线周期长度
    if( (dif[len-1] > 0 && dea[len-1] > 0) && dif[len-1] > dea[len-1] && dif[len-2] < dea[len-2] && column[len-1] > 0.2 ){ 
    //判断金叉条件:dif 与 dea 此刻均大于0 , 且dif由下上穿dea , 且 MACD量柱大于0.2
    	return 1; //返回1  代表 金叉信号。
    }
    if( (dif[len-1] < 0 && dea[len-1] < 0) && dif[len-1] < dea[len-1] && dif[len-2] > dea[len-2] && column[len-1] < -0.2 ){
    //判断死叉条件:
        return 2;//返回2  代表 死叉信号。
    }   
    return 0;  //金叉  、死叉  信号以外,为等待信号 0 。
}
function getTimeByNormal(time){// 获取时间的 函数 把毫秒时间 转换 标准时间
    var timeByNormal = new Date();
    timeByNormal.setTime(time);
    var strTime = timeByNormal.toString();
    var showTimeArr = strTime.split(" ");
    var showTime = showTimeArr[3]+"-"+showTimeArr[1]+"-"+showTimeArr[2]+"-"+showTimeArr[4];
    return showTime;
}

Below is the main entry to the policy, which uses the same 30-line equilateral policy as the previous one. The transaction template library is packed with transaction details, and interested friends can find the code on the inventor quantification, annotated version shared on the official QQ group, github.

function main(){
    var initAccount = $.GetAccount(exchange);//首先我们来记录初始时的账户信息,这里调用了模板类库的导出函数
    var nowAccount = initAccount;//再声明一个 变量 表示 现在账户信息
    var diffMoney = 0; //钱 差额
    var diffStocks = 0;//币 差额
    var repair = 0; //计算 盈亏时   用于修正的 量
    var ticker = exchange.GetTicker(); //获取此刻市场行情
    Log("初始账户:",initAccount); //输出显示  初始账户信息。
    while(true){//主函数循环
        scan(); //扫描函数,  稍后讲解,主要是判断  开仓、平仓 以及 操作 开仓 、 平仓。
        ticker = exchange.GetTicker();//在while循环内 获取 市场行情
        if(!ticker){//如果 没有获取到  (null) 跳过以下 重新循环
        	continue;
        }
        if(holdOrder.orderState == ORDER_VALID){//判断当前是否  持仓
        	Log("当前持仓:",holdOrder); //如果 当前持仓   输出  持仓 信息
        }
        if(holdOrder.orderState == ORDER_INVALID){//如果 未持仓(已平仓)
        	nowAccount = $.GetAccount(exchange); //获取当前账户信息
            diffMoney = nowAccount.Balance - initAccount.Balance; //计算  当前账户  与 初始账户之间的  钱 差额
            diffStocks = nowAccount.Stocks - initAccount.Stocks; // 计算  当前账户  与  初始账户之间的  币 差额
            repair = diffStocks * ticker.Last; //把 币的差额 * 最后成交价  ,转为等值的钱, 用于计算 盈亏
            LogProfit(diffMoney + repair ,"RMB","现在账户:",nowAccount,"本次盈亏:",profit);//输出 盈亏 信息
        }
    	Sleep(Interval);//轮询
    }
}

The following are the main parts of the strategy, the open position detection, and the open position operation.

function scan(){
	var sellInfo = null; //声明  储存平仓信息的变量  , 初始化null
	var buyInfo = null;  //声明  开仓的 , 初始化null
	var opFun = null;//  开仓函数, 两种状态 ,  开多仓 ,  开空仓。
	var singal = 0; //信号
    while(true){//检测 及操作 循环
        var ticker = exchange.GetTicker(); //获取市场行情
        if(!ticker){ //判断 获取失败  跳过以下 ,继续循环获取
        	continue;
        }
        holdOrder.SetStopPrice(ticker,state); //设置 持仓 止损价
        if(state === STATE_FREE &&  (singal = MACD_Cross()) !== 0  ){
        	//判断策略运行状态是否空闲、此刻MACD指标信号是否空闲, 符合 策略运行状态空闲 且 有金叉或死叉执行以下
        	holdOrder.initHoldOrder();//初始化持仓信息
            opFun = singal === 1 ?  $.Buy : $.Sell ;//根据MACD_Cross函数返回结果,判断开多仓、开空仓。
            buyInfo = opFun(opAmount);//开仓操作
            holdOrder.orderState = ORDER_VALID;//设置持仓信息,状态为持仓
            holdOrder.price = buyInfo.price; //设置持仓均价  由 开仓操作函数 opFun返回。 
            holdOrder.amount = buyInfo.amount; //设置持仓量
            holdOrder.time = getTimeByNormal((new Date()).getTime());//设置持仓开始的时间
            state = singal === 1 ? STATE_BUY : STATE_SELL; //更新策略状态为多仓 或 空仓
            var account = $.GetAccount(exchange); //获取账户信息
            if(singal === 1){//输出开仓方向 和 当前账户信息
            	Log("开多仓。","账户:",account);
            }else{
                Log("开空仓。","账户:",account);
            }
            break;
        }else{
        	var lastPrice = holdOrder.price;// 把持仓均价 赋值 给 lastPrice
        	if( state === STATE_BUY && holdOrder.orderState === ORDER_VALID && ticker.Last < holdOrder.stopPrice ){
            //如果 多仓 且 持仓信息为持仓 且 最后成交价 小于止损价,执行以下
        	    Log("多头止损平仓","初始止损价:",holdOrder.price * (1 - stopProfit),"--滑动止损价:",holdOrder.stopPrice,"最后成交价:",ticker.Last,"止损等级:",holdOrder.level);//多头止损平仓信息
        	    sellInfo = $.Sell(holdOrder.amount);//平仓
                holdOrder.orderState = ORDER_INVALID;//平仓信息 更新进对象
                holdOrder.price = sellInfo.price;
                holdOrder.amount = sellInfo.amount;
                holdOrder.time = getTimeByNormal((new Date()).getTime());
                profit = holdOrder.updateCurrentProfit(lastPrice,sellInfo.amount);//更新浮动盈亏
        	    state = STATE_FREE;//更新状态
        	    break;//跳出
        	}
        	if( state === STATE_SELL && holdOrder.orderState === ORDER_VALID && ticker.Last > holdOrder.stopPrice ){//同上 , 这个是空头止损平仓
        	    Log("空头止损平仓","初始止损价:",holdOrder.price * (1 + stopProfit),"--滑动止损价:",holdOrder.stopPrice,"最后成交价:",ticker.Last,"止损等级:",holdOrder.level);//测试
        	    sellInfo = $.Buy(holdOrder.amount);
                holdOrder.orderState = ORDER_INVALID;
                holdOrder.price = sellInfo.price;
                holdOrder.amount = sellInfo.amount;
                holdOrder.time = getTimeByNormal((new Date()).getTime());
                profit = holdOrder.updateCurrentProfit(lastPrice,sellInfo.amount);
        	    state = STATE_FREE;
        	    break;
        	}
            if(state === STATE_BUY && MACD_Cross() === 2 ){//做多时,MACD指标死叉 -- 死叉平仓
        	    sellInfo = $.Sell(holdOrder.amount);
        	    Log("死叉平仓","初始止损价:",holdOrder.price * (1 - stopProfit),"--滑动止损价:",holdOrder.stopPrice,"最后成交价:",ticker.Last,"止损等级:",holdOrder.level);//测试
                holdOrder.orderState = ORDER_INVALID;
                holdOrder.price = sellInfo.price;
                holdOrder.amount = sellInfo.amount;
                holdOrder.time = getTimeByNormal((new Date()).getTime());
                profit = holdOrder.updateCurrentProfit(lastPrice,sellInfo.amount);
        	    state = STATE_FREE;
        	    break;
            }
             if(state === STATE_SELL && MACD_Cross() === 1 ){//做空时,MACD指标金叉 ---金叉平仓
        	    sellInfo = $.Buy(holdOrder.amount);
        	    Log("金叉平仓","初始止损价:",holdOrder.price * (1 + stopProfit),"--滑动止损价:",holdOrder.stopPrice,"最后成交价:",ticker.Last,"止损等级:",holdOrder.level);//测试
                holdOrder.orderState = ORDER_INVALID;
                holdOrder.price = sellInfo.price;
                holdOrder.amount = sellInfo.amount;
                holdOrder.time = getTimeByNormal((new Date()).getTime());
                profit = holdOrder.updateCurrentProfit(lastPrice,sellInfo.amount);
        	    state = STATE_FREE;
        	    break;
            }
        }
        Sleep(Interval);//轮询间隔,就是让程序暂停一会儿。
    }
}

I'm tired of coding, I'm not drinking water.

Let's start with the principle of sliding stop loss.

In this section of the code about sliding stop loss, the user can see the following:SetStopPriceFunction based on inputstopState(Stop state) andticker(Market data) to update the stop loss price.stopState === STATE_BUYIn the case of a change in the price of the underlying asset, the price of the underlying asset shall be adjusted accordingly.orderStateReturns the current stop-loss price if the position is invalid. If the stop-loss price is 0, initialize it as the average purchase price multiplied by(1 - stopProfit)The following is based on the final transaction price.ticker.Last) and holding price equals (((this.priceThe difference between the current stop loss ratingthis.level) is compared to the multiplication of the step length. If it exceeds the current rank, the stop-loss price is updated to the value after the slide, while increasing the stop-loss rank; otherwise, the current stop-loss price is kept unchanged.stopState === STATE_SELLThe logic is similar, but the difference between the final transaction price and the holding price is negative, and the difference is subtracted when the stop loss price is updated. Finally, the stop loss price after the update is returned.

Sliding stop loss is a risk management strategy

During the holding, the stop loss price is adjusted according to the fluctuation of the market price in order to reduce losses or protect profits. According to the logic of the code, the following key points can be seen to achieve a slip stop loss:updateCurrentProfitThe method is used to update the current profit and loss based on the holding condition (state) and the latest price (lastPrice). If the holding is empty (STATE_SELL), the profit and loss is the difference between the latest price and the holding price multiplied by the holding amount; if it is multi-head state (STATE_BUY), the profit and loss is negative. The SetStopPrice method is used to update the stop loss price. If the stop loss condition is empty (STATE_FREE), the current stop loss price is maintained. If the holding condition is multi-loss state (STATE_BUY), the stop loss price is adjusted according to different circumstances.1 - stopProfitIf the final trade price exceeds the step length of the current rank, the stop price is set to the stop price after the slide, and the stop-loss rank is raised. Otherwise, the stop-loss price remains unchanged. If the stop-loss state is empty, the logic is similar.

You can run back and test it first, remember to refer to the template of the cryptocurrency trading library.

References


Related

More

midskyHello, I am www.banbiren.com money changer, author of the banking platform banbiren, I am learning to quantify transactions, my QQ number is:39866099, can you invite me to join the group, I can not join the search first.

ZeroI've been working hard.

muiaIt was hard.

Inventors quantify - small dreamsOK ^^, you can apply directly, MAC QQ did not find the invitation >_<, 1 group number: 309368835 There are several positions now.

Inventors quantify - small dreamsI'm so happy for you.

Inventors quantify - small dreamsWe learn together.