如何从Excel中获取数据并委托
<h4><strong>简要说明</strong></h4>
<ul>
<li>可使用os的readlines函数读取已填写好的csv格式的委托数据,并通过ths_api包中提供的cmd进行下单。下面以读取如下表所示的csv格式的Excel表格为例,进行说明:</li>
</ul>
<h4><strong>委托数据表格</strong></h4>
<table>
<thead>
<tr>
<th style="text-align: left;">买卖方向</th>
<th style="text-align: left;">证券代码</th>
<th>委托价格</th>
<th>委托数量</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">buy</td>
<td style="text-align: left;">000001</td>
<td>16.45</td>
<td>100</td>
</tr>
<tr>
<td style="text-align: left;">sell</td>
<td style="text-align: left;">000001</td>
<td>zxjg</td>
<td>100</td>
</tr>
</tbody>
</table>
<h4><strong>操作步骤</strong></h4>
<ul>
<li>在“当前工作目录\script\我的策略\配置文件”位置新建Excel文件,在Excel中编辑好如上表的委托数据,并用csv格式保存;</li>
<li>用记事本打开刚保存的csv文件,并点击“文件-另存为”,在弹窗的下方修改保存的编码格式为UTF-8;
(如程序中的open函数的encoding='GBK',可以省略该步骤,但在Python编辑器中打开再次编辑csv文件时,中文会乱码)</li>
</ul>
<p><img src="https://www.showdoc.cc/server/api/common/visitfile/sign/ebdc7473bf5314c849c3b4188493b9a9?showdoc=.jpg" alt="" /></p>
<ul>
<li>运行如下的示例代码,获得的运行结果如下;</li>
<li>之后需要修改csv文件内的委托数据时,直接在Python策略编辑器中找到对应目录文件打开编辑即可(如果找不到文件请退出交易系统再重新登录交易),修改完成后,系统会自动进行保存。</li>
</ul>
<h4><strong>示例代码</strong></h4>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from ths_api import *
import os
basket = 'test2.csv'
with open(os.getcwd() + '\\script\\我的策略\\配置文件\\' + basket, 'r', encoding='UTF-8') as f:
print(basket)
lines = f.readlines() #按行读取csv文件中的信息
for line in lines:
wt = line.split(',') #每行的委托数据按逗号分隔放在列表wt中
if '\n' in wt[-1]: #对于每行最后一个数据,如果csv文件自动增加了换行符
wt[-1] = wt[-1][0:-1] #去除每行最后一个数据的换行符
if not wt[1].isnumeric():
continue
else:
ret = xd.cmd('%s %s %s %s' % (wt[0], wt[1], wt[2], wt[3]))
print(ret)</code></pre>
<h4><strong>运行结果</strong></h4>
<p>程序输出如下,并且触发相应的委托提示框。</p>
<pre><code>tips=send buy code:000001 price:16.45 amount:100
test2.csv
tips=您的买入委托已成功提交,合同编号:1257259596。
tips=send sell code:000001 price:17.20 amount:100
{'retMsg': '您的买入委托已成功提交,合同编号:1257259596。', 'htbh': '1257259596', 'retCode': '0'}
tips=您的卖出委托已成功提交,合同编号:1257280076。
{'retMsg': '您的卖出委托已成功提交,合同编号:1257280076。', 'htbh': '1257280076', 'retCode': '0'}</code></pre>