2.6 Goods

Author: The Little Dream, Created: 2016-11-10 18:43:53, Updated: 2017-10-11 10:20:49

The term


  • Commodity futures

    The simple architecture of the commodity futures strategy (unlike the digital currency strategy learned earlier, which checks the connection status to the exchange server at the beginning of each cycle), of course it is better to judge again whether the contract to be traded is within the trading time period.
function MainLoop(){ //  处理具体工作的函数
    // deal Main task
}
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);                         //  需要有轮询间隔, 以免访问过于频繁。
    }
}

And then we're going to test the APIs with this architecture.

  • Access account information

It is assumed that the reader understands the process of adding a CTP Commodity Futures Simulator account and has already added a CTP Commodity Futures Simulator account. Unknowns can be studied Section 1.3.3 Exchange fee, CTP commodity futures Analogue plate Configuration (Teaching sticker)

The source code for the test is as follows, using the CTP Commodity Futures Simulator.

var Account = null;
function MainLoop(){
    Account = _C(exchange.GetAccount);
}
function main() {
    var status = null;
    while(true){
        status = exchange.IO("status");
        if(status === true){
            LogStatus("已连接!", new Date(), '\n', "Account:", Account);
            MainLoop();            
        }else{
            LogStatus("未连接状态!", new Date());
        }
        Sleep(1000);
    }
}

The simulation drive shows:

img

  • Set the leverage, set the contract type

Some new users may experience this error: when writing a CTP commodity futures strategy, they learn to call the API directly to get the K-line, the transaction data.exchange.IO("status"); the return value is found to be true and is connected. This is because: without subscribing to any kind of information, the API of the transaction is called to access the K-line. (The host does not know what data to send to you). So let's see how to subscribe to the contract information, that is, set the type of contract for the current operation. The following is a description of the API documentation:

SetContractType(ContractType)	设置合约类型
传统的CTP期货的ContractType就是指的合约ID,  如SetContractType("au1506") 返回合约的详细信息, 如最少一次买多少, 手续费, 交割时间等
股票合约格式为 股票代码.(SH/SZ), SH指上交所, SZ指深交所, 如000001.SZ就是指深交所的平安银行
商品期货与股票取消订阅合约, 在合约名前加上"-"前缀重新调用即可, 如SetContractType("-au1506"); 成功返回true
数字货币796支持: "week", "weekcny", 默认为子账户A, 要指定子账户是A还是B, 在合约后加"@A"或"@B", 如: "day@A" 为日合约A子账户
BitVC有week和quarter和next_week三个可选参数, OKCoin期货有this_week, next_week, quarter三个参数
exchange.SetContractType("week");

The parameter of the function ContractType is the contract code, the parameter is the string, so don't forget the double quotation marks.

imgFor example, Methanol MA, a contract delivered in January 2017, is code-named MA701. Below we use the MA701 example to call the SetContractType function to get contract information and set the contract to current operation.

The code is as follows:

var Account = null;
var isFirstSetContractType = true;   // 标记是否第一次设置 合约。
function MainLoop(){
    Account = _C(exchange.GetAccount);
    if(isFirstSetContractType === true){    // 是第一次设置合约 ,执行以下设置。
        var ContractInfo = exchange.SetContractType("MA701");   // SetContractType 函数返回 设置的合约的详细信息。
        for(var k in ContractInfo){    // 遍历这个信息结构。
            Log(k, ContractInfo[k]);   // 逐行打印。
        }
        isFirstSetContractType = false;    // 设置过合约了。
    }
}
function main() {
    var status = null;
    while(true){
        status = exchange.IO("status");
        if(status === true){
            LogStatus("已连接!", new Date(), '\n', "Account:", Account);
            MainLoop();            
        }else{
            LogStatus("未连接状态!", new Date());
        }
        Sleep(1000);
    }
}

You can see the details of the MA701 contract printed.

img img

The following are some simple attributes: Contract: Instrument Name, first hand: Volume Multiple portion, maximum order quantity: MaxLimitOrderVolume, guaranteed rate: Long Margin Ratio (multiple positions), Short Margin Ratio (empty positions), delivery date: StartDelivDate ‖

The following problems may arise during use:I want to know if there are any contracts that I can set up.exchange.IO("instruments"); query. I want to know if the current program subscribes to those contracts?exchange.IO("subscribed"); query. Try this:

var Account = null;
var isFirstSetContractType = true;                              // 标记是否第一次设置 合约。
function MainLoop(){
    Account = _C(exchange.GetAccount);
    if(isFirstSetContractType === true){                        // 是第一次设置合约 ,执行以下设置。
        var ContractInfo = exchange.SetContractType("MA701");   // SetContractType 函数返回 设置的合约的详细信息。
        for(var k in ContractInfo){                             // 遍历这个信息结构。
            Log(k, ContractInfo[k]);                            // 逐行打印。
        }
        isFirstSetContractType = false;                         // 设置过合约了。
        var contracts = exchange.IO("instruments");             // 查询 可订阅的合约 
        var str = "";
        for(var i in contracts){
            str += (i + "--");
        }
        Log("已经订阅的合约:" ,exchange.IO("subscribed"));        // 查询已经订阅的合约
        Log("可订阅的合约:", str);                               // 显示可以订阅的合约信息 
    }
}
function main() {
    var status = null;
    while(true){
        status = exchange.IO("status");
        if(status === true){
            LogStatus("已连接!", new Date(), '\n', "Account:", Account);
            MainLoop();            
        }else{
            LogStatus("未连接状态!", new Date());
        }
        Sleep(1000);
    }
}

The results of the analogue test:img

The CTP Commodity Futures Leverage setting is not supported yet.

  • Access to market data

With SetContractType, the current operating contract can be set up and the K-line and market data for that contract can be obtained. It is important to note that the SetContractType function is set to a contract, such as SetContractType (MA705), subscribe (MA705), and set the current contract to MA705, the methanol contract that was delivered in May 2017. The API functions GetRecords, GetTicker, GetDepth, etc. are called at this time.

var Account = null;   // 全局变量  用来保存每次获取的账户信息
var ticker = null;    //          用来保存每次获取的行情信息
var records = null;   //          用来保存每次获取的K线数据
var isFirstSetContractType = true;                              // 标记是否第一次设置 合约。
function MainLoop(){
        Account = _C(exchange.GetAccount);
        if(isFirstSetContractType === true){                        // 是第一次设置合约 ,执行以下设置。
            var ContractInfo = exchange.SetContractType("MA701");   // SetContractType 函数返回 设置的合约的详细信息。
            for(var k in ContractInfo){                             // 遍历这个信息结构。
                Log(k, ContractInfo[k]);                            // 逐行打印。
            }
            isFirstSetContractType = false;                         // 设置过合约了。
            var contracts = exchange.IO("instruments");             // 查询 可订阅的合约 
            var str = "";
            for(var i in contracts){
                str += (i + "--");
            }
        }
        ticker = exchange.GetTicker();      //    调用API  GetTicker 
        records = exchange.GetRecords();    //    调用API  GetRecords   默认周期
}
function main() {
        var status = null;
        while(true){
            status = exchange.IO("status");
            if(status === true){
                LogStatus("已连接!", new Date(), '\n', "Account:", Account, '\n', "ticker:", ticker , '\n', "records:", records);
                MainLoop();            
            }else{
                LogStatus("未连接状态!", new Date());
            }
            Sleep(1000);
        }
}

The results:

img

  • Acquisition of holdings

The GetPosition function API documentation describes:

GetPosition	获取当前持仓信息
返回一个Position数组, (BitVC和OKCoin)可以传入一个参数, 指定要获取的合约类型
Position 结构	期货交易中的持有仓位信息, 由GetPosition()函数返回此结构数组
{
        MarginLevel :杆杠大小, 796期货有可能为5, 10, 20三个参数, OKCoin为10或者20, 
                      BitVC期货和OK期货的全仓模式返回为固定的10, 因为原生API不支持。
        Amount       :持仓量, 796期货表示持币的数量, BitVC指持仓的总金额(100的倍数), OKCoin表示合约的份数(整数且大于1)
        CanCover     :可平量, 只有股票有此选项, 表示可以平仓的数量(股票为T+1)今日仓不能平
        FrozenAmount :冻结量, 支持传统期货与股票, 数字货币只支持796交易所
        Price        :持仓均价
        Profit       :持仓浮动盈亏(数据货币单位:BTC/LTC, 传统期货单位:RMB, 股票不支持此字段, 
                     注: OKCoin期货全仓情况下指实现盈余, 并非持仓盈亏, 逐仓下指持仓盈亏)
        Type	     :PD_LONG为多头仓位(CTP中用closebuy_today平仓), PD_SHORT为空头仓位(CTP用closesell_today)平仓, 
              (CTP期货中)PD_LONG_YD为咋日多头仓位(用closebuy平), PD_SHORT_YD为咋日空头仓位(用closesell平)
        ContractType :商品期货为合约代码, 股票为'交易所代码_股票代码', 具体参数SetContractType的传入类型
}

