# TCore Python API 快速安装说明

## **步骤 :**&#x20;

1. 执行安装 python-3.6.7-amd64.exe 及 pywin32-224.win-amd64-py3.6.exe&#x20;
2. 安装所需的其他套件 以系统管理员开启命令提示字元执行以下-- 切换至Package所在路径 ,\
   输入 py -3 -m pip install -r requirements.txt安裝

## [**pytho**n**安装文件(**&#x6309;此下载)](http://dl.icetech.com.cn/download/python_install.7z)

| **文件名**                         | **文件描述**           |
| ------------------------------- | ------------------ |
| python-3.6.7-amd64.exe          | python install exe |
| pywin32-224.win-amd64-py3.6.exe | python install exe |
| requirements.txt                | 其他套件               |

## [范例**文件(**&#x6309;此下载)](http://dl.icetech.com.cn/download/ZMQPython_Sample_20201228.7z)

| **文件名**         | **文件描述**                  |
| --------------- | ------------------------- |
| tcoreapi\_mq.py | TCore Python API 行情与交易函数库 |
| main\_zmq.py    | 行情交易连接与使用范例               |

## Initial 行情交易物件

```python
global g_TradeZMQ
global g_QuoteZMQ

g_QuoteZMQ = tcore_zmq("SystemName","ServiceKey")
g_TradeZMQ = tcore_zmq("SystemName","ServiceKey")
```

SystemName 填入 ZMQ、ServiceKey 填入8076c9867a372d2a9a814ae710c256e2

| **参数**     | 说明         |
| ---------- | ---------- |
| SystemName | TCore系统名称  |
| ServiceKey | 连线TCore ID |

## 连线 行情、交易物件

```python
q_data = g_QuoteZMQ.quote_connect("port")
t_data = g_TradeZMQ.trade_connect("port")
```

{% tabs %}
{% tab title="参数" %}

| **参数**       |        |
| ------------ | ------ |
| port         | 连线port |
| {% endtab %} |        |

{% tab title="说明" %}
Connect 时, 所需填入的 port 值 , 请搜寻 ZMQ log 中 \
\
关键字 \[INFO ] RepPort:&#x20;

TradeZMQService-YYYYMMDD.log 对应到 trade\_connect port

&#x20;QuoteZMQService-YYYYMMDD.log 对应到 quote\_connect port

以查看到的Port值来个别填入--

例如 :  trade\_connect("52208")&#x20;

&#x20;           quote\_connect("52238")
{% endtab %}
{% endtabs %}

## 取得SessionKey

之后呼叫行情交易function介面，均需帶入SessionKey

```python
global g_QuoteSession
global g_TradeSession

g_QuoteSession = q_data["SessionKey"]
g_TradeSession = t_data["SessionKey"]
```

## 创建callback线程

```python
#建立一个行情线程
t1=threading.Thread(target = quote_sub_th,args=(g_QuoteZMQ,q_data,))    
t1.start()

#创建一个交易线程
t2 = threading.Thread(target = trade_sub_th,args=(g_TradeZMQ,t_data["SubPort"],))
t2.start()
```

## 建立行情callback线程处理函数

```python
#行情callback线程处理函数
def quote_sub_th(obj,q_data,filter = ""):
    socket_sub = obj.context.socket(zmq.SUB)
    #socket_sub.RCVTIMEO=7000
    #print(sub_port)
    socket_sub.connect("tcp://127.0.0.1:%s" % q_data["SubPort"])
    socket_sub.setsockopt_string(zmq.SUBSCRIBE,filter)
    while(True):
        message = (socket_sub.recv()[:-1]).decode("utf-8")
        index =  re.search(":",message).span()[1]  # filter 
        symbol = message[:index-1]
        message = message[index:]
        message = json.loads(message)
        #for message in messages:
        if(message["DataType"] == "PING"):
            g_QuoteZMQ.QuotePong(g_QuoteSession)
        elif(message["DataType"]=="REALTIME"):
            OnRealTimeQuote(message["Quote"])
        elif(message["DataType"]=="GREEKS"):
            OnGreeks(message["Quote"])
        elif(message["DataType"]=="1K"):
            print("@@@@@@@@@@@@@@@@@@@@@@@",message)
            strQryIndex = ""
            while(True):
                History_obj = {
                    "Symbol": symbol,
                    "SubDataType":"1K",
                    "StartTime" : message["StartTime"],
                    "EndTime" : message["EndTime"],
                    "QryIndex" : strQryIndex
                }
                s_history = obj.get_history(q_data["SessionKey"],History_obj)
                historyData = s_history["HisData"]
                if len(historyData) == 0:
                    break

                last = ""
                for data in historyData:
                    last = data
                    print("历史行情：Time:%s, Volume:%s, QryIndex:%s" % (data["Time"], data["Volume"], data["QryIndex"]))
                
                strQryIndex = last["QryIndex"]
                    
    return
```

## 建立交易callback线程处理函数

```python
#交易callback线程处理函数  
def trade_sub_th(obj,sub_port,filter = ""):
    socket_sub = obj.context.socket(zmq.SUB)
    #socket_sub.RCVTIMEO=5000
    socket_sub.connect("tcp://127.0.0.1:%s" % sub_port)
    socket_sub.setsockopt_string(zmq.SUBSCRIBE,filter)
    while True:
        message =  socket_sub.recv()
        if message:
            message = json.loads(message[:-1])
            #print("in trade message",message)
            if(message["DataType"] == "PING"):
                g_TradeZMQ.TradePong(g_TradeSession)
            elif(message["DataType"] == "ACCOUNTS"):
                for i in message["Accounts"]:
                    OnGetAccount(i)
            elif(message["DataType"] == "EXECUTIONREPORT"):
                OnexeReport(message["Report"]) 
            elif(message["DataType"] == "FILLEDREPORT"):
                RtnFillReport(message["Report"])
```

## 行情与交易连线Ping/Pong维持

* [ ] 于行情callback线程处理函数，接收message\["DataType"]="PING"，请呼叫[g\_QuoteZMQ.QuotePong(g\_QuoteSession)](https://algomaster.gitbook.io/tcore-api/tcoreapi_mq.py#quotepong)回复，以维持行情连线。
* [ ] 于交易callback线程处理函数，接收message\["DataType"]="PING"，请呼叫[g\_TradeZMQ.TradePong(g\_TradeSession)](https://algomaster.gitbook.io/tcore-api/tcoreapimq.py-jiao-yi-1#tradepong)回复，以维持交易连线。
* [ ] Ping/Pong于1分钟内持续丢失，将失去该连线。
