Skip to content

Commit f6259ed

Browse files
shinny-hongyanshinny-chenli
authored andcommitted
Update Version 3.9.3
1 parent a3dc039 commit f6259ed

24 files changed

Lines changed: 327 additions & 23 deletions

PKG-INFO

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
Metadata-Version: 2.1
22
Name: tqsdk
3-
Version: 3.9.2
3+
Version: 3.9.3
44
Summary: TianQin SDK
55
Home-page: https://www.shinnytech.com/tqsdk
66
Author: TianQin

doc/_ext/tqsdk_search.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# -*- coding: utf-8 -*-
2+
3+
import re
4+
5+
from sphinx.search.zh import SearchChinese
6+
7+
8+
class TqSdkSearchChinese(SearchChinese):
9+
"""Index both jieba tokens and whole text fragments for Chinese docs search."""
10+
11+
lang = 'tqsdk_zh'
12+
# Reuse Sphinx's built-in English stemmer implementation for Latin tokens.
13+
# `js_stemmer_rawcode = 'english-stemmer.js'` expects `EnglishStemmer`.
14+
language_name = 'English'
15+
_phrase_re = re.compile(r'\w+', re.UNICODE)
16+
17+
def split(self, input: str) -> list[str]:
18+
tokens = []
19+
tokens.extend(super().split(input))
20+
tokens.extend(self._phrase_re.findall(input))
21+
22+
seen = set()
23+
results = []
24+
for token in tokens:
25+
token = token.strip()
26+
if not token or token in seen:
27+
continue
28+
seen.add(token)
29+
results.append(token)
30+
return results

doc/_static/search_zh_dict.txt

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
TqSdk 100000
2+
TqApi 100000
3+
TqAccount 100000
4+
TqAuth 100000
5+
TqBacktest 100000
6+
TqChan 100000
7+
TqKq 100000
8+
TqKqStock 100000
9+
TqMultiAccount 100000
10+
TqNotify 100000
11+
TqReplay 100000
12+
TqRiskRule 100000
13+
TqRiskRuleError 100000
14+
TqSim 100000
15+
TqTradingUnit 100000
16+
TargetPosScheduler 100000
17+
TargetPosTask 100000
18+
DataDownloader 100000
19+
target_pos 100000
20+
quote 100000
21+
tick 100000
22+
快期账户 100000
23+
快期模拟 100000
24+
实盘交易 100000
25+
模拟交易 100000
26+
目标持仓 100000
27+
目标持仓模型 100000
28+
多策略 100000
29+
主连合约 100000
30+
连续合约 100000
31+
历史行情 100000
32+
数据下载 100000
33+
行情数据 100000
34+
盘口行情 100000
35+
K线 100000
36+
Tick 100000
37+
Quote 100000

doc/ai_editor/skills/tqsdk-trading-and-data/SKILL.md

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
name: tqsdk-trading-and-data
3-
description: "Explain, implement, or debug TqSdk Python workflows for wait_update or is_changing update loops, market data retrieval, historical download, account type selection, funds or positions or orders or trades, field meanings, order placement or cancelation, target-position tools, simulation, backtest, and common TqSdk errors. Use when a request mentions TqSdk, TqApi, TqAuth, TqAccount, TqKq, TqKqStock, TqSim, TqSimStock, TqMultiAccount, TqBacktest, TargetPosTask, TargetPosScheduler, DataDownloader, market data, K-line, tick, historical data, positions, trades, orders, account data, order placement, cancelation, position adjustment, field meanings, wait_update, debugging, \u884c\u60c5, K\u7ebf, \u5386\u53f2\u6570\u636e, \u6301\u4ed3, \u6210\u4ea4, \u59d4\u6258, \u8d26\u6237, \u4e0b\u5355, \u64a4\u5355, \u8c03\u4ed3, \u5b57\u6bb5\u542b\u4e49, or \u62a5\u9519."
3+
description: "Explain, implement, or debug TqSdk Python workflows for wait_update or is_changing update loops, market data retrieval, historical download, account type selection, funds or positions or orders or trades, field meanings, order placement or cancelation, target-position tools, TqScenario margin trials, real-account margin-rate lookup, margin or risk-ratio what-if analysis, simulation, backtest, and common TqSdk errors. Use when a request mentions TqSdk, TqApi, TqAuth, TqAccount, TqKq, TqKqStock, TqSim, TqSimStock, TqMultiAccount, TqBacktest, TqScenario, TargetPosTask, TargetPosScheduler, DataDownloader, margin rate, margin calculation, risk ratio, scenario trial, market data, K-line, tick, historical data, positions, trades, orders, account data, order placement, cancelation, position adjustment, field meanings, wait_update, debugging, \u884c\u60c5, K\u7ebf, \u5386\u53f2\u6570\u636e, \u4fdd\u8bc1\u91d1\u7387, \u4fdd\u8bc1\u91d1, \u98ce\u9669\u5ea6, \u573a\u666f\u8bd5\u7b97, \u6301\u4ed3, \u6210\u4ea4, \u59d4\u6258, \u8d26\u6237, \u4e0b\u5355, \u64a4\u5355, \u8c03\u4ed3, \u5b57\u6bb5\u542b\u4e49, or \u62a5\u9519."
44
---
55