The test code is:

var Account = null;   // 全局变量  用来保存每次获取的账户信息
var ticker = null;    //          用来保存每次获取的行情信息
var records = null;   //          用来保存每次获取的K线数据
var positions = null;  //          用来获取 账户的持仓信息。
var isFirstSetContractType = true;                              // 标记是否第一次设置 合约。
function MainLoop(){
        Account = _C(exchange.GetAccount);
        if(isFirstSetContractType === true){                        // 是第一次设置合约 ,执行以下设置。
            var ContractInfo = exchange.SetContractType("MA701");   // SetContractType 函数返回 设置的合约的详细信息。
            for(var k in ContractInfo){                             // 遍历这个信息结构。
                Log(k, ContractInfo[k]);                            // 逐行打印。
            }
            isFirstSetContractType = false;                         // 设置过合约了。
            var contracts = exchange.IO("instruments");             // 查询 可订阅的合约 
            var str = "";
            for(var i in contracts){
                str += (i + "--");
            }
            exchange.SetDirection("buy");     // 设置 操作
            exchange.Buy(_C(exchange.GetTicker).Sell + 2, 1);    // 开多仓。
        }
        positions = exchange.GetPosition();   //    获取所有持仓信息
}
function main() {
        var status = null;
        while(true){
            status = exchange.IO("status");
            if(status === true){
                LogStatus("已连接!", new Date(), '\n', "Account:", Account, '\n', "ticker:", ticker 
                    , '\n', "records:", records, '\n', "positions:", positions);
                MainLoop();            
            }else{
                LogStatus("未连接状态!", new Date());
            }
            Sleep(1000);
        }
}

The results:img

You can see that if I have only one variety, and I call the GetPosition function, what I get is an array that contains only one element, and if I have multiple variety, what I get is an array that contains multiple elements.

  • Set the direction of operation, open, close (current position, previous position)

After the contract type is set, before the open position operation, the direction of operation must be set (unlike the spot one), we need another API function: SetDirection

SetDirection(Direction)	设置Buy或者Sell下单类型
Direction可以取buy, closebuy, sell, closesell四个参数, 传统期货多出closebuy_today,与closesell_today, 指平今仓,
默认为closebuy/closesell为平昨仓
对于CTP传统期货, 可以设置第二个参数"1"或者"2"或者"3", 分别指"投机", "套利", "套保", 不设置默认为投机
股票只支持buy与closebuy, 因为股票只能买跟平仓
exchange.SetMarginLevel(5);
exchange.SetDirection("buy");
exchange.Buy(1000, 2);
exchange.SetMarginLevel(5);
exchange.SetDirection("closebuy");
exchange.Sell(1000, 2);

