buy_open 开多(买开)
函数原型
buy_open(
order_book_id:
str,
style:
str,
price:
float,
volume:
int =
1,
amount:
float,
hedge_flag:
bool =
False,
order_queue:
bool =
False,
slithermethod:
bool =
False,
account:
str =
'',
repeat:
int =
0,
min_volume:
int =
1,
serial_id:
int ) ->
int
参数
参数 | 类型 | 缺省 | 必填 | 说明 |
order_book_id | str | - | Y | 合约代码 |
style | str | - | Y | 交易类型 - "Market" 市价 - "Limit" 限价 - "fak" 立即成交剩余自动撤销指令 - "fok" 立即全部成交否则自动撤销指令 - "Stop" 停损 - "ThisClose" 对手价 - "DBEST" 对方最优价优先 - "WBEST" 本方最优价优先 |
price | float | 0 | Y | 交易价格,取决于 style 类型 - "Limit": 买入价格 - "fak"/"fok"/"DBEST"/"WBEST":保护价 - "Stop"作为 止损价格, - "Market"/"ThisClose": 填 0 |
volume | int | 1 | N | 交易数量,与amount 互斥,仅可指定其一 - 单位:期货为手,股票为股,即100的整数倍。 - 参数范围【>=1】 |
amount | float | - | N | 交易金额,指定后自动换算为交易数量。与volume互斥,仅可指定其一; 使用时,以关键字形式传递 |
hedge_flag | bool | False | N | 交易标志, - 期货:True(保值),False(投机) - 股票:True(融资),False(普通) - 期权:True(备兑),False(非备兑) 注:该标志对于回测无效 |
order_queue | bool | False | N | 是否为队列单,该标志对于回测无效 |
slithermethod | bool | False | N | 是否使用大单处理下单模式, 该标志对于回测无效 |
account | str | "" 或'' | N | 指定交易账户,(如 "user123")。(即空字符串"" 或者'' )未指定或者省略此字段时,代表使用默认登录账户,该标志对于回测无效 |
repeat | int | 0 | N | 是否允许重复下单。 repeat=0:在同一K线上,同一行代码的相同下单语句仅允许下单一次,后续重复下单将被过滤,返回 repeat=1:允许重复下单,系统不限制同一K线周期内的重复下单行为。 |
min_volume | int | 1 | N | 可选参数,使用fak指令时,用于指定的最小成交数量,省略时默认为1 |
serial_id | int | - | N | 下单序列号,由系统自动生成,无需用户操作 |
返回值
状态 | 返回值 | 返回类型 | 说明 |
成功 | order_id | int | 订单ID,时交易订单的唯一标识,可用于交易过程追踪、仓位风险管理等 |
0 | int | 当order_queue或slithermethod参数为True时,其返回值恒为0 |
失败 | None | NoneType | 当order_queue或slithermethod参数为True时,下单失败返回空值 |
-1 | int | 下单委托失败,具体失败原因可以根据交易日志判定 |
-2 | int | 因 repeat=0 且在同一K线周期内触发禁止重复下单限制,订单被过滤。属正常逻辑,无需作为错误处理。 例如,1分钟K线周期内,策略每5秒执行,若某行下单条件反复满足,首次下单后,后续再尝试下单时返回 -2。 |
范例
buy_open(order_book_id="SQRB00", style="Limit", price=3200, volume=2 )
buy_open(order_book_id="SQRB00", style="Limit", price=3200, volume=2, account="" )
1
2
3
4
buy_open(order_book_id="SQRB00", style="Market", volume=1)
buy_open(order_book_id="SQRB00", style="Market", price=0, volume=1)
1
2
3
buy_open("SQRB00", "Limit", price=3200, amount=10500.0, account="004471", repeat=0 )
1
2
buy_open("SQAG00", "fak", price=3150, volume = 10, account="", min_volume=2)
1
2
buy_open(order_book_id="SH600000", style="Limit", price=10.5, volume=100, repeat=1)
1
2
order_id = buy_open(order_book_id="SQRB00", style="Limit", price=3200, volume=2 )
if order_id not in (None, -1, -2, 0):
print(f"下单成功,订单号为 {order_id}")
else:
if order_id is None or order_id == -1:
print("下单失败,请检查交易日志")
elif order_id == -2:
print("单根K重复下单被过滤")
elif order_id == 0:
print("队列单/大单模式返回值为0,无订单追踪信息")
1
2
3
4
5
6
7
8
9
10
11
symbols = ['AG00', 'RB00', 'CU00']
for symbol in symbols:
order_id = buy_open(order_book_id=symbol, style='ThisClose', price=0, volume=1)
if order_id not in (None, -1, -2, 0):
print(f"下单成功,订单号为 {order_id}")
else:
if order_id is None or order_id == -1:
print("下单失败,请检查交易日志")
elif order_id == -2:
print("单根K重复下单被过滤")
elif order_id == 0:
print("队列单/大单模式返回值为0,无订单追踪信息")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
sell_close 平多(卖平)
函数原型
sell_close(
order_book_id:
str,
style:
str,
price:
float,
volume:
int =
1,
amount:
float,
hedge_flag:
bool =
False,
order_queue:
bool =
False,
slithermethod:
bool =
False,
account:
str =
'',
repeat:
int =
0,
min_volume:
int =
1,
serial_id:
int ) ->
int
参数
参数 | 类型 | 缺省 | 必填 | 说明 |
order_book_id | str | - | Y | 合约代码 |
style | str | - | Y | 交易类型 - "Market" 市价 - "Limit" 限价 - "fak" 立即成交剩余自动撤销指令 - "fok" 立即全部成交否则自动撤销指令 - "Stop" 停损 - "ThisClose" 对手价 - "DBEST" 对方最优价优先 - "WBEST" 本方最优价优先 |
price | float | 0 | Y | 交易价格,取决于 style 类型 - "Limit": 卖出价格 - "fak"/"fok"/"DBEST"/"WBEST":保护价 - "Stop"作为 止损价格, - "Market"/"ThisClose": 填 0 |
volume | int | 1 | N | 交易数量,与amount 互斥,仅可指定其一 - 单位:期货为手,股票为股,即100的整数倍。 - 参数范围【>=1】 |
amount | float | - | N | 交易金额,指定后自动换算为交易数量。与volume互斥,仅可指定其一; 使用时,以关键字形式传递 |
hedge_flag | bool | False | N | 交易标志, - 期货:True(保值),False(投机) - 股票:True(融资),False(普通) - 期权:True(备兑),False(非备兑) 注:该标志对于回测无效 |
order_queue | bool | False | N | 是否为队列单,该标志对于回测无效 |
slithermethod | bool | False | N | 是否使用大单处理下单模式, 该标志对于回测无效 |
account | str | "" 或'' | N | 指定交易账户,(如 "user123")。(即空字符串"" 或者'' )未指定或者省略此字段时,代表使用默认登录账户,该标志对于回测无效 |
repeat | int | 0 | N | 是否允许重复下单。 repeat=0:在同一K线上,同一行代码的相同下单语句仅允许下单一次,后续重复下单将被过滤,返回 repeat=1:允许重复下单,系统不限制同一K线周期内的重复下单行为。 |
min_volume | int | 1 | N | 可选参数,使用fak指令时,用于指定的最小成交数量,省略时默认为1 |
serial_id | int | - | N | 下单序列号,由系统自动生成,无需用户操作 |
返回值
状态 | 返回值 | 返回类型 | 说明 |
成功 | order_id | int | 订单ID,时交易订单的唯一标识,可用于交易过程追踪、仓位风险管理等 |
0 | int | 当order_queue或slithermethod参数为True时,其返回值恒为0 |
失败 | None | NoneType | 当order_queue或slithermethod参数为True时,下单失败返回空值 |
-1 | int | 下单委托失败,具体失败原因可以根据交易日志判定 |
-2 | int | 因 repeat=0 且在同一K线周期内触发禁止重复下单限制,订单被过滤。属正常逻辑,无需作为错误处理。 例如,1分钟K线周期内,策略每5秒执行,若某行下单条件反复满足,首次下单后,后续再尝试下单时返回 -2。 |
范例
sell_close("SQRB00", "Limit", 3600 , 2)
sell_close(order_book_id="SQRB00", style="Limit", price=3600, volume=1 )
1
2
3
sell_close(order_book_id="SQRB00", style="Limit", price=3200, volume=1, account="004471" )
1
2
sell_close(order_book_id="SQRB00", style="Market", volume=1, account="004471")
sell_close(order_book_id="SQRB00", style="Market", price=0, volume=1, account="004471")
1
2
3
buy_open("SQRB00", "Limit", price=3200, amount=10500.0, account="004471", repeat=0 )
1
2
sell_close("SQAG00", "fOk", price=3150, volume = 10, account="")
1
2
buy_open(order_book_id="SQRB00", style="Limit", price=3200, volume=1, order_queue=True)
1
2
symbols = ['AG00', 'RB00', 'CU00']
for symbol in symbols:
sysbol_obj = get_portfolio (order_book_id="ZJIF00", type=0, account="", calc=True)
sysbol_holidng = sysbol_obj.buy_quantity
print(f"{symbol} 可用仓位:{sysbol_holidng}")
if symbol_holding >= 1:
sell_close(order_book_id=symbol, style='ThisClose', price=0, volume=sysbol_holidng)
if order_id is None or order_id == -1:
print(f"{symbol} 下单失败,请检查交易日志")
elif order_id == 0:
print(f"{symbol} 队列单/大单模式返回值为0,无订单追踪信息")
else:
print(f"下单成功,{symbol} 订单号为 {order_id}")
else:
print(f"{symbol} 无可用多头仓位,跳过平仓")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
sell_open 开空(卖开/融券开仓)
函数原型
sell_open(
order_book_id:
str,
style:
str,
price:
float,
volume:
int =
1,
amount:
float,
hedge_flag:
bool =
False,
order_queue:
bool =
False,
slithermethod:
bool =
False,
account:
str =
'',
repeat:
int =
0,
min_volume:
int =
1,
serial_id:
int ) ->
int
参数
参数 | 类型 | 缺省 | 必填 | 说明 |
order_book_id | str | - | Y | 合约代码 |
style | str | - | Y | 交易类型 - "Market" 市价 - "Limit" 限价 - "fak" 立即成交剩余自动撤销指令 - "fok" 立即全部成交否则自动撤销指令 - "Stop" 停损 - "ThisClose" 对手价 - "DBEST" 对方最优价优先 - "WBEST" 本方最优价优先 |
price | float | 0 | Y | 交易价格,取决于 style 类型 - "Limit": 买入价格 - "fak"/"fok"/"DBEST"/"WBEST":保护价 - "Stop"作为 止损价格, - "Market"/"ThisClose": 填 0 |
volume | int | 1 | N | 交易数量,与amount 互斥,仅可指定其一 - 单位:期货为手,股票为股,即100的整数倍。 - 参数范围【>=1】 |
amount | float | - | N | 交易金额,指定后自动换算为交易数量。与volume互斥,仅可指定其一; 使用时,以关键字形式传递 |
hedge_flag | bool | False | N | 交易标志, - 期货:True(保值),False(投机) - 股票:True(融资),False(普通) - 期权:True(备兑),False(非备兑) 注:该标志对于回测无效 |
order_queue | bool | False | N | 是否为队列单,该标志对于回测无效 |
slithermethod | bool | False | N | 是否使用大单处理下单模式, 该标志对于回测无效 |
account | str | "" 或'' | N | 指定交易账户,(如 "user123")。(即空字符串"" 或者'' )未指定或者省略此字段时,代表使用默认登录账户,该标志对于回测无效 |
repeat | int | 0 | N | 是否允许重复下单。 repeat=0:在同一K线上,同一行代码的相同下单语句仅允许下单一次,后续重复下单将被过滤,返回 repeat=1:允许重复下单,系统不限制同一K线周期内的重复下单行为。 |
min_volume | int | 1 | N | 可选参数,使用fak指令时,用于指定的最小成交数量,省略时默认为1 |
serial_id | int | - | N | 下单序列号,由系统自动生成,无需用户操作 |
返回值
状态 | 返回值 | 返回类型 | 说明 |
成功 | order_id | int | 订单ID,时交易订单的唯一标识,可用于交易过程追踪、仓位风险管理等 |
0 | int | 当order_queue或slithermethod参数为True时,其返回值恒为0 |
失败 | None | NoneType | 当order_queue或slithermethod参数为True时,下单失败返回空值 |
-1 | int | 下单委托失败,具体失败原因可以根据交易日志判定 |
-2 | int | 因 repeat=0 且在同一K线周期内触发禁止重复下单限制,订单被过滤。属正常逻辑,无需作为错误处理。 例如,1分钟K线周期内,策略每5秒执行,若某行下单条件反复满足,首次下单后,后续再尝试下单时返回 -2。 |
范例
sell_open(order_book_id="SQRB00", style="Limit", price=3200, volume=2 )
sell_open(order_book_id="SQRB00", style="Limit", price=3200, volume=2, account="" )
1
2
3
4
sell_open(order_book_id="SQRB00", style="Market", volume=1)
sell_open(order_book_id="SQRB00", style="Market", price=0, volume=1)
1
2
3
sell_open("SQRB00", "Limit", price=3200, amount=10500.0, account="004471", repeat=0 )
1
2
sell_open("SQAG00", "fak", price=3150, volume = 10, account="", min_volume=2)
1
2
sell_open(order_book_id="SH600000", style="Limit", price=10.5, volume=100, repeat=1)
1
2
order_id = sell_open(order_book_id="SQRB00", style="Limit", price=3200, volume=2 )
if order_id is None or order_id == -1:
print("下单失败,请检查交易日志")
elif order_id == -2:
print("单根K重复下单被过滤")
elif order_id == 0:
print("队列单/大单模式返回值为0,无订单追踪信息")
else:
print(f"下单成功,订单号为 {order_id}")
1
2
3
4
5
6
7
8
9
10
symbols = ['AG00', 'RB00', 'CU00']
for symbol in symbols:
order_id = sell_open(order_book_id=symbol, style='ThisClose', price=0, volume=1)
if order_id is None or order_id == -1:
print(f"{symbol} 下单失败,请检查交易日志")
elif order_id == -2:
print(f"{symbol} 重复下单被过滤")
elif order_id == 0:
print(f"{symbol} 队列单/大单模式返回值为0,无订单追踪信息")
else:
print(f"下单成功,{symbol} 订单号为 {order_id}")
1
2
3
4
5
6
7
8
9
10
11
12
13
buy_close 平空(买平/买券还券)
函数原型
buy_close(
order_book_id:
str,
style:
str,
price:
float,
volume:
int =
1,
amount:
float,
hedge_flag:
bool =
False,
order_queue:
bool =
False,
slithermethod:
bool =
False,
account:
str =
'',
repeat:
int =
0,
min_volume:
int =
1,
serial_id:
int ) ->
int
参数
参数 | 类型 | 缺省 | 必填 | 说明 |
order_book_id | str | - | Y | 合约代码 |
style | str | - | Y | 交易类型 - "Market" 市价 - "Limit" 限价 - "fak" 立即成交剩余自动撤销指令 - "fok" 立即全部成交否则自动撤销指令 - "Stop" 停损 - "ThisClose" 对手价 - "DBEST" 对方最优价优先 - "WBEST" 本方最优价优先 |
price | float | 0 | Y | 交易价格,取决于 style 类型 - "Limit": 卖出价格 - "fak"/"fok"/"DBEST"/"WBEST":保护价 - "Stop"作为 止损价格, - "Market"/"ThisClose": 填 0 |
volume | int | 1 | N | 交易数量,与amount 互斥,仅可指定其一 - 单位:期货为手,股票为股,即100的整数倍。 - 参数范围【>=1】 |
amount | float | - | N | 交易金额,指定后自动换算为交易数量。与volume互斥,仅可指定其一; 使用时,以关键字形式传递 |
hedge_flag | bool | False | N | 交易标志, - 期货:True(保值),False(投机) - 股票:True(融资),False(普通) - 期权:True(备兑),False(非备兑) 注:该标志对于回测无效 |
order_queue | bool | False | N | 是否为队列单,该标志对于回测无效 |
slithermethod | bool | False | N | 是否使用大单处理下单模式, 该标志对于回测无效 |
account | str | "" 或'' | N | 指定交易账户,(如 "user123")。(即空字符串"" 或者'' )未指定或者省略此字段时,代表使用默认登录账户,该标志对于回测无效 |
repeat | int | 0 | N | 是否允许重复下单。 repeat=0:在同一K线上,同一行代码的相同下单语句仅允许下单一次,后续重复下单将被过滤,返回 repeat=1:允许重复下单,系统不限制同一K线周期内的重复下单行为。 |
min_volume | int | 1 | N | 可选参数,使用fak指令时,用于指定的最小成交数量,省略时默认为1 |
serial_id | int | - | N | 下单序列号,由系统自动生成,无需用户操作 |
返回值
状态 | 返回值 | 返回类型 | 说明 |
成功 | order_id | int | 订单ID,时交易订单的唯一标识,可用于交易过程追踪、仓位风险管理等 |
0 | int | 当order_queue或slithermethod参数为True时,其返回值恒为0 |
失败 | None | NoneType | 当order_queue或slithermethod参数为True时,下单失败返回空值 |
-1 | int | 下单委托失败,具体失败原因可以根据交易日志判定 |
-2 | int | 因 repeat=0 且在同一K线周期内触发禁止重复下单限制,订单被过滤。属正常逻辑,无需作为错误处理。 例如,1分钟K线周期内,策略每5秒执行,若某行下单条件反复满足,首次下单后,后续再尝试下单时返回 -2。 |
范例
buy_close("SQRB00", "Limit", 3600 , 2)
buy_close(order_book_id="SQRB00", style="Limit", price=3600, volume=1 )
1
2
3
buy_close(order_book_id="SQRB00", style="Limit", price=3200, volume=1, account="004471" )
1
2
buy_close(order_book_id="SQRB00", style="Market", volume=1, account="004471")
buy_close(order_book_id="SQRB00", style="Market", price=0, volume=1, account="004471")
1
2
3
buy_close("SQRB00", "Limit", price=3200, amount=10500.0, account="004471", repeat=0 )
1
2
buy_close("SQAG00", "fOk", price=3150, volume = 10, account="")
1
2
buy_close(order_book_id="SQRB00", style="Limit", price=3200, volume=1, order_queue=True)
1
2
symbols = ['AG00', 'RB00', 'CU00']
for symbol in symbols:
sysbol_obj = get_portfolio (order_book_id="ZJIF00", type=0, account="", calc=True)
sysbol_holidng = sysbol_obj.buy_quantity
print(f"{symbol} 可用仓位:{sysbol_holidng}")
if symbol_holding >= 1:
buy_close(order_book_id=symbol, style='ThisClose', price=0, volume=sysbol_holidng)
if order_id is None or order_id == -1:
print(f"{symbol} 下单失败,请检查交易日志")
elif order_id == 0:
print(f"{symbol} 队列单/大单模式返回值为0,无订单追踪信息")
else:
print(f"下单成功,{symbol} 订单号为 {order_id}")
else:
print(f"{symbol} 无可用多头仓位,跳过平仓")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
get_orders 获取当日委托订单
获取当日委托订单。其数据来自账户栏的委托记录
中的记录。
函数原型
get_orders(
order_book_id:
str,
type:
int,
account:
str =
'', ) ->
List[Order]
参数
参数 | 类型 | 缺省 | 必填 | 说明 |
order_book_id | str | - | Y | 合约代码,支持传入关键词"all",表示全部合约 |
type | int | - | Y | 0:只取未成交订单 1:取全部订单 |
account | str | "" | N | 指定交易帐号,如果不填,则使用默认登录账号 |
返回值
状态 | 返回值 | 返回类型 | 说明 |
成功 | list[Order] | list | 返回符合查询条件的委托订单对象列表,每个元素为 Order 对象 |
失败 | None | NoneType | 没有符合条件的订单或者查询失败,返回None |
属性 | 类型 | 说明 |
order_id | int | 唯一标识订单的ID |
order_book_id | str | 合约代码 |
datetime | datetime.datetime | 订单创建时间 |
side | str | 订单方向 "buy" 买:"sell" 卖 |
price | float | 订单价格,仅在限价单有效;市价单返回 0 |
quantity | int | 订单数量 |
filled_quantity | int | 已成交数量 |
unfilled_quantity | int | 未成交数量 |
type | str | 订单类型 - "limit"限价 - "market"市价 - "fak"立即成交剩余自动撤销指令 - "fok"立即全部成交否则自动撤销指令 - "DBEST" 对方最优价优先 - "WBEST" 本方最优价优先 |
trade_price | float | 成交价格(仅当为"tradeing"时有效) |
trade_quantity | int | 本次成交数量(仅当为"tradeing"时有效) |
status | str | 订单状态: - "submitted"已报单未成交 - "tradeing"已成交 - "filled"全部成交 - "cancelled"已撤单 - "inactive"无效单 - "connected"已连接 - "disconnected"连接断开 |
message | str | 订单状态文字说明 |
position_effect | str | 开平标志 "open"开仓 "close"平仓 |
sign | int | 交易标志 对于期货品种 0投机 1保值 对于股票 0普通 1融资 对于期权 0非备兑 1备兑 |
account | str | 交易账户 |
system_id | str | 柜台返回的系统编号 |
范例
id_list = get_orders("RB00", 1)
if not(id_list == None):
for order in id_list:
print(f"订单ID={order.order_id}, 合约代码={order.order_book_id}, "
f"创建时间={order.datetime.strftime('%Y-%m-%d %H:%M:%S')}, 订单方向={order.side}, "
f"订单价格={order.price}, 订单数量={order.quantity}, 已成交数量={order.filled_quantity}, "
f"未成交数量={order.unfilled_quantity}, 订单类型={order.type}, 成交价格={order.trade_price}, "
f"成交数量={order.trade_quantity}, 订单状态={order.status}, 状态说明={order.message}, "
f"开平标志={order.position_effect}, 交易标志={order.sign}, 交易账户={order.account}, "
f"系统编号={order.system_id}")
1
2
3
4
5
6
7
8
9
10
11
orders = get_orders(order_book_id="all", type=1)
stats = {}
if orders:
for order in orders:
contract = order.order_book_id
if contract not in stats:
stats[contract] = {
"total_quantity": 0,
"filled_quantity": 0,
"unfilled_quantity": 0
}
stats[contract]["total_quantity"] += order.quantity
stats[contract]["filled_quantity"] += order.filled_quantity
stats[contract]["unfilled_quantity"] += order.unfilled_quantity
print("今日各合约交易统计:")
for contract, data in stats.items():
print(f"合约: {contract}, 委托总量: {data['total_quantity']} 手, 已成交: {data['filled_quantity']} 手, 未成交: {data['unfilled_quantity']} 手")
else:
print("今日无任何订单")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from PythonApi import *
from datetime import datetime
import csv
def after_trading(context):
orders = get_orders(order_book_id="all", type=0)
csv_file = "D:\\unfilled_orders"
headers = ["订单ID", "合约代码", "创建时间", "方向","开平", "价格", "委托数量", "未成交数量", "订单类型", "账户"]
with open(csv_file, mode="w", newline="", encoding="utf-8-sig") as file:
writer = csv.writer(file)
writer.writerow(headers)
if orders:
for order in orders:
writer.writerow([
order.order_id,
order.order_book_id,
order.datetime.strftime("%Y-%m-%d %H:%M:%S"),
order.side,
order.position_effect,
order.price,
order.quantity,
order.unfilled_quantity,
order.type,
order.account
])
print(f"未成交订单已保存到 {csv_file}")
else:
print("今日没有未成交订单,已生成空 CSV 文件")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
get_orders_id 获取当日指定id的委托订单
获取当日指定id的委托订单 。
函数原型
get_orders_id(
order_id:
int,
account:
str =
'', ) ->
Order
参数
参数 | 类型 | 缺省 | 必填 | 说明 |
order_id | int | - | Y | 唯一标识订单的id |
account | str | '' | N | 指定具体的交易帐号,若不指定帐号,则取默认登录帐号 |
返回值
状态 | 返回值 | 返回类型 | 说明 |
成功 | Order对象 | order | 返回指定委托订单对象 |
失败 | None | NoneType | 没有符合条件的订单或者查询失败,返回None |
属性 | 类型 | 说明 |
order_id | int | 唯一标识订单的ID |
order_book_id | str | 合约代码 |
datetime | datetime.datetime | 订单创建时间 |
side | str | 订单方向 "buy" 买:"sell" 卖 |
price | float | 订单价格,仅在限价单有效;市价单返回 0 |
quantity | int | 订单数量 |
filled_quantity | int | 已成交数量 |
unfilled_quantity | int | 未成交数量 |
type | str | 订单类型 - "limit"限价 - "market"市价 - "fak"立即成交剩余自动撤销指令 - "fok"立即全部成交否则自动撤销指令 - "DBEST" 对方最优价优先 - "WBEST" 本方最优价优先 |
trade_price | float | 成交价格(仅当为"tradeing"时有效) |
trade_quantity | int | 本次成交数量(仅当为"tradeing"时有效) |
status | str | 订单状态: - "submitted"已报单未成交 - "tradeing"已成交 - "filled"全部成交 - "cancelled"已撤单 - "inactive"无效单 - "connected"已连接 - "disconnected"连接断开 |
message | str | 订单状态文字说明 |
position_effect | str | 开平标志 "open"开仓 "close"平仓 |
sign | int | 交易标志 对于期货品种 0投机 1保值 对于股票 0普通 1融资 对于期权 0非备兑 1备兑 |
account | str | 交易账户 |
system_id | str | 柜台返回的系统编号 |
范例
def init(context):
context.code_orders = {}
def handle_bar(context):
code = 'SQAG00'
kline_data = history_bars(code, 1, '1M', ['open','CLOSE'])
if len(kline_data) > 0 and kline_data[0][0]<kline_data[0][1]:
order_id = buy_open(order_book_id=code, style='ThisClose', price=0, serial_id=1)
if order_id > 0:
if code not in context.code_orders:
context.code_orders[code] = []
context.code_orders[code].append(order_id)
print(f"下单成功,合约: {code}, 订单 ID: {order_id}")
print(context.code_orders)
for code, order_ids in context.code_orders.items():
for order_id in order_ids:
order = get_orders_id(order_id)
if order is not None:
print(f"订单ID: {order_id}, 合约: {code}, 状态: {order.status}")
print(f"已成交数量: {order.filled_quantity}, 未成交数量: {order.unfilled_quantity}")
else:
print(f"订单ID: {order_id} 查询失败(可能已撤单或未找到)")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def init(context):
context.code_orders = {}
context.codes = context.universe
def handle_bar(context):
for code in context.codes:
kline_data = history_bars(code, 1, '1M', ['OPEN','CLOSE'])
print(code)
if len(kline_data) > 0 :
order_id = buy_open(order_book_id=code, style='ThisClose', price=0,serial_id = 1)
if order_id not in (None, -1, -2, 0):
if code not in context.code_orders:
context.code_orders[code] = []
context.code_orders[code].append(order_id)
print(f"下单成功,合约: {code}, 订单 ID: {order_id}")
print(context.code_orders)
print("----------------------------------------------")
for code, order_ids in context.code_orders.items():
for order_id in order_ids:
order = get_orders_id(order_id)
if order is not None:
print(f"订单ID: {order_id}, 合约: {code}, 状态: {order.status}")
print(f"已成交数量: {order.filled_quantity}, 未成交数量: {order.unfilled_quantity}")
else:
print(f"订单ID: {order_id} 查询失败(可能已撤单或未找到)")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
cancel_order 撤销指定order_id订单
撤销指定order_id的订单 。(仅策略交易状态时有效,"backtest"回测 和 "paper_trading"模式)
函数原型
cancel_order(
order_id:
int,
queue:
bool =
False,
account:
str =
'' ) ->
NoneType
参数
参数 | 类型 | 缺省 | 必填 | 说明 |
order_id | int | - | Y | 唯一标识订单的id, 必须填 |
queue | bool | False | N | 指示是否为队列单 |
account | str | '' | N | 指定具体的交易帐号,若不指定帐号,则取默认登录帐号 |
返回值
状态 | 返回值 | 返回类型 | 说明 |
任何状态 | None | NoneType | 无论撤单成功还是失败,都返回None ,可以结合get_orders_id 方法确认订单状态 |
范例
from datetime import datetime
current_time = datetime.now().replace(microsecond=0)
if not(id_list == None):
order = get_orders_id(id_list[-1].order_id)
if order and order.status == 'submitted':
time_passed = current_time - order.datetime
if time_passed.total_seconds() > 30:
cancel_order(order.order_id)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from datetime import datetime
current_time = datetime.now().replace(microsecond=0)
pending_orders = get_orders(order_book_id="all", type=0)
if pending_orders:
for order_info in pending_orders:
order_detail = get_orders_id(order_info.order_id) if hasattr(order_info, 'order_id') else None
if order_detail and order_detail.status == 'submitted':
order_duration = (current_time - order_detail.datetime.replace(microsecond=0)).total_seconds()
print(f"[订单检查] 合约:{order_detail.order_book_id} 单号:{order_detail.order_id} "
f"挂单:{order_duration:.1f}s 未成交:{order_detail.unfilled_quantity}")
if order_duration > 30:
cancel_order(order_detail.order_id)
print(f" → 超时撤单({order_duration:.1f}s)")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
if not hasattr(context, 'pending_cancels'):
context.pending_cancels = {}
pending_orders = get_orders(order_book_id="all", type=0)
if pending_orders:
for order in pending_orders:
order_detail = get_orders_id(order.order_id)
if order_detail and order_detail.status == 'submitted':
elapsed = (datetime.now() - order_detail.datetime).total_seconds()
if elapsed > 30 and order.order_id not in context.pending_cancels:
cancel_order(order.order_id)
context.pending_cancels[order.order_id] = {
'request_time': datetime.now(),
'symbol': order.order_book_id
}
print(f"撤单请求已发送 | 订单 {order.order_book_id} #{order.order_id}")
for order_id in list(context.pending_cancels.keys()):
order = get_orders_id(order_id)
if not order:
print(f"撤单确认成功 | 订单 {context.pending_cancels[order_id]['symbol']} #{order_id} 不存在")
del context.pending_cancels[order_id]
elif order.status == 'cancelled':
print(f"撤单确认成功 | 订单 {context.pending_cancels[order_id]['symbol']} #{order_id} 已撤单")
del context.pending_cancels[order_id]
elif order.status == 'filled':
print(f"撤单终止 | 订单 {context.pending_cancels[order_id]['symbol']} #{order_id} 已完全成交")
del context.pending_cancels[order_id]
else:
print(f"撤单待确认 | 订单 {context.pending_cancels[order_id]['symbol']} #{order_id} 当前状态: {order.status}")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from datetime import datetime
if not hasattr(context, 'pending_cancels'):
context.pending_cancels = {}
pending_orders = get_orders(order_book_id="all", type=0)
if pending_orders:
for order in pending_orders:
order_detail = get_orders_id(order.order_id)
if order_detail and order_detail.status == 'submitted':
elapsed = (datetime.now() - order_detail.datetime).total_seconds()
if elapsed > 30 and order.order_id not in context.pending_cancels:
cancel_order(order.order_id)
context.pending_cancels[order.order_id] = {
'request_time': datetime.now(),
'retry_count': 0,
'symbol': order.order_book_id
}
print(f"撤单请求已发送 | 订单 {order.order_book_id} #{order.order_id}")
for order_id in list(context.pending_cancels.keys()):
record = context.pending_cancels[order_id]
if (datetime.now() - record['request_time']).seconds < 10:
continue
order = get_orders_id(order_id)
if not order:
print(f"撤单确认成功 | 订单 {record['symbol']} #{order_id} 不存在")
del context.pending_cancels[order_id]
elif order.status == 'cancelled':
print(f"撤单确认成功 | 订单 {record['symbol']} #{order_id} 已撤单")
del context.pending_cancels[order_id]
elif order.status == 'filled':
print(f"撤单终止 | 订单 {record['symbol']} #{order_id} 已完全成交")
del context.pending_cancels[order_id]
else:
record['retry_count'] += 1
if record['retry_count'] > 3:
print(f"撤单失败 | 订单 {record['symbol']} #{order_id} 仍处于 {order.status} 状态")
del context.pending_cancels[order_id]
else:
print(f"撤单待确认 | 订单 {record['symbol']} #{order_id} 当前状态: {order.status}")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
get_traders 获取当日成交订单
获取当日成交订单对象
函数原型
get_traders(
order_book_id:
int,
account:
str =
'' ) ->
list[trader]
参数
参数 | 类型 | 缺省 | 必填 | 说明 |
order_book_id | str | - | Y | 合约代码,或者为"all"全部合约 |
account | str | '' | N | 指定具体的交易帐号,若不指定帐号,则取默认登录帐号 |
返回值
状态 | 返回值 | 返回类型 | 说明 |
成功 | list[trader对象] | list | 返回符合查询条件的委托订单对象列表,每个元素为 Order 对象 |
失败 | None | NoneType | 没有符合条件的成交订单或者查询失败,返回None |
属性 | 类型 | 说明 |
order_id | int | 订单ID |
order_book_id | str | 合约代码 |
datetime | datetime.datetime | 订单创建时间 |
side | str | 订单方向 "buy"买,"sell"卖 |
filled_quantity | int | 成交数量 |
type | str | 订单类型: - "limit"限价 - "market"市价 - "fak"立即成交剩余自动撤销指令 - "fok"立即全部成交否则自动撤销指令 - "DBEST" 对方最优价优先 - "WBEST" 本方最优价优先 |
trade_price | float | 成交价格 |
position_effect | str | 开平标志 "open"开仓 "close"平仓 |
sign | int | 交易标志 对于期货品种 0投机 1保值 对于股票 0普通 1融资 对于期权 0非备兑 1备兑 |
system_id | str | 柜台返回的系统编号 |
范例
all_traders = get_traders(order_book_id="all")
if all_traders:
print(f"当日共有 {len(all_traders)} 笔成交记录:")
for trader in all_traders:
print(f"合约代码: {trader.order_book_id}")
print(f"买卖方向: {trader.side}")
print(f"成交数量: {trader.filled_quantity}")
print(f"成交价格: {trader.trade_price}")
print(f"成交时间: {trader.datetime.strftime('%Y-%m-%d %H:%M:%S')}")
print(f"订单类型: {trader.type}")
print(f"开平标志: {trader.position_effect}")
print(f"交易标志: {trader.sign}")
print(f"系统编号: {trader.system_id}")
print(f"订单ID: {trader.order_id}")
print("-" * 40)
else:
print("当日无成交记录")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
if_traders = get_traders(order_book_id="FU10")
if if_traders:
print(f"共有 {len(if_traders)} 笔成交:")
buy_open_volume = 0
buy_open_amount = 0
sell_open_volume = 0
sell_open_amount = 0
buy_close_volume = 0
buy_close_amount = 0
sell_close_volume = 0
sell_close_amount = 0
for trader in if_traders:
volume = trader.filled_quantity
amount = volume * trader.trade_price
if trader.side == 'buy' and trader.position_effect == 'open':
buy_open_volume += volume
buy_open_amount += amount
action = "买入开仓"
elif trader.side == 'sell' and trader.position_effect == 'open':
sell_open_volume += volume
sell_open_amount += amount
action = "卖出开仓"
elif trader.side == 'buy' and trader.position_effect == 'close':
buy_close_volume += volume
buy_close_amount += amount
action = "买入平仓"
elif trader.side == 'sell' and trader.position_effect == 'close':
sell_close_volume += volume
sell_close_amount += amount
action = "卖出平仓"
else:
action = "未知操作"
print(f"{action} {volume}手 @ {trader.trade_price} "
f"- 时间: {trader.datetime.strftime('%H:%M:%S')}")
print(f"--------------成交统计详情:------------------")
if buy_open_volume > 0:
print(f"买入开仓: {buy_open_volume}手 均价: {buy_open_amount/buy_open_volume:,.2f}元")
if sell_open_volume > 0:
print(f"卖出开仓: {sell_open_volume}手 均价: {sell_open_amount/sell_open_volume:,.2f}元")
if buy_close_volume > 0:
print(f"买入平仓: {buy_close_volume}手 均价: {buy_close_amount/buy_close_volume:,.2f}元")
if sell_close_volume > 0:
print(f"卖出平仓: {sell_close_volume}手 均价: {sell_close_amount/sell_close_volume:,.2f}元")
total_volume = (buy_open_volume - sell_close_volume) - (sell_open_volume - buy_close_volume)
print(f"净成交: {total_volume}手")
else:
print("无成交记录")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
MATCH_METHOD = 'system_id'
all_orders = get_orders("all",1)
all_traders = get_traders("all")
if all_orders and all_traders:
print(f"委托成交均价计算 (关联方式: {MATCH_METHOD}):")
print("=" * 70)
for order in all_orders:
if MATCH_METHOD == 'system_id':
related_traders = [t for t in all_traders if t.system_id == order.system_id]
else:
related_traders = [t for t in all_traders if t.order_id == order.order_id]
if related_traders:
total_quantity = sum(t.filled_quantity for t in related_traders)
total_amount = sum(t.filled_quantity * t.trade_price for t in related_traders)
avg_price = total_amount / total_quantity
print(f"{order.order_book_id} |{order.datetime} | {order.side}_{order.position_effect} {order.quantity}手")
print(f"关联方式: {MATCH_METHOD}")
if MATCH_METHOD == 'system_id':
print(f"系统ID: {order.system_id}")
else:
print(f"订单ID: {order.order_id}")
print(f"成交数量: {total_quantity}/{order.quantity}手")
print(f"成交均价: {avg_price:.2f}")
print(f"委托价格: {order.price} ")
for trader in related_traders:
print(f" → 成交{trader.filled_quantity}手 价格:{trader.trade_price}")
else:
print(f"委托#{order.order_id} | {order.order_book_id} | 无成交记录")
if MATCH_METHOD == 'system_id':
print(f"系统ID: {order.system_id}")
else:
print(f"订单ID: {order.order_id}")
print("-" * 50)
else:
print("无委托或成交记录")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
get_account 得到投资者账户信息
获取指定账户的资金、权益、保证金、状态等相关信息。
函数原型
get_account(
type:
int,
account:
str =
'' ) ->
list[Trader]
参数
参数 | 类型 | 缺省 | 必填 | 说明 |
type | int | - | Y | 账户信息类别, 参数同PEL |
account | str | '' | N | 指定具体的交易帐号,若不指定帐号,则取默认登录帐号 |
type | 说明 |
1 | 该函数返回常数,返回当前交易帐户ID(该函数返回字符串类型数值) |
2 | 账户类型,0 盈透 1 CTP 2 金仕达期货 3FIX接口 4恒生期货 5子账户 6其他柜台 255 无效账户 |
3 | 现金余额 |
4 | 浮动盈亏 |
5 | 盯市盈亏 |
6 | 当前交易帐户中的动态权益/资产值 |
19 | 当前可用资金 |
20 | 当前流动资产 |
26 | 上次结算准备金/期初余额 |
27 | 结算准备金/期初余额 |
28 | 占用保证金/证券市值 |
29 | 可取资金 |
30 | 平仓盈亏数额/回报卖出金额/融券盈亏(回测无效) |
31 | 手续费 |
32 | 入金金额/利息积数/融资市值 |
33 | 出金金额/当前余额 |
34 | 上次信用额度 |
35 | 上次质压 |
36 | 质压金额 |
37 | 信用额度 |
38 | 冻结保证金/禁取资产 |
39 | 冻结手续费/回报买入金额/融资盈亏 |
40 | 保底资金 |
41 | 返回交易网关名称,该函数返回字符串常数 |
42 | 空头保证金率(期货专有) |
43 | 多头保证金率(期货专有) |
44 | 融券市值 |
45 | 融券费用 |
46 | 融券利息 |
47 | 融资余额 |
48 | 融券余额 |
49 | 可用保证金 |
50 | 已用融资额 |
51 | 已用融券额 |
52 | 融资负债 |
53 | 返回当前交易账户是否处于有效状态,有效登录返回1,无效登录返回0。 建议对账户持仓或资金进行读取时首先调用该函数对账户有效性进行判断,以免出现误操作。(对IB外盘无效,仅限国内) |
返回值
状态 | 返回值 | 返回类型 | 说明 |
成功 | 具体数值,如 12345 ,1000.5 ,"CTP" | int / float / str | 返回相应账户信息数值 |
失败 | None | NoneType | 查询失败,返回None |
范例
account_id = get_account(1)
print(f"账户ID: {account_id} 类型: {type(account_id)}")
account_type = get_account(2)
print(f"账户类型: {account_type} 类型: {type(account_type)}")
cash_balance = get_account(3)
print(f"现金余额: {cash_balance} 类型: {type(cash_balance)}")
float_pnl = get_account(4)
print(f"浮动盈亏: {float_pnl} (类型: {type(float_pnl)}")
equity = get_account(6)
print(f"动态权益: {equity} 类型: {type(equity)}")
available_funds = get_account(19)
print(f"可用资金: {available_funds} 类型: {type(available_funds)}")
margin_used = get_account(28)
print(f"占用保证金: {margin_used} 类型: {type(margin_used)}")
frozen_margin = get_account(38)
print(f"冻结保证金: {frozen_margin} 类型: {type(frozen_margin)}")
is_valid = get_account(53)
print(f"账户是否有效: {is_valid} 类型: {type(is_valid)}")
if not is_valid:
print("当前账户无效,请检查登录状态!")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
get_account_book 得到当前登录所有账户列表
获取当前已登录的资金账户列表,含登录失败的无效账号。
函数原型
get_account_book()
list of str 账户列表
返回值
状态 | 返回值 | 返回类型 | 说明 |
成功 | list[str],如 "12345", "67890" | list[str] | 返回资金账户ID列表 |
失败 | [] | list | 未登录账户时返回空列表 |
范例
accounts = get_account_book()
print(f"当前已登录 {len(accounts)} 个资金账户:")
for i, account_id in enumerate(accounts, 1):
print(f"账户{i} : {account_id}")
1
2
3
4
all_accounts = get_account_book()
if all_accounts:
valid_accounts = []
invalid_accounts = []
for account_id in all_accounts:
is_valid = get_account(53, account=account_id)
if is_valid == 1:
valid_accounts.append(account_id)
else:
invalid_accounts.append(account_id)
print(f"总共 {len(all_accounts)} 个账户:")
print(f"有效账户 ({len(valid_accounts)} 个): {valid_accounts}")
print(f"无效账户 ({len(invalid_accounts)} 个): {invalid_accounts}")
else:
print("没有配置任何资金账户")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
isaccount 判断指定帐号是否是当前已登录有效帐号
isaccount(account)
判断指定帐号是否是当前已登录有效帐号
参数
参数 | 类型 | 说明 |
account | str | 指定具体的交易帐号,若不指定帐号,则取默认登录帐号 |
返回值
bool 账户已登录则返回True,否则返回False
范例
account=isaccount("351579")
1
2
get_portfolio 投资组合信息
get_portfolio (order_book_id, type, account, calc)
投资组合信息(股票+期货的混合)。
参数
参数 | 类型 | 说明 |
order_book_id | str | 合约代码,必填项 |
type | int | 指定查询类型, 必填项, 期货: 0表示投机, 1表示保值 ; 股票: 0表示普通, 1表示融资 ; 期权: 0表示非备兑 1表示备兑; 2表示全部类型, 该参数对回测无效 |
account | str | 指定具体的交易帐号,若不指定帐号,则取默认登录帐号, 该参数对回测无效 |
calc | bool | 指示是否自动减扣未成交平仓单,比如当有1手持仓,1手未成交平仓单,那么实际返回持仓数量为0。可不填,默认为True |
返回值
portfolio对象,失败返回 None
范例
portfolio=get_portfolio ("SQRB10", 2)
write_logging(str(portfolio.pnl))
1
2
3
get_portfolio_book 投资组合持仓品种
get_portfolio_book (type, account)
投资组合持仓品种
参数
参数 | 类型 | 说明 |
type | int | 指定查询类型, 必填项, 期货: 0表示投机, 1表示保值 ; 股票: 0表示普通, 1表示融资 ; 期权: 0表示非备兑 1表示备兑; 2表示全部类型, 该参数对回测无效 |
account | str | 指定具体的交易帐号,若不指定帐号,则取默认登录帐号, 该参数对回测无效 |
返回值
返回 list of str,若没有任何持仓,则返回一个空的list
范例
portfolio=get_portfolio_book (2, "5")
if 'SQRB00' in portfolio:
write_logging('已持仓')
else:
write_logging('未持仓')
1
2
3
4
5
6
7