66
# TqSdk Trading and Data
@@ -15,11 +15,12 @@ Read only the references needed for the user's question.
1515
2. Read [references/market-data.md](references/market-data.md) for `get_quote`, `get_kline_serial`, `get_tick_serial`, contract discovery, symbol metadata, and `DataDownloader`.
1616
3. Read [references/account-type-matrix.md](references/account-type-matrix.md) for `TqAccount`, `TqKq`, `TqKqStock`, `TqSim`, `TqSimStock`, OTG account classes, and `TqMultiAccount`.
1717
4. Read [references/accounts-and-trading.md](references/accounts-and-trading.md) for account, position, order, and trade getters plus multi-account getter patterns.
18-
5. Read [references/order-functions-and-position-tools.md](references/order-functions-and-position-tools.md) for `insert_order`, `cancel_order`, `TargetPosTask`, `TargetPosScheduler`, and advanced execution helpers.
19-
6. Read [references/object-fields.md](references/object-fields.md) when the user asks what fields mean on `Quote`, K-line or tick rows, `Account`, `Position`, `Order`, `Trade`, or their stock variants.
20-
7. Read [references/simulation-and-backtest.md](references/simulation-and-backtest.md) for local sim, Quick sim, stock sim, backtest, and cross-account backtest limits.
21-
8. Read [references/error-faq.md](references/error-faq.md) when the user asks about common TqSdk failures, confusing behavior, or exception messages.
22-
9. Read [references/example-map.md](references/example-map.md) when you want a repository-backed example or doc page to imitate.
18+
5. Read [references/scenario-and-margin.md](references/scenario-and-margin.md) for `TqScenario`, real-account margin-rate lookup, margin occupancy calculation, risk-ratio what-if analysis, and limited built-in margin discount rules.
19+
6. Read [references/order-functions-and-position-tools.md](references/order-functions-and-position-tools.md) for `insert_order`, `cancel_order`, `TargetPosTask`, `TargetPosScheduler`, and advanced execution helpers.
20+
7. Read [references/object-fields.md](references/object-fields.md) when the user asks what fields mean on `Quote`, K-line or tick rows, `Account`, `Position`, `Order`, `Trade`, or their stock variants.
21+
8. Read [references/simulation-and-backtest.md](references/simulation-and-backtest.md) for local sim, Quick sim, stock sim, backtest, and cross-account backtest limits.
22+
9. Read [references/error-faq.md](references/error-faq.md) when the user asks about common TqSdk failures, confusing behavior, or exception messages.
23+
10. Read [references/example-map.md](references/example-map.md) when you want a repository-backed example or doc page to imitate.
2324

2425
## Core Rules
2526

