Skip to content
All library documents

Using a CLI Trading Engine to Query and Trade CTP Futures

Notebook vn.py

Summary

This notebook demonstrates a basic command-line workflow for operating a trading engine through a CTP gateway. It loads connection settings, initializes the engine, and connects to the server. The example then queries available contracts, account balances, positions, and active orders, before subscribing to a specified futures contract and retrieving its latest tick data.

The final steps show how to submit a buy order, inspect that order by its identifier, and request its cancellation. These examples illustrate the sequence of common gateway and order-management operations, but they do not explain the underlying API behavior, configuration fields, or error handling. The notebook presents no trading signal, execution analysis, or performance results, and its contract and order parameters are illustrative rather than a recommendation. Anyone adapting the workflow would need to supply valid connection settings and confirm contract, quantity, price, and account requirements for their own environment.

Key ideas

  • The notebook connects a command-line trading engine to a CTP gateway using loaded settings.
  • It demonstrates queries for contracts, accounts, positions, and active orders.
  • Market data can be subscribed to and retrieved for a selected futures contract.
  • A buy order can be submitted, looked up by its identifier, and canceled.
  • The examples do not describe error handling or validate any trading strategy.

Tags

Full text
# 连接到服务器


该Jupyter Notebook用于展示如何使用ScriptTraderApp模块,在CLI命令行下进行交易指令的调用

```python
from vnpy.trader.utility import load_json

from vnpy_scripttrader import init_cli_trading
from vnpy_ctp import CtpGateway
```

```python
# 连接到服务器
setting = load_json("connect_ctp.json")
engine = init_cli_trading([CtpGateway])
engine.connect_gateway(setting, "CTP")
```

```python
# 查询所有合约
engine.get_all_contracts(use_df=True)
```

```python
# 查询资金
engine.get_all_accounts(use_df=True)
```

```python
# 查询持仓
engine.get_all_positions(use_df=True)
```

```python
# 查询活动委托
engine.get_all_active_orders(use_df=True)
```

```python
# 订阅行情
engine.subscribe(["sc2209.INE"])
```

```python
# 查询行情
engine.get_tick("sc2209.INE", use_df=True)
```

```python
# 委托下单
vt_orderid = engine.buy("sc2209.INE", 32, 1000)
print(vt_orderid)
```

```python
# 查询特定委托
engine.get_order(vt_orderid)
```

```python
# 委托撤单
engine.cancel_order(vt_orderid)
```

```python

```

Shown in full with attribution under the source's licence. Licence: MIT

This summary was written by Stratmill's research agent from the original; it is not a copy of the source.