The parameters for SetDirection are explained as follows:

  • 1. clickbuy button: This parameter is entered when calling SetDirection, and after calling it, the exchange.Buy function is called again, to proceed.More storesThe operation.
  • 2. sell button: This parameter is entered when calling SetDirection, and after calling it, the exchange.Sell function is called again, to proceed.Opened warehouseThe operation.
  • 3. closebuy button: Enter this parameter when calling SetDirection, and call the exchange.Sell function after the call, and proceed.Plain stockThe operation ((( can be seen to be the same as calling the exchange.Sell function, which can be distinguished by setting the operation direction by calling SetDirection before.Opened warehouseOrPlain stock)
  • 4. clickclosesell button: Enter this parameter when calling SetDirection, and call the exchange.Buy function again after calling it, to proceedFlat warehouseOperations. (also different from SetDirection. (buy more than one position)

Traditional futures have two more parameters:

  • 1. closebuy_today button: Use it to buy more stocks today.
  • 2. closesell_today button: used to close today's vacancy.

The default is two parameters:

  • 1. closebuy button: used to pay for yesterday's stock.
  • 2. closesell: used to clear yesterday's empty stock.

A: The data returned by the exchange will tell us the answer. In the data that gets the information about the holdings by calling GetPosition, there is a Type attribute that tells us whether the holdings are the current holdings or the previous holdings.

img

Come and try it, open the balance!

function main() {  // 这次为了方便重点看  开仓平仓操作,我们在回测系统中进行测试。
    var initAccount = exchange.GetAccount();   // 获取初始 账户信息
    var info = exchange.SetContractType("MA701");   //   设置我们要操作的合约  甲醇 
    var ticker = exchange.GetTicker();   // 先获取当前的行情 数据
    
    Log("initAccount:", initAccount);
    Log(info);
    
    // 开仓买入做多
    exchange.SetDirection("buy");
    exchange.Buy(ticker.Sell + 1, 1);  // 吃掉卖一价这个单子,  买入一手。
    
    Sleep(1000);
    
    // 获取一下持仓信息
    var positions = exchange.GetPosition();  // 获取持仓信息
    Log("当前所有持仓:", positions);
    
    //平仓
    var pos = null;
    for(var i = 0 ; i < positions.length ; i++){
        if(positions[i].ContractType == "MA701"){
            pos = positions[i];
        }
    }
    exchange.SetDirection("closebuy_today");
    exchange.Sell(ticker.Buy - 1, pos.Amount);
    
    positions = exchange.GetPosition();
    Log("当前所有持仓:", positions);
}

In the retesting system, the transaction fee is automatically deducted, and the collateral is also automatically returned to the account. And the retesting system does not distinguish between current and past positions. When writing a policy, it is best to write it as requested, so as not to change it again and again in real time.

img

  • Quickly master the commodity futures trading library

To make it easier for users to use, the platform has packaged an easy-to-use toolkit to create a template for commodity futures trading libraries. The source code is open, students who are interested can see the implementation and learn a lot of knowledge and ideas. Below, we'll take a look at some of the ease of use of the template. 1. Copy the template first.

img

2. Summarize the code, the template code itself contains the main function for testing, which can be run directly in the template test. After we copy the template, the existing template will appear in the template bar of the policy, which one needs to be added to the policy will be checked in the box in front of it.

img

Try using: The template hasMonotypicMulti-taskingThe two working models, which we first know about in the primary, are mono-varieties and use methods.

function main() {
    var p = $.NewPositionManager();   // $.NewPositionManager() 是 商品期货交易类库 模板的导出函数(接口)。
                                      // 该函数的作用是返回一个对象,用该对象管理开仓、平仓等操作。
    p.OpenShort("MA701", 1);          // p对象 的方法 OpenShort() , 功能是开空仓, 参数传入 合约代码 ,数量
                                      // 会根据当前行情的价格 开空仓。
    p.OpenShort("MA701", 1);          // 继续开空
    Log(p.GetPosition("MA701", PD_SHORT));   // 调用对象 p的 方法 GetPosition() ,传入合约代码, 合约类型, 找出相应的持仓,打印出来。

    Log(p.Account());
    Sleep(60000 * 10);                // 暂停一段时间
    p.CoverAll();                     // 调用 对象 p的方法 CoverAll() 把持仓全部平掉。
    LogProfit(p.Profit());            // 调用 对象 p的方法 Profit()  并打印 盈亏信息。
}

imgIn the template code, a function that starts with $ is a function that is exported to the template and can be called by other policies (provided that it has been added to the policy). The template also has many powerful functions, such as determining whether the variety is in trading time, multitasking, etc.

  • The future of digital currency

It supports BitVC, OKCoin, and 796.

  • Leverage can be modified using the SetMarginLevel function, 10, 20, which differs slightly from exchange to exchange.
SetMarginLevel(MarginLevel)	设置杆杠大小
设置Buy(多单)或者Sell(空单)的杆杠大小, MarginLevel有5, 10, 20 三个可选参数
796支持5,10,20,50三个选项, BitVC的LTC不支持20倍杠杆, OKCoin支持10倍和20倍
如: exchange.SetMarginLevel(5)
  • Contract varieties OKCoin futures have this_week, next_week, quarter. The contracts differ from exchange to exchange, see API documentation.

More

Quantitative exchangeCan you please add to the teaching section of the digital currency contract?

The Little DreamGood, new tutorial is in the works.