@@ -38,6 +39,12 @@ Read only the references needed for the user's question.
3839
- `TargetPosTask` for target net position.
3940
- `TargetPosScheduler` plus `twap_table` or `vwap_table` from `tqsdk.algorithm` for scheduled execution.
4041
- Mention `InsertOrderTask` and `InsertOrderUntilAllTradedTask` as internal or advanced helpers, not the default answer.
42+
10. Use `TqScenario` for synchronous what-if margin and risk trials, not for live order placement. It is futures-only, single-account, and updates the trial snapshot immediately after each call.
43+
11. Explain the margin-rate source in every `TqScenario` answer:
44+
- `account=None` or `TqSim()` uses `Quote` margin data.
45+
- `TqAccount(...)` or `TqKq()` queries account-specific rates synchronously and may fall back to `Quote` margin if lookup fails.
46+
12. Treat margin discounts conservatively. Reuse one `TqScenario` object for step-by-step trial actions, and do not promise broker-specific preferential rules beyond the limited built-in rules modeled by TqSdk.
47+
13. Preserve exchange-specific close semantics in `TqScenario`. For SHFE or INE futures, keep `CLOSE` versus `CLOSETODAY` consistent with the imported position snapshot.
4148

4249
## Answering Style
4350

@@ -46,3 +53,4 @@ Read only the references needed for the user's question.
4653
- Name the exact API the user should call next.
4754
- If behavior differs in live trading, Quick sim, local sim, stock sim, or backtest, say so explicitly.
4855
- If the answer depends on a common pitfall, state the pitfall directly instead of burying it in examples.
56+
- If the answer uses `TqScenario`, say what snapshot goes into `positions`, what balance goes into `init_balance`, and whether the result comes from quote margin or account-specific margin rates.
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
interface:
22
display_name: "TqSdk Trading and Data"
3-
short_description: "Guide TqSdk data, account, order, and strategy workflows"
4-
default_prompt: "Use $tqsdk-trading-and-data to explain or implement a TqSdk data, account, order, strategy, or debugging task."
3+
short_description: "Guide TqSdk data, trading, margin, and strategy workflows"
4+
default_prompt: "Use $tqsdk-trading-and-data to explain or implement a TqSdk data, trading, scenario, or debugging task."

doc/ai_editor/skills/tqsdk-trading-and-data/references/accounts-and-trading.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
Read [account-type-matrix.md](account-type-matrix.md) first if the user is still choosing an account class.
1818
Read [object-fields.md](object-fields.md) when the user asks what a field means.
1919
Read [order-functions-and-position-tools.md](order-functions-and-position-tools.md) for `insert_order`, `cancel_order`, and `TargetPosTask`.
20+
Read [scenario-and-margin.md](scenario-and-margin.md) for `TqScenario`, real-account margin-rate lookup, and margin or risk what-if analysis.
2021

2122
## Core Getters
2223

doc/ai_editor/skills/tqsdk-trading-and-data/references/error-faq.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,11 +103,13 @@ Typical cause:
103103

104104
- the user expects polling behavior from a blocking update loop
105105
- the code is running in Jupyter and hangs waiting for updates
106+
- the first real-account `TqScenario` margin-rate lookup is waiting for OTG data synchronously
106107

107108
Fix:
108109

109110
- use `deadline=...` when the user truly needs a timeout
110111
- in Jupyter, prefer simple synchronous examples and explicitly mention the limitation
112+
- if the code uses `TqScenario(account=TqAccount(...))` or `TqScenario(account=TqKq())`, explain that the first uncached margin-rate lookup may block while TqSdk fetches the account-specific rate
111113

112114
## Backtest Behavior Looks Wrong
113115

doc/ai_editor/skills/tqsdk-trading-and-data/references/example-map.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,19 @@ Use this file when you need a concrete repository example or doc page before wri
5151
- `doc/advanced/scheduler.rst`
5252
- `TargetPosScheduler`
5353

54+
## If The User Asks About Margin Trials Or `TqScenario`
55+
56+
- `tqsdk/scenario/tqscenario.py`
57+
- public `TqScenario` docstrings and method semantics
58+
- `design/scenario.md`
59+
- scenario design, margin-rate source rules, and discount-model notes
60+
- `tqsdk/test/scenario/test_scenario.py`
61+
- runnable what-if patterns for margin and risk changes
62+
- `tqsdk/test/scenario/test_pre_insert_order.py`
63+
- real-account margin-rate lookup examples and expected values
64+
- `doc/reference/tqsdk.scenario.rst`
65+
- public API reference entry
66+
5467
## If The User Asks About Account Types Or Multi-Account
5568

5669
- `doc/usage/shinny_account.rst`

