The inventor's diary of quantum chemistry (a) completed

Author: The Little Dream, Created: 2016-05-23 23:10:46, Updated: 2019-08-01 10:31:25

It used to be very rare to write a journal, now it feels like you need to record something every day, can't you see the light of day? What do you write? Just record learning, work! (in fact, almost all of it..) Today, in addition to daily work, there is no problem in writing a module to the customer, retesting the entire code, except for a strange indicator line on the chart, the rest seems normal, OK, upper simulator testing.

Question one:

  • 1, the K-line of the graph is sometimes missing a BAR, is looking for a BUG. The problem is found, analyzed, and no data is received when testing with the analog disk. At the time of receiving the data, two BARs have passed, so the latest data is drawn on the graph, causing one or more of the intermediate spaces to pass.
  • 2, run for a while ((1 minute K-line cycle) no problem, try again ((30 minutes K-line cycle) problem comes up, unknown strange:

TypeError: cannot read property length of null duk_hobject_props.c:2258 WToneAndWTtwo __FIL This error is reported.

I'm looking at an error that should be in the function WToneAndWTtwo, reading the name of the null value called the length property, which is a variable such as var name = null; then I read the name of the null value called the length property, which is a variable such as var name = null; then I read the name of the null value called the length value, which is a variable such as var name = null; then I read the name of the null value called the length value, which is a variable such as var name = null; then I read the name of the null value, which is a variable called the length value, which is a variable called the length value, which is a variable called the length value, which is a variable called the length value, which is a variable called the length value, which is a variable called the length of the variable. After reading name.length, the entire code is searched for a place where the length can be called.

function isNullAndLog(arr,strArrName){//空数组报错
     if(!arr){
         Log("arr is:",arr,"name:",strArrName);
         return true;
      }
      return false;
}

Think, hey! I put all the variables used to the length into this function to test, there are absolutely no null bugs to escape. Change the code, run the robot test. I've been using the K-line test for 30 minutes, and then I'm rubbing it again:

TypeError: cannot read property ‘length’ of null duk_hobject_props.c:2258 WToneAndWTtwo FILEI'm not sure what to do.

I can't figure it out! Be patient! Go out and turn around and change your mind or you'll come to your senses! I'm back and I'm wondering if I'm calling the index library, the input parameter is null, the index library is running and it's gone wrong.

function isNullAndLog(arr,strArrName){//空数组报错
    if(!arr){
        Log("arr is:",arr,"name:",strArrName);
        return true;
    }
    return false;
}

function main(){
   if(typeof(x) === undefined ){
       Log(typeof(x));
   }
    var aaa = null;
    Log(isNullAndLog(aaa));
    /*
    while(!aaa || aaa.length < 9){
        Log("while xunhuan");
        Sleep(5000 * 1000);
    } 
    */
    talib.EMA(aaa,5);
} 

talib.EMA ((aaa,5); the key word aaa is null, I set it intentionally, pass it on and see what happens. TypeError: Cannot read property length of null ~~OK. This is probably the problem, keep modifying the code.

Question two:

Another problem is that the previously thought about now recording code:

function DeleteNullEle(initArr){
    var dealArr = [];
    var initArrLen = initArr.length;
    for(var i = 0,j = 0 ; i < initArrLen ; i++,j++){
    //Log("initArr-",i,":",initArr[i]);//ceshi
    if(initArr[i] === null || isNaN(initArr[i]) ){
        j--;
        //Log("i:",i);//ceshi
        continue;
    }
        dealArr[j] = initArr[i];
    }
    //Log("dealArr:",dealArr);//ceshi
return dealArr;
}

The reason for adding this function is that some arrays are like this [NaN, NaN, NaN, NaN, 22, 3, 56, 78, 4, 23] but when the inventor quantized the test using the Log function, it showed that it was null, which is the same as the log of the array. Let me be confused for a long time, big hole, I must remember, you see is null or maybe NaN, so judging null is not judging.
Another thing is this while ((!aaa gbla aaa.length < 10) {...}, if aaa === null, why not return an error because the expression for this operator is null. The aaa.length expression is always true, so the next aaa.length may not have been executed. This seems to have been seen when learning HTML, CSS, DOM, and judging the browser. Some of the APIs have been used.

Question three:

In addition, a group of friends asked me to modify the monitoring of the difference, which is actually an additional detection of the difference range, and WeChat pushed, very simple.

 if (diff != __lastDiff) {
//--------------------------------------------------------------------------------------------
        if(openWeixin){
            if( (diff <= price1 || diff >= price2 ) && off_on === true ){
                Log("差价:"+diff+"微信推送@");
                off_on = false;
                Sleep(1000);
            }else{
                off_on = true;
                Sleep(1000);
                }
        }
//---------------------------------------------------------------------------------------------
        // add添加数据到series, 参数格式为[series序号, 数据];
        __chart.add([0, [new Date().getTime(), diff]]);
        __lastDiff = diff;
    }

img

The code that is added between the lines of code is very simple and may not be perfect.

Question 4 (not really a problem, just a little learning record)

These days in learning the strategy of writing futures, this is more complex than the spot point, ((Luckily there are Z-sized futures trading templates, otherwise writing the details of the trade is enough to drink a glass of water >____

  • exchange.GetPosition ((() // is used to retrieve the position information, note that this function returns an array of a position structure containing all the specific information for the position.
  • exchange.SetMarginLevel (MarginLevel) // This function is used to set the leverage. Specific parameters MarginLevel selection ((5 times? 10 times?) depending on the variety, exchange, specifically, some cannot be changed (such as CTP commodity futures)
  • exchange.SetDirection ((Direction) // This is a very important API, which is called before the following list, because we have just introduced four operations ((sell open position...), this function is the one that sets these operations ((although there is a bit of extra content), and the second parameter of CTP is not yet studied.
  • exchange.SetContractType (ContractType) // One is to specify the direction of the transaction before opening or closing the position (more? empty? flat?), and the other is to specify the contract (white sugar? cotton?), so this function is used to set the contract type. The parameters are specific to different exchanges. This is basically the same as using these functions. The rest of the functions are the same as the current ones.
  • exchange.Buy ((() // buy
  • exchange.Sell ((() // sell Below is the code of my experiment, where I just select a section (which can be copied to try in the main function) and retest. The exchange being tested is the commodity futures exchange:img
 if (!manager) {//Z大写的商品期货模板类库,用来管理交易的对象(manager 初始时null)。不明白的可以去看源代码,QQ群共享有注释版。
        if (_C(exchange.GetPosition).length > 0) {
            throw "策略启动前不能有持仓.";
        }
        Log('交易平台:', exchange.GetName(), _C(exchange.GetAccount));  //输出当前交易所 信息
        var insDetail = _C(exchange.SetContractType, ContractTypeName);  // 用容错函数 _C ,容错调用 SetContractType函数  首先明确 设置交易的合约类型。
        Log("合约", insDetail.InstrumentName, "一手", insDetail.VolumeMultiple, "份, 最大下单量", insDetail.MaxLimitOrderVolume, "保证金率:", insDetail.LongMarginRatio.toFixed(4), insDetail.ShortMarginRatio.toFixed(4), "交割日期", insDetail.StartDelivDate);
        // 上面这个Log 显示出合约的一些信息,注意 在回测的时候,与实际运行的结果不一样,可以看图杠杆都是null,保证金率都是0,可以试试看。
        manager = $.NewPositionManager();  // 这个生成管理者 对象
    }
    exchange.SetMarginLevel(10); //不支持       在这里我试着设置了一下杠杆试试,发现  显示 错误:Not support     ,CTP商品期货 应该不能自己调整杠杆
    var positions = exchange.GetPosition();     在所有的操作前 ,我试着调用了一下 GetPosition 函数  获取一下持仓信息,显示的null
    Log(positions[0]);
    exchange.SetDirection("buy"); // 在所有的操作前需要设置  操作方向  ,这里设置 买开仓(做多)。
    var id = exchange.Buy(1911,1); // 执行买入操作  下了一个  限价单,  有兴趣的同学 可以试试 市价单。(嘿嘿!自己动手记得牢)
    positions = _C(exchange.GetPosition); //再获取下 持仓信息 看看
    Log(positions);  //有持仓信息了,  在上面 Buy的时候  有兴趣的同学 试试 用低价格 买入。  Buy(1000,1) 看看。

Question 5: Today a friend wrote a piece of code asking for the Sleep () function. The error is large and affects the high frequency policy.

function main(){
    for(var i = 0 ; i < 10 ; i++){
        var b1 = 0;
        var b2 = 0;
        var b3 = 15;
        while(b1 < 200){
            var t2s1 = (new Date()).getTime();
            b1++;
            Sleep(b3);
            var t2s6 = (new Date()).getTime();
            b2 += (t2s6 - t2s1);
        }
        Log("Sleep()",b3,"MS",b1,"平均次数",b2/b1);
    }
    throw 2;
}

I retested and found that the Sleep function would run for 1 second in the retest (with a time difference of 1000 before and after), and then the time error of this test code was very large, but if it was running on an analog drive, it was basically within 1 millisecond. It may be that the retest system belongs to the sandbox model, the error caused by the running algorithm in it. The simulation time is very small.

Question 6: A friend of mine sent me a system log this morning, saying that the host crashed in the middle of the night. I reported the problem to Z. I found out, I recorded it here.

- This is a log.

runtime/cgo: pthread_create failed: Resource temporarily unavailable
SIGABRT: abort
PC=0x7f332c591cc9 m=2

goroutine 0 [idle]:

goroutine 1 [select, 207 minutes]:

From the first line we see thread generation failure, resource temporarily unavailable (insufficient). It seems that it should be a memory problem, possibly caused by insufficient memory. The solution: 1, checks the running bot policy code, whether the resources used were not released, whether the APIs used were multi-threaded. 2, use ulimit command to check the system limitations of the host (Linux) ⋅ This blog can be viewed here: (Blog address)http://smilejay.com/2012/04/fork_resource/I'm not sure. 3, Pay attention to the use of system memory.

Use ulimit -a to show:img

The parameters of the ulimit command: -H sets the hard resource limit. -S sets the soft resource limit. -a shows all current resource limits. -c size: set the maximum value of the core file. Unit: blocks -d size: Set the maximum value of the data segment. Unit: kbytes -f size: Set the maximum value for creating a file. Unit: blocks -l size: Set the maximum value of the process to lock in memory. Unit: kbytes -m size: Set the maximum amount of RAM that can be used. Unit: kbytes -n size: Set the maximum value of the file descriptor that can be opened simultaneously in the kernel. Unit: n -p size: Maximum value of the pipeline buffer zone set. Unit: kbytes -s size: Set the maximum value of the stack. Unit: kbytes -t size: Set the maximum CPU usage time. Unit:seconds -v size: set the maximum value of virtual memory. Unit: kbytes -u < number of programs> Maximum number of programs a user can run

A friend who encountered this problem found that the error filtering function may be the cause of the problem, and found the cause of the crash of the host (memory inflation). SetErrorFilter (( 502: 503: tcp character unexpected network timeout WSARecv Connect GetAddr no such reset httppreceived EOF reused ); function misuse, the function only needs to be called once and cannot be written in the loop structure. The problem above ( memory expansion) is that because the function is written in the onTick function, the onTick number is repeatedly called in the loop, leading to the final crash.

Question 7: A simple summary of the use of the _C() function, _N() function, _G() function.

  • The _C() function

Explanation: This function is mainly used for API error tolerance, such as the exchange.GetAccount () function, which is called as follows: _C ((exchange.GetAccount); note that the function name does not include parentheses, if the error tolerant function requires the addition of parameters, it is written in the second parameter of the _C() function, in turn backwards. Use examples.

function main(){
    var account = null;
    var amount = 1;
    var price = 2000;
    account = exchange.GetAccount();
    Log("_C 函数使用前  account :",account);
    //exchange = null; 
    _C(exchange.Buy,price,amount);
    //exchange.Buy(price,1);
    account = exchange.GetAccount();
    Log("_C 函数使用后  account :",account);
}

I guess the _C function looks like this:

 function ___C(functionName,p1){
    functionName("执行需要容错的函数,传入的测试参数为:",p1);
    Log("__C 容错函数启动,容错完毕");
}
function main(){
    pstr = "测试参数--hello";
    ___C(Log,pstr);
}

The results:img

  • The _N() function Explanation: This function is used to handle a large number of decimal places and retains a few decimal places. Use examples:
function main(){
    var pi = 3.1415926535897;
    Log("使用_N函数 前pi:",pi);
    var piOfDeal = _N(pi,2);
    Log("使用_N函数后 pi:",piOfDeal);
}

The results:img

  • The _G() function Explanation: This is a comprehensive dictionary that can be saved in the API documentation. KV tables, permanently stored local files, a separate database for each bot, that remain after a restart or an administrator logs out K must be written as a number or a string, regardless of size, and V can be written as anything that can be sequenced in JSON. _G ((num, 1); // Set a global variable num to a value of 1 _G ((num, ok); // Change a global variable number to the value of string ok _G ((num, null); // Delete the global variable num _G ((num); // Returns the value of the global variable num _G(); // Returns the ID of the current bot _G(null); // Removes all global variables
function main(){
    Log("totalYLMoney 初始赋值 0");
    var totalYLMoney = 0;
    Log("totalYLMoney 已赋,  = ",totalYLMoney);
    if(typeof(_G("totalYLMoney_save")) !== "object"){
        totalYLMoney = _G("totalYLMoney_save"); 
        Log("读取 totalYLMoney 本地数据库 名称为totalYLMoney_save 的值 赋给 totalYLMoney ");
    }else{
        totalYLMoney = 100.12546328765458;
        _G("totalYLMoney_save",totalYLMoney.toString());
        Log("记录 totalYLMoney 保存到本地数据库");
    }
    Log("totalYLMoney",totalYLMoney);
    Log("typeof\(_G(\"totalYLMoney_save\"))",typeof(_G("totalYLMoney_save")));
}

The above _G() function test code requires testing on the robot, retesting is not supported. Test method, deploy the program on the robot, the first time the robot is started, the robot will record 100.12546328765458; this value is stored in the dictionary under the name "totalYLMoney_save"; run the robot again and you will find var totalYLMoney = 0, which is still read from the dictionary after the variable totalYLMoney is initialized.

Question 8: A little insight into strategy and profit and loss calculation:

Many times I see new students in the group, asking about the algorithms of the strategy. Generally, there are several ways to deal with it, here is a simple one, the idea is also provided by the Great God in the group, here I am responsible for explaining it.

  • Floating profits:

The floating profit is: divided by (current currency - initial currency) x current price + (current money - initial money)

For example: For example, the initial price of the coin is 10 yuan/piece, the account starts with 5 yuan/piece, 100 yuan/piece. Over a period of time, I bought 3 yuan/piece at an average price of 15 yuan/piece. At the end of this period, the price of the coin rises to 20 yuan/piece. At the moment my account is: 8 yuan/piece, 55 yuan/piece. Profit = (8 - 5) * 20 + (55 - 100) = 60 + (-45) = 15 This method of calculation Profit is 15 yuan. (Note: at this time your earnings are floating, because if the price of the currency falls significantly at this time, maybe you not only do not make a profit, but also lose money, of course losing money is also floating, because your earnings at this time is following the price of the currency floating, the reason is to do too much flat bust, drop bag) Additionally, if at the time of the coin price of 20 yuan/piece, the equilibrium, i.e. 20 yuan to sell 3 coins bought at the same price of 15 yuan, at the moment the account is: 5 coins, 115 yuan; or the above algorithm: Profit = (5 - 5) * 20 + (115 - 100) = 15, the gain is still 15 yuan, the difference is that if the initial holding currency depreciation is not taken into account, the gain does not change with the price.

  • Profit on account:

The book profit: (current coin x current price + current money) - (initial coin x initial price + initial money)

Let's use the example above: For example, the initial price of the coin is 10 yuan/piece, the account starts with 5 yuan/piece, 100 yuan/piece. Over a period of time, I bought 3 yuan/piece at an average price of 15 yuan/piece. At the end of this period, the price of the coin rose to 20 yuan/piece. Profit = (8 * 20 + 55) - (5 * 10 + 100) = 215 - 150 = 65 This method of calculation is a profit of 65 yuan. Profit = (5 * 20 + 115) - (5 * 10 + 100) = 215 - 150 = 65 is the same.

Comparing the above two methods, one earning 15 and one earning 65, it is not difficult to see. The first method ignores the gains and losses of the initial bearer's devaluation. The second algorithm calculates the gains and losses by including the gains and losses of the initial bearer's devaluation. The calculation of the perceived accounting profit is applied to settlement funds. Floating profit refers to the profit or loss on a transaction over a period of time. These are some of the experiences of little dream analysis, if there are mistakes, please leave a message, thank you in advance ^-^

Question 9: A group member saw the status bar of a public policy displaying a table, so he went through the API below and found what appeared to be a new feature, the LogStatus function in the API that could draw a table. The group member asked me to test the test, which I also took note of, by the way, to make it easier for new students to learn.

First, take a look at the platform's API description:

LogStatus(Msg); //	此信息不保存到日志列表里, 只更新当前机器人的状态信息, 在日志上方显示, 可多次调用, 更新状态
LogStatus('这是一个普通的状态提示');
LogStatus('这是一个红色字体的状态提示 #ff0000');
LogStatus('这是一个多行的状态信息\n我是第二行');
var table = {type: 'table', title: '持仓信息', cols: ['列1', '列2'], rows: [ ['abc', 'def'], ['ABC', 'support color #ff0000']]};
LogStatus('`' + JSON.stringify(table)+'`'); // JSON序列化后两边加上`字符, 视为一个复杂消息格式(当前支持表格)
LogStatus('第一行消息\n`' + JSON.stringify(table)+'`\n第三行消息'); // 表格信息也可以在多行中出现
LogStatus('`' + JSON.stringify([table, table])+'`'); // 支持多个表格同时显示, 将以TAB显示到一组里

The test code is:

function main(){
    var value1 = 99;
    var value2 ="ceshi 01";
    var table1 = { type : "table", title : "ceshi1", cols : ["列1","列2","列3"] , rows : [ ["abc","def","ghi"] , ["1","2","3"] ] };
    var table2 = { type : "table", title : "ceshi2", cols : ["列1","列2","列3"] , rows : [ ["abc",value1,"ghi"] , [value2,"2","3"] ] };
    LogStatus("测试文本1\n`" + JSON.stringify([table1,table2]) + "`");
}

imgThe first diagram shows that we have a table that is partitioned into ceshi1, and the data format of the table is var table1 and var table2. Note that the JSON.stringify (([table1, table2]) function must be preceded by the addition of `. Otherwise, the table will not be displayed. Of course, we have to use tables to dynamically display some data, it can't always be fixed text content. table2 This page has two test data, value1 and value2, both data.imgNew students can copy the code, try it out and change it themselves.

Question 10: A user who wants a graph of the yield rate may currently have a relatively simple narrative in the inventor's quantified API documentation, and the graph may be difficult to use manually.

I used a random number to simulate the dynamic change in yields to show the yield curve on the graph.

var ChartObj = {//画图
    tooltip: {xDateFormat: '%Y-%m-%d %H:%M:%S, %A',enabled:true,valueDecimals:2,valueSuffix:'%'}, //提示框  就是鼠标在线上时 显示的一个 框框 里面有一些内容,这里是设置提示框的格式
    chart: { zoomType:'x',panning:true },//图表缩放  
    title: { text: '收益率 %'}, //标题
    rangeSelector: { //范围 区域 选择 
            buttons:  [{type: 'hour',count: 1, text: '1h'}, {type: 'hour',count: 3, text: '3h'}, {type: 'hour', count: 8, text: '8h'}, {type: 'all',text: 'All'}],
            selected: 0,
            inputEnabled: false
        },
    subtitle: {text: " 显示瞬时收益率 % "},//副标题
    xAxis:{type: 'datetime'}, //设置 X轴  的数值为时间类型
    yAxis: [{
            title: {text: '收益率 %'},//标题
            style: {color: '#4572A7'},//样式 
            //opposite: false  //生成右边Y轴
        }
    ],
    series: [//系列
        {name:'收益率',dataLables:{enabled:true,format:'{y} %'},type:'spline',yAxis:0,data:[]} //该图标只用到一条曲线  ,所以 只用设置一个数据序列
        ]                  
};
var chart = Chart(ChartObj);  //初始化

function main(){ //测试用的主函数
    chart.update(ChartObj); //更新
    chart.reset(); //清空图表
    var i = 0; //初始一个 i 值 , 后面循环用,   用来限制循环次数
    var randomNum = 0; //声明一个  随机数 初始化 0
    while(i < 5000){ //限制循环次数
        randomNum = Math.random() * 10;  // 生产随机数 0  -  9.9999
        //chart.add([0,[(new Date()),randomNum]]);
        chart.add(0,[(new Date()).getTime(),randomNum + 5]);  //把生成的随机数  按照时间(X 坐标)     把随机数 画在图表上(Y坐标)     
        Sleep(1000*60); // 程序 每次循环暂停60秒
        //chart.update(ChartObj);
        //chart.reset(500);
    }
    Log("over");
}
  • There is a problem here that has puzzled me for half a day, and I have also recorded it. Just when writing the time, it must be a millisecond count, write it like this: new Date (().getTime (()) This is a millisecond count, if this is new Date (()) then there will be a small problem, such as time display, and X-axis scaling cannot be used. There is also a tooltip: {xDateFormat: %Y-%m-%d %H:%M:%S, %A, enabled:true,valueDecimals:2,valueSuffix:%}, this setting is visible in the viewfinder.

More

liuxinghuiTeacher Little Dream, please tell me, if I have an unfinished order to cancel, what should I do?

louisThis must be a compliment!

It rained hard.There's a lot of things that aren't mentioned in the API documentation.

Autumn and fallShe is always good at organizing things.

The short-line king won selling the high-price strategyIt's good!

The Little DreamPlease be nice. This is a list of all the different ways Dn-filebox.qbox.me/bf52888dc68aba5326c403f2280994e81fbce2ee.png is credited in the database. The tutorial is available here: https://www.botvs.com/bbs-topic/475

The Little DreamIt's easy to learn!