DolphinDB Skill
One skill, two modes:
- Runtime — run bash/Python snippets against the user's live DolphinDB
server (patched connection info below).
- Reference — offline knowledge base for syntax, engines, plugins,
error codes, and best practices (Routing Table below).
All content targets DolphinDB Server 3.00+ and its official client APIs.
⚠️ Authoritative connection info — USE THESE VALUES VERBATIM
Do not invent defaults like localhost:8848 or 127.0.0.1:8848.
The values in the table below were written into this file by the
dolphindb-agent-skills installer and are the user's real DolphinDB
server. Every s.connect(...) call in the Runtime Patterns section
is already hard-coded with these same 4 values — copy a snippet as-is,
do not rewrite it.
| Field |
Value |
| Host |
{{DDB_HOST}} |
| Port |
{{DDB_PORT}} |
| User |
{{DDB_USER}} |
| Password |
{{DDB_PASSWD}} |
If the table above still shows literal {{DDB_HOST}} / {{DDB_PORT}} /
{{DDB_USER}} / {{DDB_PASSWD}} placeholders, the user never ran the
dolphindb-agent-skills installer (or ran it non-interactively). Tell
them to re-run it in a real terminal and enter their real server info.
Decision tree — runtime vs reference
- User wants to run / query / execute against their DolphinDB
(e.g. "what databases do I have", "show me 10 rows", "跑一下这个脚本",
"我的 dolphindb 里有哪些库") → use the Runtime Patterns section
below.
- User shows a
.dos file or inline DolphinDB script and asks
"does this work?" / "what does this return?" → run it via Runtime
Pattern 2 or Pattern 3 and report the real result.
- User asks "what databases/tables exist?" / "how big is this table?" →
Runtime Pattern 6 (
getClusterDFSDatabases, getTables(database(…)),
getTableDiskUsage).
- User has a local CSV / pandas DataFrame to push into DolphinDB →
Runtime Pattern 4 (upload + query) or Pattern 7 (bulk insert).
- Long batch job / many calls → start from Runtime Pattern 8
(robust connect) or Pattern 10 (reusable
DDBClient), wrap each
call with Runtime Pattern 9's run_safely helper.
- User only wants explanation / syntax / design / error-code lookup
→ jump to the Routing Table and pull the right
docs/ or reference/ file.
Safety rules (for runtime execution)
- Read-only by default. Do not run
drop*, dropPartition,
delete from, truncate, rename*, or DDL that mutates the cluster
unless the user explicitly asked for it.
- Start small. Probe with
select top 10 … / select count(*) …
before running heavy aggregations.
- Echo the script you ran in your reply so the user can audit.
- Partition column in
where. Always filter on the partition
column (usually a date/time) to avoid full-cluster scans.
Runtime Patterns
Pattern 1 — One-liner sanity check
python3 -c "import dolphindb as ddb; s=ddb.session(); s.connect('127.0.0.1', 8848, 'admin', '123456'); print(s.run('version()'))"
If this prints a version string, the connection is healthy.
Pattern 2 — Run a .dos script file
python3 << 'PYEOF'
import dolphindb as ddb
s = ddb.session()
s.connect("127.0.0.1", 8848, "admin", "123456")
script = open("/path/to/your/script.dos").read()
result = s.run(script)
print(result)
PYEOF
Replace /path/to/your/script.dos with the actual file path (use
Glob to find it if the user didn't say).
Pattern 3 — Run an inline DolphinDB script
python3 << 'PYEOF'
import dolphindb as ddb
s = ddb.session()
s.connect("127.0.0.1", 8848, "admin", "123456")
script = """
symVec = `AAPL`MSFT`GOOG
n=50; ts = 2024.01.02T09:30:00.000 + (0..(n-1))*60000
syms=array(SYMBOL,0); times=array(TIMESTAMP,0)
opens=array(DOUBLE,0); highs=array(DOUBLE,0); lows=array(DOUBLE,0)
closes=array(DOUBLE,0); vols=array(LONG,0)
for(sym in symVec){
bp=100.0+rand(100.0,1)[0]; bv=5000.0+rand(3000.0,1)[0]
for(t in ts){
o=bp+rand(2.0,1)[0]; h=o+rand(1.5,1)[0]; l=o-rand(1.5,1)[0]
c=l+rand(h-l,1)[0]; v=round(bv+rand(2000.0,1)[0],0)
syms.append!(sym); times.append!(t)
opens.append!(o); highs.append!(h); lows.append!(l)
closes.append!(c); vols.append!(v)
}
}
bars=table(syms as symbol, times as tradetime, opens as open,
highs as high, lows as low, closes as close, vols as volume)
bars=select * from bars order by symbol, tradetime
f=select symbol, tradetime, close,
mavg(volume,5)/mavg(volume,20) as volRatio,
close/mavg(close,20)-1 as priceMom,
(mavg(volume,5)/mavg(volume,20))*(close/mavg(close,20)-1) as pvpFactor
from bars context by symbol csort tradetime
print(select top 5 symbol,tradetime,close,volRatio,priceMom,pvpFactor from f)
print(select symbol,count(*) as n, avg(pvpFactor) as meanPvp from f group by symbol)
"""
r = s.run(script)
print(r)
PYEOF
Pattern 4 — Upload a pandas DataFrame, then query it
python3 << 'PYEOF'
import dolphindb as ddb
import pandas as pd
s = ddb.session()
s.connect("127.0.0.1", 8848, "admin", "123456")
df = pd.DataFrame({
"symbol": ["AAPL"] * 5,
"close": [100.0, 101.0, 102.0, 101.5, 103.0],
"volume": [1000, 1100, 1050, 1150, 1200],
})
s.upload({"myDF": df})
result = s.run("""
select * from myDF
context by symbol csort rowNo
""")
print(result)
PYEOF
Pattern 5 — Parameterized query (safe against SQL injection)
python3 << 'PYEOF'
import dolphindb as ddb
import pandas as pd
s = ddb.session()
s.connect("127.0.0.1", 8848, "admin", "123456")
# Upload filter values as a table, then reference by name.
local_df = pd.DataFrame({"sym": ["AAPL", "MSFT"], "d": ["2024.01.02", "2024.01.02"]})
s.upload({"filter": local_df})
result = s.run("""
select count(*) as cnt from loadTable('dfs://demo',`trades)
where sym in filter.sym and date in filter.d
""")
print(result)
PYEOF
Prefer this over f-string interpolation of user input.
Pattern 6 — DFS catalog & disk usage (canonical ops)
These 4 operations cover most "what's in this DolphinDB?" questions.
Prefer these exact calls over show databases / show tables (the
latter are OLAP-era aliases and don't always work on newer clusters).
python3 << 'PYEOF'
import dolphindb as ddb
s = ddb.session()
s.connect("127.0.0.1", 8848, "admin", "123456",
keepAliveTime=3600, reconnect=True)
# (1) List all DFS databases on the cluster
print(s.run("getClusterDFSDatabases()"))
# (2) List tables in a specific DFS database
print(s.run('getTables(database("dfs://trades"))'))
# (3) Disk usage for one DFS table (requires the 'ops' module)
print(s.run('use ops; getTableDiskUsage("dfs://trades", "trade", byNode=false)'))
# (4) Run an arbitrary script — the universal escape hatch
print(s.run("select top 10 * from loadTable('dfs://trades', `trade)"))
PYEOF
Tip: getTableDiskUsage returns a per-chunk breakdown by default.
Pass byNode=true if you want it rolled up per datanode, or wrap the
call to aggregate yourself (select sum(diskSize) from …).
Pattern 7 — Bulk-append rows to a DFS table
python3 << 'PYEOF'
import dolphindb as ddb
import pandas as pd
s = ddb.session()
s.connect("127.0.0.1", 8848, "admin", "123456")
df = pd.DataFrame({
"sym": ["AAPL", "MSFT"],
"date": pd.to_datetime(["2024-01-02", "2024-01-02"]).date,
"price": [189.5, 370.1],
"volume": [1000, 2000],
})
s.upload({"chunk": df})
# `tableInsert` returns the number of rows inserted.
print(s.run("""
tableInsert(loadTable('dfs://trades', `trade), chunk)
"""))
PYEOF
For high-throughput ingestion use MultithreadedTableWriter — see
docs/60-api/python-api.md via the Routing Table below.
Pattern 8 — Robust connect (long-running scripts / notebooks)
For anything longer than a one-shot query, pass keepAliveTime and
reconnect=True so a dropped TCP connection is auto-recovered.
python3 << 'PYEOF'
import dolphindb as ddb
s = ddb.session()
s.connect(
"127.0.0.1", 8848, "admin", "123456",
keepAliveTime=3600, # seconds; suppresses idle-disconnect
reconnect=True, # auto-reconnect on transient network errors
)
# ... many calls over hours ...
print(s.run("now()"))
s.close()
PYEOF
Other useful kwargs on session() / connect():
enableSSL=True — if the server listens with TLS.
highAvailability=True, highAvailabilitySites=["ip1:port", "ip2:port"]
— cluster mode with failover across controllers.
compress=True — compress result payloads for large frames.
Pattern 9 — Capture errors (don't crash the whole run)
Wrap every s.run(...) in try/except so a bad script does not kill
the whole workflow.
python3 << 'PYEOF'
import dolphindb as ddb
def run_safely(s, script: str):
try:
return True, s.run(script)
except Exception as e:
return False, str(e)
s = ddb.session()
s.connect("127.0.0.1", 8848, "admin", "123456",
keepAliveTime=3600, reconnect=True)
scripts = [
"version()",
"getClusterDFSDatabases()",
"select top 5 * from loadTable('dfs://no_such_db', `x)", # will fail
]
for sc in scripts:
ok, result = run_safely(s, sc)
status = "OK " if ok else "ERR"
print(f"[{status}] {sc}\n -> {result}\n")
s.close()
PYEOF
If you see RefId: Sxxxxx in the error string, look it up via the
Routing Table below (reference/error-codes/Sxxxxx.md).
Pattern 10 — Reusable session context manager
Copy this class into a standalone script when you need to run many
snippets against the same server — it guarantees close() runs even
on exceptions.
# dolphindb_client.py
import dolphindb as ddb
class DDBClient:
def __init__(self, host="127.0.0.1", port=8848,
user="admin", passwd="123456",
keep_alive_time=3600, reconnect=True):
self.host, self.port, self.user, self.passwd = host, port, user, passwd
self.keep_alive_time, self.reconnect = keep_alive_time, reconnect
self.session = ddb.session()
def __enter__(self):
self.session.connect(
self.host, int(self.port), self.user, self.passwd,
keepAliveTime=self.keep_alive_time, reconnect=self.reconnect,
)
return self
def __exit__(self, exc_type, exc_value, tb):
self.session.close()
def run(self, script: str):
try:
return True, self.session.run(script)
except Exception as e:
return False, str(e)
if __name__ == "__main__":
with DDBClient() as c: # defaults match this skill's patched values
print(c.run("version()"))
print(c.run("getClusterDFSDatabases()"))
Then:
python3 dolphindb_client.py
Connection troubleshooting
ConnectionRefusedError / "Connection refused"
nc -zv 127.0.0.1 8848
If that fails: DolphinDB is not running on that host:port, or a
firewall is blocking it.
ModuleNotFoundError: No module named 'dolphindb'
pip install dolphindb
# or, in an externally-managed env (macOS Homebrew / PEP 668):
uv pip install dolphindb
# or to run without installing globally:
uvx --with dolphindb python3 -c "import dolphindb; print(dolphindb.__version__)"
"Server response: Authentication failed"
Credentials are wrong. Re-run the dolphindb-agent-skills installer and
enter the correct user/password, or edit this file.
Script runs but s.run(...) returns None
Many DolphinDB scripts print nothing when they have no tail expression.
Either add an explicit print(...) inside the script, or end the script
with an expression (e.g. a variable name) whose value should be returned.
Reference Library
How to use this skill (reference mode)
- Identify the user's intent and consult the Routing Table below to pick the right file.
- For an unknown DolphinDB function, look it up in
reference/functions/INDEX.md → then read the theme file it points to.
- For a runtime error message containing
RefId: Sxxxxx, look it up in reference/error-codes/INDEX.md → then read reference/error-codes/Sxxxxx.md.
- For "how do I do X" tasks, check
patterns/ first; for runnable end-to-end scripts check examples/.
- Only fall back to the Quick snippets section below for the most common one-liners.
Routing Table
| If the user is asking about... |
Go to |
| What DolphinDB is / architecture / node types |
docs/00-overview.md |
| Install, connect, first script |
docs/01-quickstart.md |
| Data types (INT, LONG, DECIMAL, SYMBOL, TIMESTAMP, …) |
docs/10-language/data-types.md |
| Data forms (vector, matrix, table, dict, tuple, set, pair, tensor) |
docs/10-language/data-forms.md |
Dict (creation, ANY values, syncDict, missing-key, merge) ★ |
docs/10-language/dict.md |
Operators, assignment = / <-, in-place ! |
docs/10-language/operators.md |
Control flow (if, for, do..while, try..catch) |
docs/10-language/control-flow.md |
| Named / anonymous / lambda / partial application / higher-order |
docs/10-language/functions.md |
Metaprogramming, sqlCol, makeCall, sql() |
docs/10-language/metaprogramming.md |
Modules (use, module) |
docs/10-language/modules.md |
SELECT ... WHERE basics |
docs/20-sql/select-where.md |
group by aggregation |
docs/20-sql/group-by.md |
context by (per-group vectorized calc) ★ |
docs/20-sql/context-by.md |
| Time types (DATE/TIMESTAMP/NANOTIMESTAMP/… — 10 variants, join-empty trap) ★ |
docs/10-language/time-types.md |
NULL handling (typed nulls, isValid, nullFill, window propagation) ★ |
docs/10-language/null-handling.md |
Error handling (try/catch, RefIds, job errors, streaming poison-pill) |
docs/10-language/error-handling.md |
pivot by ★ |
docs/20-sql/pivot-by.md |
| Window functions / analytic functions |
docs/20-sql/window-functions.md |
| Joins: equi / left / full / cross / asof / window / prefix |
docs/20-sql/joins-overview.md |
asof join (aj) / wj — time-series alignment ★ |
docs/20-sql/asof-join.md |
update / insert into / delete / alter |
docs/20-sql/update-insert-delete.md |
Create DFS database, database(...), createPartitionedTable |
docs/30-database/dfs-database.md |
| Partitioning schemes (VALUE / RANGE / HASH / LIST / COMPO) |
docs/30-database/partitioning.md |
| TSDB engine specifics (sortColumns, keepDuplicates) |
docs/30-database/tsdb-engine.md |
| OLAP engine specifics |
docs/30-database/olap-engine.md |
| Primary-key engine (PKEY) — upsert semantics |
docs/30-database/pkey-engine.md |
| DFS limits & best practices |
docs/30-database/limits-and-best-practices.md |
streamTable, share, persist |
docs/40-streaming/stream-table.md |
subscribeTable, handler, msgAsTable |
docs/40-streaming/subscribe.md |
| Stream engines (reactiveState / timeSeries / cross / asof / session / anomaly) |
docs/40-streaming/engines.md |
| Stream engine selection — decision tree ★ |
docs/40-streaming/engine-selection.md |
| CEP |
docs/40-streaming/cep-overview.md |
| Historical replay |
docs/40-streaming/replay.md |
loadText, ploadText, schema inference |
docs/50-ingestion/loadText-ploadText.md |
| HDF5 / Parquet / Arrow |
docs/50-ingestion/hdf5-parquet.md |
| Kafka / MQTT ingestion |
docs/50-ingestion/kafka-mqtt.md |
Python API (dolphindb, ddb.session, .run, .upload) |
docs/60-api/python-api.md |
| Java API |
docs/60-api/java-api.md |
| C++ API |
docs/60-api/cpp-api.md |
| Cross-language type mapping |
docs/60-api/type-mapping.md |
| Query optimization, EXPLAIN, hints |
docs/70-perf/query-optimization.md |
| Partition pruning |
docs/70-perf/partition-pruning.md |
| Memory & threading tuning |
docs/70-perf/memory-threading.md |
| Slow-query diagnosis checklist ★ |
docs/70-perf/slow-query-diagnosis.md |
JIT (@jit) compilation guide |
docs/70-perf/jit-guide.md |
| Cluster ops |
docs/90-admin/cluster.md |
| Backup / restore |
docs/90-admin/backup-restore.md |
| Users / ACL |
docs/90-admin/security.md |
| Look up any built-in function by name |
python scripts/lookup.py fn <name> (or reference/functions/INDEX.md) |
Look up any runtime error RefId: Sxxxxx |
python scripts/lookup.py error S00012 (or reference/error-codes/INDEX.md) |
| Jump to curated reads for a topic |
`python scripts/lookup.py topic <backtest |
| One-page top-traps cheatsheet ★ |
docs/cheatsheet.md |
| Chinese ↔ English keyword map (中文提问) |
docs/cn-keywords.md |
| Plugin quick catalog (one-line per plugin) |
reference/plugins-catalog.md |
| Any specific plugin manual (amdQuote / Arrow / Kafka / ODBC / Parquet / CTP / INSIGHT / …) |
docs/plugins/README.md (hub) + docs/plugins/<name>/ or docs/plugins/<name>.md |
| Worked tutorials (OHLC, backtest, IoT anomaly, scheduledJob, …) |
docs/tutorials/README.md (curated index of 281 tutorials) |
Built-in modules (ta, wq101alpha, gtja191Alpha, mytt, MarketHoliday, …) |
docs/modules/README.md |
| Deployment guides / license fingerprint |
docs/deploy/ |
| DolphinDB MCP |
docs/mcp/ |
| O&M troubleshooting (connection lost / server hang / slow I/O) |
docs/90-admin/omc/ |
| Web console admin UI (user mgmt, config, stream graph, querybuilder, Shell) |
docs/90-admin/web/README.md (18 pages) |
| Client IDE & editor integrations (VSCode, Jupyter, DBeaver, Grafana, PowerBI, Superset) |
docs/60-api/{vscode,jupyter,gui,terminal,clients}.md + docs/60-api/tools/ |
| Configuration parameter reference |
docs/90-admin/cfg/ |
| Version release notes |
docs/release-notes/ |
| Upstream top-level index & 3rd-party integrations list |
docs/upstream-index.md, docs/third_party.md |
| Functions by topic (categorical index of all 1721 built-ins) |
reference/functions/funcs_by_topics.md (55 KB) + funcs_intro.md + appendix.md |
| Backtest / simulated matching (Backtest plugin, MatchingEngineSimulator, OME, SimulatedExchangeEngine) ★ |
docs/backtest/README.md (hub) + docs/backtest/{backtest-plugin-guide,matching-engine-guide,assets,traps,factors,tutorials-index}.md |
Factor / alpha computation (@state, reactive state engine, lookahead, WQ101, GTJA191) ★ |
docs/backtest/factors.md |
| Runnable end-to-end scripts |
examples/ (backtest-quickstart/-future/-option, parquet-roundtrip, stream-reactive-engine, tick-to-ohlc, python-api-quickstart) |
| "How do I do X" recipes |
patterns/ (signal-to-order, stream-ingestion-to-dfs, stream-recovery-after-restart, scheduled-job-template, python-roundtrip-type-safety, asof-join, partition-design, tick-to-ohlc, upsert-via-pkey) |
| Eval battery — 10 representative tasks |
evals/README.md |
| How to measure hit-rate / uplift |
evals/HOW-TO-MEASURE.md + scripts/run_evals.py |
Common traps (read before writing DolphinDB code)
These are the most frequent mistakes agents make. Follow the linked page for details.
context by ≠ group by. group by collapses rows; context by keeps all rows and computes per-group vectors. Use context by for rolling/cumulative per-symbol calculations. → docs/20-sql/context-by.md
- Partition column must appear in
where, otherwise the query scans all partitions. Always filter on the partition column first (typically a date/time). → docs/70-perf/partition-pruning.md
share before subscribe. A stream table must be shared (or persisted) before subscribeTable can attach. → docs/40-streaming/stream-table.md
= vs ==. In DolphinDB, = is assignment and equality comparison inside where clauses. Use == for equality in script expressions; use = inside SQL predicates. → docs/10-language/operators.md
<- is assignment in function definitions and also appears in some stream APIs; it is NOT a comparison operator.
- Symbol literals use backticks.
`AAPL is a SYMBOL literal; "AAPL" is STRING. Mixing them changes partition routing and join behavior.
- Date literals have no quotes. Write
2024.01.01, not "2024-01-01". Use date("2024-01-01") to convert from string.
append! mutates; append does not exist for tables. The ! suffix means in-place mutation.
loadTable(...) is lazy. Operations are lazily planned; only fully materialized when the query is executed or the result is touched.
- Python API returns numpy-backed DataFrames.
SYMBOL/STRING become object, TIMESTAMP becomes datetime64[ns]. Check docs/60-api/type-mapping.md before comparing values.
- Dict is NOT Python-style. No
{"a": 1} literal — use dict(STRING, INT) (empty) or dict(keys, vals). Missing-key read returns null (not an error); use d.contains(k). Concurrent writes need syncDict, otherwise the node can crash. → docs/10-language/dict.md
- Backtest lookahead bias.
mavg(close, 5) and any same-bar factor include the current bar, which is only valid if you execute at bar close. For next-bar execution, lag signals by one bar. matchingRatio=1, zero slippage, and unmodeled queue position all flatter results. → docs/backtest/traps.md
show engines, getStreamingStat() and getPerformance() are your first debugging tools — check them before assuming a bug.
Quick snippets
Kept intentionally minimal. For more, read examples/.
Connect from Python
import dolphindb as ddb
s = ddb.session()
s.connect("localhost", 8848, "admin", "123456")
df = s.run("select top 100 * from loadTable('dfs://trades', `trade)")
Create a partitioned DFS table (TSDB engine)
db = database("dfs://trades", VALUE, 2024.01.01..2024.12.31, engine="TSDB")
schema = table(
1:0,
`sym`date`price`volume,
[SYMBOL, DATE, DOUBLE, INT]
)
db.createPartitionedTable(
table = schema,
tableName = `trade,
partitionColumns = `date,
sortColumns = `sym`date
)
Append rows
t = table(
take(`AAPL`MSFT, 10) as sym,
take(2024.01.01..2024.01.10, 10) as date,
rand(100.0, 10) as price,
rand(1000, 10) as volume
)
loadTable("dfs://trades", `trade).append!(t)
context by vs group by
// group by: 1 row per sym
select sym, avg(price) as avgPx from t group by sym
// context by: keep all rows, add per-sym 5-row moving avg
select sym, date, price, mavg(price, 5) as ma5
from t context by sym
Stream table + subscription
share streamTable(1000:0, `time`sym`price, [TIMESTAMP, SYMBOL, DOUBLE]) as trades
def myHandler(msg) { /* msg is a table when msgAsTable=true */ }
subscribeTable(
tableName = `trades,
actionName = `printAction,
handler = myHandler,
msgAsTable = true
)
Diagnosing an error from a script
If the user shows a log line like ... RefId: S02006, read reference/error-codes/S02006.md — every error code ships with 报错信息 / 错误原因 / 解决办法.
Maintenance
Every file in this skill is either hand-authored or auto-mirrored
from the upstream DolphinDB documentation. They coexist flatly — there is
no separate _source/ layer.
Auto-mirrored files begin with the HTML comment
<!-- Auto-mirrored from upstream ... -->. Do not edit them by hand; rerun
the build script and they will be overwritten. Hand-authored files have no
such marker and are never touched by the build.
Auto-mirrored tree (regenerated by scripts/build_from_docs.py):
reference/functions/ — INDEX, by-theme, by-name (1718 function pages).
reference/error-codes/ — every RefId: Sxxxxx page in full.
reference/plugins-catalog.md — one-line summary per plugin.
docs/**/*.md except the hand-authored files listed below.
Hand-authored (never auto-touched):
docs/00-overview.md, docs/01-quickstart.md.
docs/<area>/README.md in every numbered area.
docs/10-language/{data-types,data-forms,dict,time-types,null-handling,error-handling,operators,control-flow,functions,metaprogramming,modules}.md.
docs/20-sql/{select-where,group-by,context-by,pivot-by,window-functions,joins-overview,asof-join,update-insert-delete}.md.
docs/30-database/{dfs-database,partitioning,tsdb-engine,olap-engine,pkey-engine,limits-and-best-practices}.md.
docs/40-streaming/{stream-table,subscribe,engines,engine-selection,cep-overview,replay}.md.
docs/50-ingestion/{loadText-ploadText,hdf5-parquet,kafka-mqtt}.md.
docs/60-api/{python-api,java-api,cpp-api,type-mapping}.md.
docs/70-perf/{partition-pruning,query-optimization,memory-threading,slow-query-diagnosis,jit-guide}.md.
docs/90-admin/{cluster,backup-restore,security}.md.
docs/backtest/{README,backtest-plugin-guide,matching-engine-guide,assets,traps,factors,tutorials-index}.md.
docs/tutorials/README.md, docs/plugins/README.md, docs/modules/README.md — curated navigation indexes.
patterns/*.md — "how do I do X" recipes.
examples/*.dos, examples/*.py — runnable end-to-end scripts.
evals/{README,scoring,run}.md + evals/tasks/*.md — regression battery.
docs/cheatsheet.md — compressed top-traps.
docs/cn-keywords.md — CN↔EN keyword map.
scripts/lookup.py — agent-invokable CLI for error codes / functions / topics.
SKILL.md — this file.
Rebuild after upstream changes:
python skills/dolphindb/scripts/build_from_docs.py
Only files carrying the auto-mirror marker are deleted/rewritten; anything
you wrote manually is preserved across rebuilds.
1---2name: dolphindb3description: The ONE skill for anything DolphinDB — covers BOTH running queries against the user's live DolphinDB server AND offline reference / syntax lookup. Use this whenever the user mentions DolphinDB, ddb, .dos, DFS, or anything database-related for DolphinDB. Runtime side: the connection info (host/port/user/password) embedded below was written by the `dolphindb-agent-skills` installer and is the user's REAL server — use it verbatim, do NOT fall back to localhost:8848 or any other default. Runtime capabilities: one-shot queries via Python API (`import dolphindb`), executing .dos files, uploading pandas DataFrames, parameterized queries, listing DFS databases/tables (`getClusterDFSDatabases`, `getTables(database(…))`), checking table disk usage (`getTableDiskUsage`), bulk-inserting into DFS tables (`tableInsert`), robust long-lived connections (`keepAliveTime`, `reconnect`), error-safe execution. Reference side: DolphinDB SQL dialect (context by / pivot by / asof join / window join), DFS partitioned tables on TSDB /4license: Apache-2.05---67# DolphinDB Skill89One skill, two modes:1011- **Runtime** — run bash/Python snippets against the user's live DolphinDB12 server (patched connection info below).13- **Reference** — offline knowledge base for syntax, engines, plugins,14 error codes, and best practices (Routing Table below).1516All content targets **DolphinDB Server 3.00+** and its official client APIs.1718---1920## ⚠️ Authoritative connection info — USE THESE VALUES VERBATIM2122**Do not invent defaults like `localhost:8848` or `127.0.0.1:8848`.**23The values in the table below were written into this file by the24`dolphindb-agent-skills` installer and are the **user's real DolphinDB25server**. Every `s.connect(...)` call in the Runtime Patterns section26is already hard-coded with these same 4 values — copy a snippet as-is,27do not rewrite it.2829| Field | Value |30|----------|--------------------|31| Host | `{{DDB_HOST}}` |32| Port | `{{DDB_PORT}}` |33| User | `{{DDB_USER}}` |34| Password | `{{DDB_PASSWD}}` |3536> If the table above still shows literal `{{DDB_HOST}}` / `{{DDB_PORT}}` /37> `{{DDB_USER}}` / `{{DDB_PASSWD}}` placeholders, the user never ran the38> `dolphindb-agent-skills` installer (or ran it non-interactively). Tell39> them to re-run it in a real terminal and enter their real server info.4041---4243## Decision tree — runtime vs reference44451. User wants to **run / query / execute** against their DolphinDB46 (e.g. "what databases do I have", "show me 10 rows", "跑一下这个脚本",47 "我的 dolphindb 里有哪些库") → use the **Runtime Patterns** section48 below.492. User shows a `.dos` file or inline DolphinDB script and asks50 "does this work?" / "what does this return?" → run it via Runtime51 **Pattern 2** or **Pattern 3** and report the real result.523. User asks "what databases/tables exist?" / "how big is this table?" →53 Runtime **Pattern 6** (`getClusterDFSDatabases`, `getTables(database(…))`,54 `getTableDiskUsage`).554. User has a local CSV / pandas DataFrame to push into DolphinDB →56 Runtime **Pattern 4** (upload + query) or **Pattern 7** (bulk insert).575. Long batch job / many calls → start from Runtime **Pattern 8**58 (robust connect) or **Pattern 10** (reusable `DDBClient`), wrap each59 call with Runtime **Pattern 9**'s `run_safely` helper.606. User only wants **explanation / syntax / design / error-code lookup**61 → jump to the [Routing Table](#routing-table) and pull the right62 `docs/` or `reference/` file.6364### Safety rules (for runtime execution)6566- **Read-only by default.** Do not run `drop*`, `dropPartition`,67 `delete from`, `truncate`, `rename*`, or DDL that mutates the cluster68 unless the user explicitly asked for it.69- **Start small.** Probe with `select top 10 …` / `select count(*) …`70 before running heavy aggregations.71- **Echo the script you ran** in your reply so the user can audit.72- **Partition column in `where`.** Always filter on the partition73 column (usually a date/time) to avoid full-cluster scans.7475---7677# Runtime Patterns7879## Pattern 1 — One-liner sanity check8081```bash82python3 -c "import dolphindb as ddb; s=ddb.session(); s.connect('127.0.0.1', 8848, 'admin', '123456'); print(s.run('version()'))"83```8485If this prints a version string, the connection is healthy.8687---8889## Pattern 2 — Run a .dos script file9091```bash92python3 << 'PYEOF'93import dolphindb as ddb94s = ddb.session()95s.connect("127.0.0.1", 8848, "admin", "123456")96script = open("/path/to/your/script.dos").read()97result = s.run(script)98print(result)99PYEOF100```101102Replace `/path/to/your/script.dos` with the actual file path (use103`Glob` to find it if the user didn't say).104105---106107## Pattern 3 — Run an inline DolphinDB script108109```bash110python3 << 'PYEOF'111import dolphindb as ddb112s = ddb.session()113s.connect("127.0.0.1", 8848, "admin", "123456")114115script = """116symVec = `AAPL`MSFT`GOOG117n=50; ts = 2024.01.02T09:30:00.000 + (0..(n-1))*60000118syms=array(SYMBOL,0); times=array(TIMESTAMP,0)119opens=array(DOUBLE,0); highs=array(DOUBLE,0); lows=array(DOUBLE,0)120closes=array(DOUBLE,0); vols=array(LONG,0)121for(sym in symVec){122 bp=100.0+rand(100.0,1)[0]; bv=5000.0+rand(3000.0,1)[0]123 for(t in ts){124 o=bp+rand(2.0,1)[0]; h=o+rand(1.5,1)[0]; l=o-rand(1.5,1)[0]125 c=l+rand(h-l,1)[0]; v=round(bv+rand(2000.0,1)[0],0)126 syms.append!(sym); times.append!(t)127 opens.append!(o); highs.append!(h); lows.append!(l)128 closes.append!(c); vols.append!(v)129 }130}131bars=table(syms as symbol, times as tradetime, opens as open,132 highs as high, lows as low, closes as close, vols as volume)133bars=select * from bars order by symbol, tradetime134135f=select symbol, tradetime, close,136 mavg(volume,5)/mavg(volume,20) as volRatio,137 close/mavg(close,20)-1 as priceMom,138 (mavg(volume,5)/mavg(volume,20))*(close/mavg(close,20)-1) as pvpFactor139from bars context by symbol csort tradetime140141print(select top 5 symbol,tradetime,close,volRatio,priceMom,pvpFactor from f)142print(select symbol,count(*) as n, avg(pvpFactor) as meanPvp from f group by symbol)143"""144r = s.run(script)145print(r)146PYEOF147```148149---150151## Pattern 4 — Upload a pandas DataFrame, then query it152153```bash154python3 << 'PYEOF'155import dolphindb as ddb156import pandas as pd157158s = ddb.session()159s.connect("127.0.0.1", 8848, "admin", "123456")160161df = pd.DataFrame({162 "symbol": ["AAPL"] * 5,163 "close": [100.0, 101.0, 102.0, 101.5, 103.0],164 "volume": [1000, 1100, 1050, 1150, 1200],165})166167s.upload({"myDF": df})168result = s.run("""169 select * from myDF170 context by symbol csort rowNo171""")172print(result)173PYEOF174```175176---177178## Pattern 5 — Parameterized query (safe against SQL injection)179180```bash181python3 << 'PYEOF'182import dolphindb as ddb183import pandas as pd184185s = ddb.session()186s.connect("127.0.0.1", 8848, "admin", "123456")187188# Upload filter values as a table, then reference by name.189local_df = pd.DataFrame({"sym": ["AAPL", "MSFT"], "d": ["2024.01.02", "2024.01.02"]})190s.upload({"filter": local_df})191192result = s.run("""193 select count(*) as cnt from loadTable('dfs://demo',`trades)194 where sym in filter.sym and date in filter.d195""")196print(result)197PYEOF198```199200Prefer this over f-string interpolation of user input.201202---203204## Pattern 6 — DFS catalog & disk usage (canonical ops)205206These 4 operations cover most "what's in this DolphinDB?" questions.207Prefer these exact calls over `show databases` / `show tables` (the208latter are OLAP-era aliases and don't always work on newer clusters).209210```bash211python3 << 'PYEOF'212import dolphindb as ddb213s = ddb.session()214s.connect("127.0.0.1", 8848, "admin", "123456",215 keepAliveTime=3600, reconnect=True)216217# (1) List all DFS databases on the cluster218print(s.run("getClusterDFSDatabases()"))219220# (2) List tables in a specific DFS database221print(s.run('getTables(database("dfs://trades"))'))222223# (3) Disk usage for one DFS table (requires the 'ops' module)224print(s.run('use ops; getTableDiskUsage("dfs://trades", "trade", byNode=false)'))225226# (4) Run an arbitrary script — the universal escape hatch227print(s.run("select top 10 * from loadTable('dfs://trades', `trade)"))228PYEOF229```230231**Tip:** `getTableDiskUsage` returns a per-chunk breakdown by default.232Pass `byNode=true` if you want it rolled up per datanode, or wrap the233call to aggregate yourself (`select sum(diskSize) from …`).234235---236237## Pattern 7 — Bulk-append rows to a DFS table238239```bash240python3 << 'PYEOF'241import dolphindb as ddb242import pandas as pd243244s = ddb.session()245s.connect("127.0.0.1", 8848, "admin", "123456")246247df = pd.DataFrame({248 "sym": ["AAPL", "MSFT"],249 "date": pd.to_datetime(["2024-01-02", "2024-01-02"]).date,250 "price": [189.5, 370.1],251 "volume": [1000, 2000],252})253s.upload({"chunk": df})254255# `tableInsert` returns the number of rows inserted.256print(s.run("""257 tableInsert(loadTable('dfs://trades', `trade), chunk)258"""))259PYEOF260```261262For high-throughput ingestion use `MultithreadedTableWriter` — see263`docs/60-api/python-api.md` via the Routing Table below.264265---266267## Pattern 8 — Robust connect (long-running scripts / notebooks)268269For anything longer than a one-shot query, pass `keepAliveTime` and270`reconnect=True` so a dropped TCP connection is auto-recovered.271272```bash273python3 << 'PYEOF'274import dolphindb as ddb275276s = ddb.session()277s.connect(278 "127.0.0.1", 8848, "admin", "123456",279 keepAliveTime=3600, # seconds; suppresses idle-disconnect280 reconnect=True, # auto-reconnect on transient network errors281)282283# ... many calls over hours ...284print(s.run("now()"))285s.close()286PYEOF287```288289Other useful kwargs on `session()` / `connect()`:290291- `enableSSL=True` — if the server listens with TLS.292- `highAvailability=True, highAvailabilitySites=["ip1:port", "ip2:port"]`293 — cluster mode with failover across controllers.294- `compress=True` — compress result payloads for large frames.295296---297298## Pattern 9 — Capture errors (don't crash the whole run)299300Wrap every `s.run(...)` in try/except so a bad script does not kill301the whole workflow.302303```bash304python3 << 'PYEOF'305import dolphindb as ddb306307def run_safely(s, script: str):308 try:309 return True, s.run(script)310 except Exception as e:311 return False, str(e)312313s = ddb.session()314s.connect("127.0.0.1", 8848, "admin", "123456",315 keepAliveTime=3600, reconnect=True)316317scripts = [318 "version()",319 "getClusterDFSDatabases()",320 "select top 5 * from loadTable('dfs://no_such_db', `x)", # will fail321]322for sc in scripts:323 ok, result = run_safely(s, sc)324 status = "OK " if ok else "ERR"325 print(f"[{status}] {sc}\n -> {result}\n")326s.close()327PYEOF328```329330If you see `RefId: Sxxxxx` in the error string, look it up via the331Routing Table below (`reference/error-codes/Sxxxxx.md`).332333---334335## Pattern 10 — Reusable session context manager336337Copy this class into a standalone script when you need to run many338snippets against the same server — it guarantees `close()` runs even339on exceptions.340341```python342# dolphindb_client.py343import dolphindb as ddb344345class DDBClient:346 def __init__(self, host="127.0.0.1", port=8848,347 user="admin", passwd="123456",348 keep_alive_time=3600, reconnect=True):349 self.host, self.port, self.user, self.passwd = host, port, user, passwd350 self.keep_alive_time, self.reconnect = keep_alive_time, reconnect351 self.session = ddb.session()352353 def __enter__(self):354 self.session.connect(355 self.host, int(self.port), self.user, self.passwd,356 keepAliveTime=self.keep_alive_time, reconnect=self.reconnect,357 )358 return self359360 def __exit__(self, exc_type, exc_value, tb):361 self.session.close()362363 def run(self, script: str):364 try:365 return True, self.session.run(script)366 except Exception as e:367 return False, str(e)368369370if __name__ == "__main__":371 with DDBClient() as c: # defaults match this skill's patched values372 print(c.run("version()"))373 print(c.run("getClusterDFSDatabases()"))374```375376Then:377378```bash379python3 dolphindb_client.py380```381382---383384## Connection troubleshooting385386### `ConnectionRefusedError` / "Connection refused"387388```bash389nc -zv 127.0.0.1 8848390```391392If that fails: DolphinDB is not running on that host:port, or a393firewall is blocking it.394395### `ModuleNotFoundError: No module named 'dolphindb'`396397```bash398pip install dolphindb399# or, in an externally-managed env (macOS Homebrew / PEP 668):400uv pip install dolphindb401# or to run without installing globally:402uvx --with dolphindb python3 -c "import dolphindb; print(dolphindb.__version__)"403```404405### "Server response: Authentication failed"406407Credentials are wrong. Re-run the `dolphindb-agent-skills` installer and408enter the correct user/password, or edit this file.409410### Script runs but `s.run(...)` returns `None`411412Many DolphinDB scripts print nothing when they have no tail expression.413Either add an explicit `print(...)` inside the script, or end the script414with an expression (e.g. a variable name) whose value should be returned.415416---417418# Reference Library419420## How to use this skill (reference mode)4214221. Identify the user's intent and **consult the Routing Table** below to pick the right file.4232. For an unknown DolphinDB function, look it up in `reference/functions/INDEX.md` → then read the theme file it points to.4243. For a runtime error message containing `RefId: Sxxxxx`, look it up in `reference/error-codes/INDEX.md` → then read `reference/error-codes/Sxxxxx.md`.4254. For "how do I do X" tasks, check `patterns/` first; for runnable end-to-end scripts check `examples/`.4265. Only fall back to the [Quick snippets](#quick-snippets) section below for the most common one-liners.427428---429430## Routing Table431432| If the user is asking about... | Go to |433|---|---|434| What DolphinDB is / architecture / node types | `docs/00-overview.md` |435| Install, connect, first script | `docs/01-quickstart.md` |436| Data types (INT, LONG, DECIMAL, SYMBOL, TIMESTAMP, …) | `docs/10-language/data-types.md` |437| Data forms (vector, matrix, table, dict, tuple, set, pair, tensor) | `docs/10-language/data-forms.md` |438| **Dict** (creation, `ANY` values, `syncDict`, missing-key, merge) ★ | `docs/10-language/dict.md` |439| Operators, assignment `=` / `<-`, in-place `!` | `docs/10-language/operators.md` |440| Control flow (`if`, `for`, `do..while`, `try..catch`) | `docs/10-language/control-flow.md` |441| Named / anonymous / lambda / partial application / higher-order | `docs/10-language/functions.md` |442| Metaprogramming, `sqlCol`, `makeCall`, `sql()` | `docs/10-language/metaprogramming.md` |443| Modules (`use`, `module`) | `docs/10-language/modules.md` |444| `SELECT ... WHERE` basics | `docs/20-sql/select-where.md` |445| `group by` aggregation | `docs/20-sql/group-by.md` |446| **`context by`** (per-group vectorized calc) ★ | `docs/20-sql/context-by.md` |447| **Time types** (DATE/TIMESTAMP/NANOTIMESTAMP/… — 10 variants, join-empty trap) ★ | `docs/10-language/time-types.md` |448| **NULL handling** (typed nulls, `isValid`, `nullFill`, window propagation) ★ | `docs/10-language/null-handling.md` |449| **Error handling** (`try/catch`, RefIds, job errors, streaming poison-pill) | `docs/10-language/error-handling.md` |450| **`pivot by`** ★ | `docs/20-sql/pivot-by.md` |451| Window functions / analytic functions | `docs/20-sql/window-functions.md` |452| Joins: equi / left / full / cross / asof / window / prefix | `docs/20-sql/joins-overview.md` |453| **`asof join` (`aj`) / `wj` — time-series alignment** ★ | `docs/20-sql/asof-join.md` |454| `update` / `insert into` / `delete` / `alter` | `docs/20-sql/update-insert-delete.md` |455| Create DFS database, `database(...)`, `createPartitionedTable` | `docs/30-database/dfs-database.md` |456| Partitioning schemes (VALUE / RANGE / HASH / LIST / COMPO) | `docs/30-database/partitioning.md` |457| TSDB engine specifics (sortColumns, keepDuplicates) | `docs/30-database/tsdb-engine.md` |458| OLAP engine specifics | `docs/30-database/olap-engine.md` |459| Primary-key engine (PKEY) — upsert semantics | `docs/30-database/pkey-engine.md` |460| DFS limits & best practices | `docs/30-database/limits-and-best-practices.md` |461| `streamTable`, `share`, persist | `docs/40-streaming/stream-table.md` |462| `subscribeTable`, handler, `msgAsTable` | `docs/40-streaming/subscribe.md` |463| Stream engines (reactiveState / timeSeries / cross / asof / session / anomaly) | `docs/40-streaming/engines.md` |464| **Stream engine selection — decision tree** ★ | `docs/40-streaming/engine-selection.md` |465| CEP | `docs/40-streaming/cep-overview.md` |466| Historical replay | `docs/40-streaming/replay.md` |467| `loadText`, `ploadText`, schema inference | `docs/50-ingestion/loadText-ploadText.md` |468| HDF5 / Parquet / Arrow | `docs/50-ingestion/hdf5-parquet.md` |469| Kafka / MQTT ingestion | `docs/50-ingestion/kafka-mqtt.md` |470| Python API (`dolphindb`, `ddb.session`, `.run`, `.upload`) | `docs/60-api/python-api.md` |471| Java API | `docs/60-api/java-api.md` |472| C++ API | `docs/60-api/cpp-api.md` |473| Cross-language type mapping | `docs/60-api/type-mapping.md` |474| Query optimization, EXPLAIN, hints | `docs/70-perf/query-optimization.md` |475| Partition pruning | `docs/70-perf/partition-pruning.md` |476| Memory & threading tuning | `docs/70-perf/memory-threading.md` |477| **Slow-query diagnosis checklist** ★ | `docs/70-perf/slow-query-diagnosis.md` |478| **JIT (`@jit`) compilation guide** | `docs/70-perf/jit-guide.md` |479| Cluster ops | `docs/90-admin/cluster.md` |480| Backup / restore | `docs/90-admin/backup-restore.md` |481| Users / ACL | `docs/90-admin/security.md` |482| **Look up any built-in function by name** | `python scripts/lookup.py fn <name>` (or `reference/functions/INDEX.md`) |483| **Look up any runtime error `RefId: Sxxxxx`** | `python scripts/lookup.py error S00012` (or `reference/error-codes/INDEX.md`) |484| **Jump to curated reads for a topic** | `python scripts/lookup.py topic <backtest|stream|factor|python|…>` |485| **One-page top-traps cheatsheet** ★ | `docs/cheatsheet.md` |486| **Chinese ↔ English keyword map (中文提问)** | `docs/cn-keywords.md` |487| Plugin quick catalog (one-line per plugin) | `reference/plugins-catalog.md` |488| **Any specific plugin manual** (amdQuote / Arrow / Kafka / ODBC / Parquet / CTP / INSIGHT / …) | `docs/plugins/README.md` (hub) + `docs/plugins/<name>/` or `docs/plugins/<name>.md` |489| Worked tutorials (OHLC, backtest, IoT anomaly, scheduledJob, …) | `docs/tutorials/README.md` (curated index of 281 tutorials) |490| Built-in modules (`ta`, `wq101alpha`, `gtja191Alpha`, `mytt`, `MarketHoliday`, …) | `docs/modules/README.md` |491| Deployment guides / license fingerprint | `docs/deploy/` |492| DolphinDB MCP | `docs/mcp/` |493| O&M troubleshooting (connection lost / server hang / slow I/O) | `docs/90-admin/omc/` |494| **Web console admin UI** (user mgmt, config, stream graph, querybuilder, Shell) | `docs/90-admin/web/README.md` (18 pages) |495| Client IDE & editor integrations (VSCode, Jupyter, DBeaver, Grafana, PowerBI, Superset) | `docs/60-api/{vscode,jupyter,gui,terminal,clients}.md` + `docs/60-api/tools/` |496| Configuration parameter reference | `docs/90-admin/cfg/` |497| Version release notes | `docs/release-notes/` |498| Upstream top-level index & 3rd-party integrations list | `docs/upstream-index.md`, `docs/third_party.md` |499| **Functions by topic** (categorical index of all 1721 built-ins) | `reference/functions/funcs_by_topics.md` (55 KB) + `funcs_intro.md` + `appendix.md` |500| **Backtest / simulated matching** (Backtest plugin, MatchingEngineSimulator, OME, SimulatedExchangeEngine) ★ | `docs/backtest/README.md` (hub) + `docs/backtest/{backtest-plugin-guide,matching-engine-guide,assets,traps,factors,tutorials-index}.md` |501| **Factor / alpha computation** (`@state`, reactive state engine, lookahead, WQ101, GTJA191) ★ | `docs/backtest/factors.md` |502| Runnable end-to-end scripts | `examples/` (backtest-quickstart/-future/-option, parquet-roundtrip, stream-reactive-engine, tick-to-ohlc, python-api-quickstart) |503| "How do I do X" recipes | `patterns/` (signal-to-order, stream-ingestion-to-dfs, stream-recovery-after-restart, scheduled-job-template, python-roundtrip-type-safety, asof-join, partition-design, tick-to-ohlc, upsert-via-pkey) |504| **Eval battery — 10 representative tasks** | `evals/README.md` |505| **How to measure hit-rate / uplift** | `evals/HOW-TO-MEASURE.md` + `scripts/run_evals.py` |506507---508509## Common traps (read before writing DolphinDB code)510511These are the most frequent mistakes agents make. Follow the linked page for details.512513- **`context by` ≠ `group by`.** `group by` collapses rows; `context by` keeps all rows and computes per-group vectors. Use `context by` for rolling/cumulative per-symbol calculations. → `docs/20-sql/context-by.md`514- **Partition column must appear in `where`**, otherwise the query scans all partitions. Always filter on the partition column first (typically a date/time). → `docs/70-perf/partition-pruning.md`515- **`share` before subscribe.** A stream table must be `share`d (or persisted) before `subscribeTable` can attach. → `docs/40-streaming/stream-table.md`516- **`=` vs `==`.** In DolphinDB, `=` is assignment _and_ equality comparison inside `where` clauses. Use `==` for equality in script expressions; use `=` inside SQL predicates. → `docs/10-language/operators.md`517- **`<-` is assignment in function definitions** and also appears in some stream APIs; it is NOT a comparison operator.518- **Symbol literals use backticks.** `` `AAPL `` is a SYMBOL literal; `"AAPL"` is STRING. Mixing them changes partition routing and join behavior.519- **Date literals have no quotes.** Write `2024.01.01`, not `"2024-01-01"`. Use `date("2024-01-01")` to convert from string.520- **`append!` mutates; `append` does not exist for tables.** The `!` suffix means in-place mutation.521- **`loadTable(...)` is lazy.** Operations are lazily planned; only fully materialized when the query is executed or the result is touched.522- **Python API returns numpy-backed DataFrames.** `SYMBOL`/`STRING` become `object`, `TIMESTAMP` becomes `datetime64[ns]`. Check `docs/60-api/type-mapping.md` before comparing values.523- **Dict is NOT Python-style.** No `{"a": 1}` literal — use `dict(STRING, INT)` (empty) or `dict(keys, vals)`. Missing-key read returns null (not an error); use `d.contains(k)`. Concurrent writes need `syncDict`, otherwise the node can crash. → `docs/10-language/dict.md`524- **Backtest lookahead bias.** `mavg(close, 5)` and any same-bar factor include the current bar, which is only valid if you execute at bar close. For next-bar execution, lag signals by one bar. `matchingRatio=1`, zero `slippage`, and unmodeled queue position all flatter results. → `docs/backtest/traps.md`525- **`show engines`, `getStreamingStat()` and `getPerformance()`** are your first debugging tools — check them before assuming a bug.526527---528529## Quick snippets530531Kept intentionally minimal. For more, read `examples/`.532533### Connect from Python534535```python536import dolphindb as ddb537538s = ddb.session()539s.connect("localhost", 8848, "admin", "123456")540541df = s.run("select top 100 * from loadTable('dfs://trades', `trade)")542```543544### Create a partitioned DFS table (TSDB engine)545546```dolphindb547db = database("dfs://trades", VALUE, 2024.01.01..2024.12.31, engine="TSDB")548549schema = table(550 1:0,551 `sym`date`price`volume,552 [SYMBOL, DATE, DOUBLE, INT]553)554555db.createPartitionedTable(556 table = schema,557 tableName = `trade,558 partitionColumns = `date,559 sortColumns = `sym`date560)561```562563### Append rows564565```dolphindb566t = table(567 take(`AAPL`MSFT, 10) as sym,568 take(2024.01.01..2024.01.10, 10) as date,569 rand(100.0, 10) as price,570 rand(1000, 10) as volume571)572loadTable("dfs://trades", `trade).append!(t)573```574575### `context by` vs `group by`576577```dolphindb578// group by: 1 row per sym579select sym, avg(price) as avgPx from t group by sym580581// context by: keep all rows, add per-sym 5-row moving avg582select sym, date, price, mavg(price, 5) as ma5583from t context by sym584```585586### Stream table + subscription587588```dolphindb589share streamTable(1000:0, `time`sym`price, [TIMESTAMP, SYMBOL, DOUBLE]) as trades590591def myHandler(msg) { /* msg is a table when msgAsTable=true */ }592593subscribeTable(594 tableName = `trades,595 actionName = `printAction,596 handler = myHandler,597 msgAsTable = true598)599```600601### Diagnosing an error from a script602603If the user shows a log line like `... RefId: S02006`, read `reference/error-codes/S02006.md` — every error code ships with **报错信息 / 错误原因 / 解决办法**.604605---606607## Maintenance608609Every file in this skill is either **hand-authored** or **auto-mirrored**610from the upstream DolphinDB documentation. They coexist flatly — there is611no separate `_source/` layer.612613**Auto-mirrored files** begin with the HTML comment614`<!-- Auto-mirrored from upstream ... -->`. Do not edit them by hand; rerun615the build script and they will be overwritten. Hand-authored files have no616such marker and are never touched by the build.617618Auto-mirrored tree (regenerated by `scripts/build_from_docs.py`):619620- `reference/functions/` — INDEX, by-theme, by-name (1718 function pages).621- `reference/error-codes/` — every `RefId: Sxxxxx` page in full.622- `reference/plugins-catalog.md` — one-line summary per plugin.623- `docs/**/*.md` except the hand-authored files listed below.624625Hand-authored (never auto-touched):626627- `docs/00-overview.md`, `docs/01-quickstart.md`.628- `docs/<area>/README.md` in every numbered area.629- `docs/10-language/{data-types,data-forms,dict,time-types,null-handling,error-handling,operators,control-flow,functions,metaprogramming,modules}.md`.630- `docs/20-sql/{select-where,group-by,context-by,pivot-by,window-functions,joins-overview,asof-join,update-insert-delete}.md`.631- `docs/30-database/{dfs-database,partitioning,tsdb-engine,olap-engine,pkey-engine,limits-and-best-practices}.md`.632- `docs/40-streaming/{stream-table,subscribe,engines,engine-selection,cep-overview,replay}.md`.633- `docs/50-ingestion/{loadText-ploadText,hdf5-parquet,kafka-mqtt}.md`.634- `docs/60-api/{python-api,java-api,cpp-api,type-mapping}.md`.635- `docs/70-perf/{partition-pruning,query-optimization,memory-threading,slow-query-diagnosis,jit-guide}.md`.636- `docs/90-admin/{cluster,backup-restore,security}.md`.637- `docs/backtest/{README,backtest-plugin-guide,matching-engine-guide,assets,traps,factors,tutorials-index}.md`.638- `docs/tutorials/README.md`, `docs/plugins/README.md`, `docs/modules/README.md` — curated navigation indexes.639- `patterns/*.md` — "how do I do X" recipes.640- `examples/*.dos`, `examples/*.py` — runnable end-to-end scripts.641- `evals/{README,scoring,run}.md` + `evals/tasks/*.md` — regression battery.642- `docs/cheatsheet.md` — compressed top-traps.643- `docs/cn-keywords.md` — CN↔EN keyword map.644- `scripts/lookup.py` — agent-invokable CLI for error codes / functions / topics.645- `SKILL.md` — this file.646647Rebuild after upstream changes:648649```powershell650python skills/dolphindb/scripts/build_from_docs.py651```652653Only files carrying the auto-mirror marker are deleted/rewritten; anything654you wrote manually is preserved across rebuilds.