QT implements simple ctp program

1. Development environment

  qt5.9.9 msvc2017 environment (mingw cannot run) and the built-in Qt Creator, the penetrating API provided in the previous issue, and the qcustomplot library is imported to achieve chart effects.

  This program draws on the video from station b: BV1ET4y1L7iN.

2. Effect display

 

 

  Realizes the display of market prices, commissions, transactions, positions, contracts, and other tables, as well as user login and order operations. Note: The login data is fixed and can be expanded by yourself. You can check your orders and other operations by downloading the express trading platform. After the program is running, if there is no data in the market table, please use another usable port to log in to the program (which can be viewed on the express trading platform).

3. Code introduction

   Quote: The Comprehensive Transaction Platform (CTP) is a futures brokerage business management system specially developed for futures companies. It consists of three major systems: trading, risk control and settlement. After importing the API interface provided in the previous issue, we can implement the market conditions, commissions, transactions, positions, and contracts respectively.

All interfaces of CTP are divided into two types: Spi and Api, which are briefly explained here.

API: The Api class provides various functions for trading/quotes, but these require us to actively make requests to the server.

SPI: The Spi class provides transaction/market-related callback interfaces. We need toinherit this class and overloadthese interfaces to obtain response data.

  API can be understood as a type of encapsulated functions provided to us in the previous issue. We only need to call these functions directly, most of which can be used without rewriting. SPI embodies the idea of ​​​​a callback. After our api is called, spi will return something, and we can use these return values ​​to determine whether the api is executing normally.

  For example, when we need to log in to the market, we need to use the RspUserLogin function. After the function is executed, the corresponding OnRspUserLogin function will be automatically called. We can use the return value to determine whether the login is successful.

  To implement the market part, we need to create a class to inheritCThostFtdcMdSpi and rewrite some functions.

  For example, when the client communicates with the trading backend, we canOnFrontConnected重写来监听连接是否成功。

 

  At the same time, you can log in to the market. Next, we implement the acquisition of market information by rewriting OnRtnDepthMarketData. Since it involves information communication between multiple classes, after obtaining the data, we splice it into a string separated by, and write a The signal sendData with a string parameter is used to transmit the data, which is obtained in the main class and printed on the form.

 

   The trading part is a bit more complicated. But let us start from the client login, follow the same example, we rewrite the tradeapiOnFrontConnected 函数,来在信号连  接的时候就实现其登录,以下的userid也就是注册时得到的investorID可以修改为您自己的investorID。

    To realize the login of personal account, we write a slot function on the login button, write the correct account password, and the login is successful.

  After logging in, the program will immediately obtain the contract, position, account and other information. There will be no big difference in the writing methods of the three. Let us take the contract as an example.

  We need to rewrite the OnRspQryInstrument function and use multiple strings to accept the data in pInstrument. Next, we splice it into a string. Same as above. Since it involves information communication between multiple classes, we get the data. Then concatenate it into a string separated by and write a signal sendDataHy with string parameters to transmit the data. At the same time, we also need to store the data in a double string array for later use. Finally , split the string in the main class and write it to the table.

   There is not much difference in the operations of contracts, positions, and account forms. Once you learn about contracts, you can draw inferences from one example. We have come to a very important step, placing and canceling orders, please continue reading the following content.

    To implement this function, we need to write a function ourselves and actively call it. We found the ReqOrderInsert function and found that this function can be used to place orders, so we can define a ReqOrderInsert function with the same name ourselves, but it has parameters for us to call it.

 

  

void CTraderSpi::ReqOrderInsert(QString dm,QString lx,int lots,double price)
{
    CThostFtdcInputOrderField ord ;
    memset(&ord, 0, sizeof(ord));
    strcpy_s(ord.BrokerID, "9999");
    strcpy_s(ord.InvestorID, "204925");
    strcpy_s(ord.ExchangeID, "SHFE");
    strcpy_s(ord.InstrumentID,dm.toStdString().data() );


    sprintf(ORDER_REF,"%d",iRequestID);
    strcpy_s(ord.OrderRef,ORDER_REF );

    ord.OrderPriceType = THOST_FTDC_OPT_LimitPrice;//限价

    if(lx =="kd"){
        ord.Direction = THOST_FTDC_D_Buy;//买 DIRECTION
        ord.CombOffsetFlag[0] = THOST_FTDC_OF_Open;//开
    }
    else if(lx =="pd"){
        ord.Direction = THOST_FTDC_D_Buy;//买 DIRECTION
        ord.CombOffsetFlag[0] = THOST_FTDC_OF_CloseToday;//开
    }
    else if(lx =="kk"){
        ord.Direction = THOST_FTDC_D_Sell;//买 DIRECTION
        ord.CombOffsetFlag[0] = THOST_FTDC_OF_Open;//开
    }
    else if(lx =="pk"){
        ord.Direction = THOST_FTDC_D_Sell;//买 DIRECTION
        ord.CombOffsetFlag[0] = THOST_FTDC_OF_CloseToday;//开
    }


    ord.CombHedgeFlag[0] = THOST_FTDC_HF_Speculation;//投机
    ord.LimitPrice = price;
    ord.VolumeTotalOriginal = lots;
    ord.TimeCondition = THOST_FTDC_TC_GFD;///当日有效
    ord.VolumeCondition = THOST_FTDC_VC_AV;///任意数量
    ord.MinVolume = 1;
    ord.ContingentCondition = THOST_FTDC_CC_Immediately;
    ord.StopPrice = 0;
    ord.ForceCloseReason = THOST_FTDC_FCC_NotForceClose;
    ord.IsAutoSuspend = 0;
    pUserApi->ReqOrderInsert(&ord, ++iRequestID);
};

   The function looks very long, but many of them have relatively fixed values. For us novices, copy and paste is enough. The parameter lx is used to distinguish whether to open long, close long, or open short, close short, as As a non-financial major, I don’t know much about this. You can search it by yourself to expand it. After writing the ord data, we call ReqOrderInsert with ord as the parameter to place an order.

  After the order is placed, data will appear in the order. If the order has not yet been completed, we can implement the order cancellation function. Then in the order form, we need to implement a column that recognizes the click after clicking and a cancellation button appears. Single option, click Cancel order and we can cancel the order.

  code show as below: 

void MainWindow::OnWTmenu(const QPoint &pt)
{
    qDebug()<<"onwtmenu";
    QMenu menu;
    menu.addAction(ui->actioncd);
    menu.exec(ui->tableWT_2->mapToGlobal(pt));

}

void MainWindow::ct()
{
    if(ui->tableWT_2->rowCount()==0)return;
    int i = ui->tableWT_2->currentIndex().row();
    QString wth = ui->tableWT_2->item(i,7)->text();
    QString jys = ui->tableWT_2->item(i,8)->text();
    QString brokerid = "9999";

    qDebug()<<wth;
    qDebug()<<jys;

    if(wth == "")return;

    ptdUserSpi->ReqOrderAction(brokerid,wth,jys);
}

  Canceling an order is relatively simple. After we get the number of clicked lines, we get the order number and exchange through the number of lines. Finally, we add the broker ID to call the order cancellation. After the order is successfully canceled, its status in the order table will be Change to order cancellation, at the same time, you can also log in to the express trading platform to check whether the transaction has been canceled successfully.

4. Code acquisition

 Account registration:    sinmow  (You may not be able to log in during some time periods).

api acquisition:first half technology official service  ,sinmow.

gitee: QTctp: QT simply implements the ctp program.

Recommended reading articles:CTP study notes_EmoryHuang’s blog-CSDN blog

Guess you like

Origin blog.csdn.net/weixin_56108590/article/details/126690726