doc/ai_editor/skills/tqsdk-trading-and-data/references/order-functions-and-position-tools.md

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
- `cancel_order`
77
- `TargetPosTask`
88
- `TargetPosScheduler`
9-
- Choosing between manual order control and target-position control
9+
- Choosing between manual order control, target-position control, and `TqScenario`
1010

1111
## Table Of Contents
1212

@@ -15,6 +15,7 @@
1515
- When to use manual orders
1616
- `TargetPosTask`
1717
- `TargetPosScheduler`
18+
- `TqScenario` versus live execution tools
1819
- Advanced helpers beyond the default answer
1920
- Stock limitations
2021

@@ -141,6 +142,18 @@ from tqsdk.algorithm import twap_table, vwap_table
141142

142143
It still depends on continuous `wait_update()` calls and must not be mixed with `TargetPosTask` or manual `insert_order()` for the same workflow.
143144

145+
## `TqScenario` Versus Live Execution Tools
146+
147+
Use `TqScenario` when the user wants synchronous trial calculation for futures margin or risk changes without sending live orders.
148+
149+
Read [scenario-and-margin.md](scenario-and-margin.md) when the request is about:
150+
151+
- how many lots can still be opened
152+
- how much margin can be released by reducing positions
153+
- what margin or risk ratio becomes after changing positions, balance, or margin rates
154+
155+
Do not route live execution requests to `TqScenario`.
156+
144157
## Advanced Helpers Beyond The Default Answer
145158

