Playing JavaScript with the old man - creating a partner who buys and sells - born in a sandbox

Author: The Little Dream, Created: 2017-03-06 10:41:40, Updated: 2017-10-11 10:36:53

I'm playing JavaScript with my old friend, and I'm creating a partner who will buy and sell.

Born in a Sandbox

  • The sandbox system

    When searching online for information, you find that using computer programs to do financial securities trading is called programmed trading, quantitative trading. Old-fashioned mathematical level is also at the university level, statistics has only a few basic concepts: normal distribution, expectations, integration, etc. Do not dare to say that you are most quantified in learning programming, quantification. In the process of learning programming, quantification, or in practice.

    The old man feels that a good sandbox needs the following:

    • 1, Simulating real time sequences as much as possible, i.e. when running a program in a sandbox, the time sequence should be as close as possible to the real situation, based on the tick level, so that the test results have a reference value. This may cause the program to run at a limited speed in the sandbox, but the speed is also a very important factor.

    • 2, various parametric options control, which is required not by the parameters of the test program, but by the parameters of the sandbox system. For example: settings of the exchange (futures?A shares?Forex?), simulated account information of the exchange under test, transaction fees of the exchange, possible slippage rate, time range control, etc.

    • 3, Program parameters tweak: sometimes the old man has a lot of spare parameters, trying to see which one is better. A good sandbox system can accept a lot of preset parameters, and then run it itself, analyze the results, show the best.

    • 4, error tolerance testing: the program simulations often run smoothly, wind is calm, because it is in the basin of the sink (how many waves can there be?), but in reality it is an unpredictable deep sea, various unknown storms appear at any time. Then the sandbox system has to create some wind waves in the basin of the sink, to simulate the worst possible environment (is to release all kinds of erroneous data, network error reports, even logically impossible data).

    • 5, chart shows: charts can record a lot of useful data for analysis, such as earnings charts, price differential curves, etc.

  • We have a sandbox system in our hands, and we write some simple code in JS.

    • 1, General architecture of the CTP commodity futures automation program The bottom layer used by Old White already has a function wrapped in it.exchange.IO("status")To identify if the forward server of the futures company is connected. Here run the question: forward server of the futures company? The old man replied: Commodity futures use the CTP protocol, and the connection structure is: the terminal program of the futures company's client (the old white code) ----> the futures company's front-end server -----> the exchange server Returning to the main issue, when the commodity futures are off the market, it is not possible to connect to the forward server of the futures company ((after the expiration of a certain time the forward server of the futures company is off); or some circumstances cause the CTP to disconnect.

      function MainLoop(){  //  处理具体工作的函数
                          //  编写处理具体交易逻辑
      }
      function main() {
          var status = null;
          while(true){
              status = exchange.IO("status");      //  调用API 确定连接状态
              if(status === true){                 //  判断状态
                  LogStatus("已连接!");            //  在回测或者实际运行中显示一些实时数据、信息。
                  MainLoop();                      //  连接上 交易所服务器后,执行主要工作函数。
              }else{                               //  如果没有连接上 即 exchange.IO("status") 函数返回 false
                  LogStatus("未连接状态!");         //  显示 未连接状态。
              }
              Sleep(1000);                         //  封装的睡眠函数,参数是毫秒,1000毫秒 等于 1秒,需要有轮询间隔, 以免访问过于频繁。CTP协议是每秒推送2次数据。
          }
      }
      

      Run in the sandbox:

      img img

      You see in the diagram, we set up a check-back account with 100W of funds.

      img

    • How do you get your account information data in the program, since the bottom layer is wrapped up and made into a function?exchange.GetAccount()I'm going to try this simple sentence.

      function MainLoop(){  //  处理具体工作的函数
          exchange.GetAccount();    
      }
      

      It's just that this customizationMainLoop()Write to the functionexchange.GetAccount();

      The result shows nothing. The function is running, but no log printing function is called. This is also a wrapped log output function.Log()The function parameter is to output various variables, which can be passed multiple comma intervals. When writing code, in addition to the string can be entered in Chinese input, the rest of the writing code must be remembered when switching to English, old white will drop this pit, waste a lot of time to find out is written in Chinese input symbol.

      function MainLoop(){                     // 处理具体工作的函数
          Log(exchange.GetAccount());          // 写法1
          var Account = exchange.GetAccount(); // 写法2
      }
      

      img

      MainLoop is executed continuously (with intervals of 1 second all-sleep) so all the output of the retrieval system logs is analog account information.
    • Then in the sandbox request some other data, old white used to often focus on the screw steel commodity futures variety, because at the same time also focus on the price of housing.

      The first thing you need to know is what kind of market you want to understand, for example, the 1705 contract for stainless steel. Well, the contract in the exchange code is: rb1705 (futures knowledge I'm also a Baidu self-employed), use it.exchange.SetContractType("rb1705")Also, I would like to know what the current state of the rb1705 contract is (the time point in the feedback system when it is running).exchange.GetTicker()I would like to know the historical price cycle statistics of this contract.exchange.GetRecords()Put it down.MainLoopThe function is modified:

      var index = 0;                                                // 声明一个全局变量 用来记录循环次数
      function MainLoop(){
          var ContractInfo = exchange.SetContractType("rb1705");    // 设置我要操作的 商品期货合约类型 即 螺纹钢1705合约。
          if(!ContractInfo){
              return;                                               // 如果设置合约没有成功,即返回函数,再次进入重试。
          }
          Log("rb1705 Info:", ContractInfo);                        // 显示一下合约详细信息。
          var ticker = exchange.GetTicker();                        // 通过CTP协议请求 此刻行情数据
          var records = exchange.GetRecords();                      // 通过CTP协议请求 历史K线数据,K线的周期默认周期是在沙盒系统上设置的。
          Log("ticker:", ticker);                                   // 打印出来 此刻行情数据
          Log("records:", records);                                 // 打印出来 历史K线数据
          Log("index:", index++, "#FF0000");                        // 打印循环次数, 在最后参数传入 "#FF0000" 可以使打印的日志显示为红色。
      }
      

      img

      Select part of records Variable value (array type): [This is a video] It is also known as the "Template:Citation needed" or "Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Template:Temp Time: The time stamp, the millisecond scale of time. Open: Open price 、High: High price 、Low: Low price 、Close: Closing price 、Volume: Trade volume

      The value of the ticker variable (object) is printed: I'm going to have to go to the gym and get some sleep. High: current highest price Low: current lowest price Sell: sell price Buy: buy price Last: last trade price Volume: most recent trade

      Information about the rb1705 contract: ((You can see the description of the fields in the CTP protocol.)) {pos (192,210) } This is the most common type of silicon. This is the first time I've ever seen this. I'm not sure what you're talking about. This is the first time I've seen this in my life. This is a list of all the different ways EndDelivDate is credited in the database. The exchange ID tag: SHFE tag It is also known as the "RB1705" or the "RB1705". I've been trying to get a hold of you for a while. You can't go wrong with this. The instrument ID is rb1705. It is the most commonly used type of metal in the world. This is the first time I've seen this video. The long margin ratio is 0.06%. I'm not sure what you're talking about. Max Margin Side Algorithm is 48%. I'm not sure what you're talking about. This is the first time I've ever seen this in my life. This is the first time I've ever seen this in my life. This is the first time I've seen this in my life. It's not a good idea. This is the first time I've seen this. I'm going to go to the gym. I'm going to go to the gym. I'm not sure what you're saying. I'm not sure what you mean. The product ID tag: rb tag The short-margin ratio is 0.06%. This is the first time I've seen this video. I'm not going to say anything about it. "UnderlyingInstrID": UnderlyingMultiple: 0, I'm going to try to get a copy of this. I'm not sure.

    • And finally, we're going to have the robot move in the sandbox.

      Here is a brief introduction to the concept of commodity futures, in the futures, whether it is to buy a multi-position contract (see below contract) or to buy a short position contract (see below contract) are called open positions, in order to distinguish: buy a multi-position contract is called open position, buy a short position contract is called open position.

The term "placement" refers to the act of a futures trader buying or selling futures contracts of the same type, number and delivery month as the futures contract he holds, but in the opposite direction of the trade, closing positions. A futures trader has the option to sell the futures contract purchased before the end of the last trading day, or to buy back the futures contract sold, in order to obtain an equal amount of cash. In the opposite direction, futures trading to displace the original futures contract, thus ending the futures trading, releasing the obligation to deliver in physical on maturity. What's up?

##### 所以在期货市场做买卖就有4个方向:

用 ```SetDirection()``` 函数来 确定操作的方向

- 开多仓:SetDirection("buy") ,传入参数 "buy" 字符串,明确 exchange.Buy() 函数为 开多仓 操作, Buy 函数稍后讲到。

- 开空仓:SetDirection("sell"), 传入参数 "sell" 字符串,明确 exchange.Sell() 函数为 开空仓 操作,Sell 函数稍后讲到。

- 平多仓:SetDirection("closebuy"), 传入参数 "closebuy" 字符串, 明确 exchange.Sell()函数为 平多仓操作。

- 平空仓:SetDirection("closesell"), 传入参数 "closesell" 字符串,明确 exchange.Buy()函数为 平空仓操作。

下个单试试!继续改写 MainLoop 函数,我们让程序在沙盒里面每隔10分钟 交易一次,开多仓平多仓交替进行。
```
var index = 0;
var isFirst = true;
function MainLoop(){
    if(isFirst){
        Log(exchange.GetAccount());
        isFirst = false;
    }
    var ContractInfo = exchange.SetContractType("rb1705");
    if(!ContractInfo){
        return;                                               // 如果设置合约没有成功,即返回函数,再次进入重试。
    }
    var ticker = exchange.GetTicker();
    if(index % 2 === 0){
        exchange.SetDirection("buy");
        exchange.Buy(ticker.Last + 1, 1, ticker); // exchange.Buy 函数有2个必要参数,第一个参数为下单价格,
                                          // 第二个参数为下单数量(希望交易的数量),之后还可以跟一些参数输出在日志信息。 
                                          //ticker.Last + 1 是为了让单子能成交,意思是在最后成交价的基础上多出1块钱。
    }else if(index % 2 === 1){
        exchange.SetDirection("closebuy");
        exchange.Sell(ticker.Last - 1, 1, ticker); // ticker.Last - 1 是为了在最后成交价的基础上减去1元 卖出。
    }
    index++;
    Sleep(1000 * 60 * 10 - 1000);         // 这里暂停10分钟 ,减去的1000 即1秒是 main 函数循环中的1秒。
    Log(exchange.GetAccount());
}
```

![img](/upload/asset/bd6dd2ef0e5db88c70f0585aee3a417c92227d31.png) 

##### 开始的账户信息 和 最后一次开仓 前的账户信息比较,可见不能胡乱开仓平仓。 >_<

Before I write this, welcome readers to leave me a comment! Send me your suggestions and comments, and if you feel like it's fun, share it with more friends who love the program and love the deal.

https://www.fmz.com/bbs-topic/724

Programmer littleDream originally created


More