146159
These exist, but should not be the first answer unless the user is already using them:
Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
# Scenario And Margin
2+
3+
## Use This Reference For
4+
5+
- `TqScenario`
6+
- Real-account margin-rate lookup
7+
- Margin occupancy and risk-ratio what-if analysis
8+
- Questions such as "how many lots can I still open?" or "how much margin will I release?"
9+
10+
## Table Of Contents
11+
12+
- When to choose `TqScenario`
13+
- Core APIs
14+
- Snapshot inputs
15+
- Margin-rate sources
16+
- Limited margin discount behavior
17+
- Common patterns
18+
- Boundaries
19+
- Repository sources
20+
21+
## When To Choose `TqScenario`
22+
23+
Use `TqScenario` when the user wants synchronous "what if" analysis against a snapshot of current futures positions and funds.
24+
25+
Typical requests:
26+
27+
- max lots under a margin budget
28+
- how many lots to close to free a target amount of margin
29+
- margin or risk ratio after opening or reducing multiple futures symbols
30+
- risk ratio after changing a futures margin rate
31+
- risk ratio after keeping positions unchanged but changing starting equity
32+
33+
Prefer live-order helpers such as `insert_order()` or `TargetPosTask` only when the user wants execution, not trial calculation.
34+
35+
## Core APIs
36+
37+
- `TqScenario(api, account=None, positions=None, init_balance=10000000.0)`
38+
- `scenario_insert_order(symbol, direction, offset, volume, limit_price)`
39+
- `scenario_set_margin_rate(symbol, margin_rate)`
40+
- `scenario_get_account()`
41+
42+
Important behavior:
43+
44+
- `TqScenario` creates an internal futures trading snapshot and updates it immediately after each `scenario_*` call.
45+
- `scenario_insert_order()` matches immediately at the passed `limit_price`.
46+
- `scenario_insert_order()` does not model partial fills. Read `status`, `volume_left`, and `last_msg`.
47+
- `scenario_get_account()` returns only `margin` and `risk_ratio`.
48+
- `scenario_set_margin_rate()` updates one futures symbol inside the scenario and recalculates account margin from `pre_settlement`.
49+
50+
## Snapshot Inputs
51+
52+
- Pass `positions=api.get_position()` to start from the current futures position snapshot.
53+
- Pass one `Position` object if the user only wants to trial one symbol.
54+
- Omit `positions` to start from an empty futures account.
55+
- Use `init_balance` to choose the starting equity for the scenario snapshot.
56+
- When the user wants "current positions plus extra capital", read `balance = api.get_account().balance` first, then pass `init_balance=balance + extra`.
57+
58+
Keep all related trial actions inside one `TqScenario` object so the margin and risk calculations stay cumulative.
59+
60+
## Margin-Rate Sources
61+
62+
- `account=None` creates an internal `TqSim()` and uses `Quote.margin` together with `pre_settlement`.
63+
- `account=TqAccount(...)` or `account=TqKq()` triggers account-specific margin-rate lookup through the internal pre-insert-order path.
64+
- The first uncached real-account lookup is synchronous and may spend time inside `wait_update()` before returning.
65+
- If account-specific lookup fails, TqSdk falls back to `Quote.margin`.
66+
- CTP margin-rate lookup is flow-controlled at roughly one new symbol per second.
67+
- `scenario_set_margin_rate()` is the right API when the user explicitly wants to shock one futures symbol to a hypothetical new margin rate.
68+
69+
## Limited Margin Discount Behavior
70+
71+
- Reuse one `TqScenario` object and apply actions step by step when the margin result depends on net exposure after each trade.
72+
- The reported margin change can reflect the limited built-in margin discount rules already modeled by TqSdk's simulator, including supported futures hedge and cross-period cases.
73+
- Do not promise exact broker settlement logic for every custom preferential rule. If the user asks about a broker-specific rule that TqSdk does not model, say the result is only the built-in approximation.
74+
75+
## Common Patterns
76+
77+
### "How many lots can I still open under a 200000 margin budget?"
78+
79+
```python
80+
from tqsdk import TqApi, TqAuth, TqAccount, TqScenario
81+
82+
account = TqAccount("broker", "acct", "pwd")
83+
api = TqApi(account=account, auth=TqAuth("quick_user", "quick_pass"))
84+
symbol = "SHFE.rb2611"
85+
quote = api.get_quote(symbol)
86+
positions = api.get_position()
87+
88+
with TqScenario(api, account=account, positions=positions) as s:
89+
base_margin = s.scenario_get_account().margin
90+
lots = 0
91+
while True:
92+
order = s.scenario_insert_order(symbol, "BUY", "OPEN", 1, quote.last_price)
93+
if order.status == "FINISHED" and order.volume_left > 0:
94+
break
95+
lots += 1
96+
if s.scenario_get_account().margin - base_margin > 200000:
97+
s.scenario_insert_order(symbol, "SELL", "CLOSETODAY", 1, quote.last_price)
98+
lots -= 1
99+
break
100+
```
101+
102+
### "What happens if the futures margin rate becomes 15%?"
103+
104+
```python
105+
account = TqAccount("broker", "acct", "pwd")
106+
api = TqApi(account=account, auth=TqAuth("quick_user", "quick_pass"))
107+
positions = api.get_position()
108+
109+
with TqScenario(api, account=account, positions=positions) as s:
110+
before = s.scenario_get_account()
111+
s.scenario_set_margin_rate("SHFE.rb2611", 0.15)
112+
after = s.scenario_get_account()
113+
```
114+
115+
### "What happens if I add 100000 equity and keep positions unchanged?"
116+
117+
```python
118+
account = TqAccount("broker", "acct", "pwd")
119+
api = TqApi(account=account, auth=TqAuth("quick_user", "quick_pass"))
120+
positions = api.get_position()
121+
balance = api.get_account().balance
122+
123+
with TqScenario(api, account=account, positions=positions, init_balance=balance + 100000) as s:
124+
after = s.scenario_get_account()
125+
```
126+
127+
## Boundaries
128+
129+
- `TqScenario` currently supports futures only.
130+
- `TqScenario` currently supports one account snapshot at a time.
131+
- `TqScenario` is synchronous. Run it outside the hot `wait_update()` loop when possible.
132+
- `scenario_insert_order()` always fills immediately at the passed price inside the trial snapshot.
133+
- `scenario_insert_order()` and `scenario_get_account()` return reduced objects, not the full live `Order` or `Account`.
134+
- Preserve `CLOSE` versus `CLOSETODAY` when closing SHFE or INE positions imported from a live snapshot.
135+
- Do not recommend `TqScenario` for stock trading, option pricing shocks, or arbitrary custom broker discount tables that the simulator does not model.
136+
137+
## Repository Sources
138+
139+
- `tqsdk/scenario/tqscenario.py`
140+
- `design/scenario.md`
141+
- `doc/reference/tqsdk.scenario.rst`
142+
- `tqsdk/test/scenario/test_scenario.py`
143+
- `tqsdk/test/scenario/test_pre_insert_order.py`
144+
- `tqsdk/api.py`

0 commit comments

Comments
 (0)