Skip to content

Configuration and paths

Setting sources and precedence, the available settings, and the directories CJTrade writes to.

Where settings come from

Settings are KEY = value pairs. Each key is resolved from these sources in order; the first value found wins:

  1. an environment variable (export API_KEY=..., or API_KEY=... command),
  2. a .env file in the working directory,
  3. any *.cjconf file in the working directory or below it (shallower directories first, then alphabetical),
  4. *.cjconf files in the user config directory (see Paths),
  5. the defaults shipped with CJTrade (*.cjsys files).

An exported variable therefore overrides any file, and a project file overrides one in the user config directory.

*.cjconf files hold your settings and secrets; keep them out of git (the repository's .gitignore already excludes them). Generate a starting file with bash scripts/gen_config.sh arenax or ... sinopac.

Which file did a value come from?

cjtrade.pkgs.config.config_loader.describe_sources() prints every setting with its source file or variable.

Broker settings (*.cjconf)

Key Used by Meaning
API_KEY ArenaX, Sinopac ArenaX: testkey123. Sinopac: your API key
SECRET_KEY Sinopac your API secret
CA_CERT_PATH Sinopac path to your Sinopac.pfx certificate
CA_PASSWORD Sinopac the certificate's password
SIMULATION Sinopac y for Sinopac's sandbox, n for your real account (the generated file says n)
LLM_MODEL, LLM_API_KEY, GEMINI_API_KEY LLM clients, CJShell llm which model and its key
FINMIND_TOKEN FinMind price source optional; raises the request limit

CJTrade-wide variables

Variable Meaning
CJTRADE_HOME root for every directory in the Paths table below
CJTRADE_OFFLINE=1 network price sources fail instead of connecting
CJTRADE_LOG_LEVEL DEBUG, INFO (default), WARNING, ...
ARENAX_PORT the port AccountClient connects to on ArenaX (default 8801)
I_UNDERSTAND_REAL_TRADING_RISKS=y required to start arenaxd --backend=real

ArenaX server settings (AX_*)

Per-backend defaults live in src/cjtrade/apps/ArenaX/configs/<backend>.cjsys; set the variable to override.

Variable Default (demo) Meaning
AX_HOST_PORT 8801 port (backtest 8802, paper 8803, real 8888)
AX_DATA_SOURCES yfinance price sources, as --data
AX_PRICE_DB_PATH shared cache price file, as --price-db
AX_INITIAL_BALANCE 100000 starting cash of a fresh account
AX_STATE_FILE account snapshot to resume from instead of a fresh account
AX_BACKTEST_DURATION_DAYS 11 (backtest 300) days of prices to load from the start date
AX_BACKTEST_PLAYBACK_SPEED 120 market seconds per real second
AX_SKIP_NON_TRADING_HOURS y jump over nights and weekends
AX_COMMISSION_DISCOUNT 1.0 commission multiplier; 0.6 is a 六折 discount
AX_SLIPPAGE_MODEL, AX_SLIPPAGE_PCT none, 0.0005 slippage model and size (not yet applied to ArenaX fills)

FinHub settings (FINHUB_*)

See the FinHub README.

Paths

Folder Holds macOS Linux
config *.cjconf, finhub.env ~/Library/Application Support/cjtrade ~/.config/cjtrade
data reports, account snapshots, FinHub's database ~/Library/Application Support/cjtrade ~/.local/share/cjtrade
cache the price cache arenax_price.db ~/Library/Caches/cjtrade ~/.cache/cjtrade
state, logs runtime state, log files ~/Library/Application Support/cjtrade, ~/Library/Logs/cjtrade ~/.local/state/cjtrade, ~/.local/state/cjtrade/log

With CJTRADE_HOME=/some/path, they become /some/path/config, /some/path/data, /some/path/cache, /some/path/state and /some/path/logs. arenaxd prints the directories it uses at startup.

API

Warning

load_supported_config_files() writes into os.environ for the whole process (first source wins), and the paths helpers create directories the first time they are asked.

cjtrade.pkgs.config.config_loader

Loading of .cjconf configuration files.

ONE RULE

The first source to set a key wins. Later sources cannot overwrite it. That is load_dotenv(override=False), and it applies uniformly to every source below.

So the search order is the precedence order, most specific first:

0. environment variables already set     (set before we run, so nothing
                                          in a file can displace them)
1. ./.env
2. ./**/*.cjconf                         shallower before deeper,
                                         alphabetical within a depth
3. <user config dir>/*.cjconf            see pkgs.paths.config_dir()

Bundled *.cjsys defaults are not loaded here. Apps load them separately (brokerside_server.load_cjsys) after calling this, which under the first-wins rule makes package defaults the weakest source of all -- correct for defaults, but worth knowing when a .cjsys value appears to be ignored.

Differences from git, deliberately kept for now

git config applies the least specific scope first and lets later ones overwrite, so the most specific wins by being applied last. Here the most specific wins by being applied first. The resolved value usually agrees, but the mechanism is inverted, and flipping it would silently change what every existing deployment resolves to. Tracked in ref/TODO.md under "Config provenance", together with recording which file each key came from.

Within a directory the order used to be whatever rglob returned, i.e. the filesystem's readdir order -- so two .cjconf files setting the same key resolved differently on different machines. _discover now sorts by depth then path, which is deterministic and matches git's local-beats-parent intuition.

CJTradeConfiguration

Placeholder for a hierarchical configuration object.

Warnings

Not implemented; the class is empty.

default_config_paths()

Search roots, most specific first. Resolved lazily.

Not a module-level constant: paths.config_dir() creates the directory, and evaluating this at import time would create it just by importing.

Warnings

Calling this creates the user config directory if it does not exist.

Source code in src/cjtrade/pkgs/config/config_loader.py
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def default_config_paths() -> List[Path]:
    """Search roots, most specific first. Resolved lazily.

    Not a module-level constant: ``paths.config_dir()`` creates the directory,
    and evaluating this at import time would create it just by importing.

    Warnings
    --------
    Calling this creates the user config directory if it does not exist.
    """
    from cjtrade.pkgs import paths

    return [
        Path(".env"),
        Path.cwd(),                 # project-local *.cjconf, searched recursively
        paths.config_dir(),         # user-level *.cjconf
    ]

config_sources(paths_=_UNSET, recursive_pattern=SUPPORTED_FILE_PATTERN)

The files that would be loaded, in precedence order. Loads nothing.

Useful on its own for answering "which files is this process reading?", and it is the ordering the provenance work in ref/TODO.md will attach sources to.

Pass None to mean "no sources at all"; omit the argument for the defaults.

Parameters:

Name Type Description Default
paths_ iterable of str or Path

Search roots: files, directories or glob patterns.

_UNSET
recursive_pattern str

Glob applied when a root is a directory.

SUPPORTED_FILE_PATTERN

Returns:

Type Description
list of Path

Each resolved file appears once, at its first position.

Warnings

With the default roots, creates the user config directory if missing.

Source code in src/cjtrade/pkgs/config/config_loader.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
def config_sources(
    paths_=_UNSET,
    recursive_pattern: str = SUPPORTED_FILE_PATTERN,
) -> List[Path]:
    """The files that would be loaded, in precedence order. Loads nothing.

    Useful on its own for answering "which files is this process reading?", and
    it is the ordering the provenance work in ref/TODO.md will attach sources to.

    Pass None to mean "no sources at all"; omit the argument for the defaults.

    Parameters
    ----------
    paths_ : iterable of str or Path, optional
        Search roots: files, directories or glob patterns.
    recursive_pattern : str
        Glob applied when a root is a directory.

    Returns
    -------
    list of Path
        Each resolved file appears once, at its first position.

    Warnings
    --------
    With the default roots, creates the user config directory if missing.
    """
    if paths_ is None:
        return []
    roots = default_config_paths() if paths_ is _UNSET else list(paths_)
    ordered: List[Path] = []
    seen = set()
    for entry in roots:
        for f in _discover(entry, recursive_pattern):
            resolved = f.resolve()
            if resolved not in seen:
                seen.add(resolved)
                ordered.append(f)
    return ordered

load_supported_config_files(paths=_UNSET, recursive_pattern=SUPPORTED_FILE_PATTERN, override=False)

Load every discovered config file into os.environ.

Parameters:

Name Type Description Default
paths iterable of str or Path

Search roots, most specific first. Omit for default_config_paths(); pass None to load nothing.

_UNSET
recursive_pattern str

Glob applied when a root is a directory.

SUPPORTED_FILE_PATTERN
override bool

Leave at False to keep the first-wins rule. Passing True inverts the precedence of every source at once, so do it knowingly.

False

Returns:

Type Description
list of str

The loaded file paths as strings, in the order they were applied.

Warnings

Mutates os.environ for the whole process. With the default roots, also creates the user config directory if missing.

Source code in src/cjtrade/pkgs/config/config_loader.py
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
def load_supported_config_files(
    paths=_UNSET,
    recursive_pattern: str = SUPPORTED_FILE_PATTERN,
    override: bool = False,
) -> List[str]:
    """Load every discovered config file into ``os.environ``.

    Parameters
    ----------
    paths : iterable of str or Path, optional
        Search roots, most specific first. Omit for
        ``default_config_paths()``; pass None to load nothing.
    recursive_pattern : str
        Glob applied when a root is a directory.
    override : bool
        Leave at False to keep the first-wins rule. Passing True
        inverts the precedence of every source at once, so do it knowingly.

    Returns
    -------
    list of str
        The loaded file paths as strings, in the order they were applied.

    Warnings
    --------
    Mutates ``os.environ`` for the whole process. With the default roots,
    also creates the user config directory if missing.
    """
    loaded: List[str] = []
    for f in config_sources(paths, recursive_pattern):
        load_dotenv(str(f), override=override)
        loaded.append(str(f))

    for l in loaded:
        log.info("loaded cfg file %s", l)
    return loaded

describe_sources(paths=_UNSET, recursive_pattern=SUPPORTED_FILE_PATTERN)

Human-readable listing of the search order, for diagnostics.

Warnings

With the default roots, creates the user config directory if missing.

Source code in src/cjtrade/pkgs/config/config_loader.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
def describe_sources(
    paths=_UNSET,
    recursive_pattern: str = SUPPORTED_FILE_PATTERN,
) -> str:
    """Human-readable listing of the search order, for diagnostics.

    Warnings
    --------
    With the default roots, creates the user config directory if missing.
    """
    files = config_sources(paths, recursive_pattern)
    if not files:
        return "No config files found."
    lines = ["Config files, in precedence order (first to set a key wins):"]
    lines += [f"  {i}. {f}" for i, f in enumerate(files, 1)]
    return "\n".join(lines)

cjtrade.pkgs.paths

Where CJTrade keeps user data, config, cache, state and logs.

Single source of truth for every path that is not source code. Importing this instead of writing a literal keeps three things true:

  1. It is cross-platform. Hard-coding "./data/..." puts user data inside whatever directory the process happened to start in -- usually the repo, so a trading account's mirror DB ends up next to the code that reads it, and a git clean can delete it. Hard-coding "~/.config/..." is wrong on macOS and Windows, which do not use XDG.

  2. It is relocatable. CJTRADE_HOME overrides everything, which is how you run two independent instances (say a paper and a backtest one) without them sharing a price cache or an account state.

  3. The categories mean something. platformdirs separates data (keep), cache (safe to delete, will be refetched), state (machine-local, survives reboot) and logs. Putting a 160MB refetchable price cache under "data" is why backups and du get confusing.

Typical locations
macOS    ~/Library/Application Support/cjtrade
         ~/Library/Caches/cjtrade
Linux    ~/.local/share/cjtrade        (XDG_DATA_HOME)
         ~/.cache/cjtrade              (XDG_CACHE_HOME)
Windows  %LOCALAPPDATA%\cjtrade

Override with CJTRADE_HOME=/some/path, which puts every category under it as data/, config/, cache/, state/ and logs/ -- handy for tests and for keeping a run entirely self-contained.

data_dir(*, ensure=True)

Durable user data: account states, mirror DBs. Losing this loses history.

Warnings

Creates the directory unless ensure=False.

Source code in src/cjtrade/pkgs/paths.py
63
64
65
66
67
68
69
70
def data_dir(*, ensure: bool = True) -> Path:
    """Durable user data: account states, mirror DBs. Losing this loses history.

    Warnings
    --------
    Creates the directory unless ``ensure=False``.
    """
    return _resolve("data", _DIRS.user_data_dir, ensure=ensure)

config_dir(*, ensure=True)

User config: .cjconf files and anything else the user edits by hand.

Warnings

Creates the directory unless ensure=False.

Source code in src/cjtrade/pkgs/paths.py
73
74
75
76
77
78
79
80
def config_dir(*, ensure: bool = True) -> Path:
    """User config: .cjconf files and anything else the user edits by hand.

    Warnings
    --------
    Creates the directory unless ``ensure=False``.
    """
    return _resolve("config", _DIRS.user_config_dir, ensure=ensure)

cache_dir(*, ensure=True)

Refetchable data: the ArenaX price cache. Safe to delete at any time.

Warnings

Creates the directory unless ensure=False.

Source code in src/cjtrade/pkgs/paths.py
83
84
85
86
87
88
89
90
def cache_dir(*, ensure: bool = True) -> Path:
    """Refetchable data: the ArenaX price cache. Safe to delete at any time.

    Warnings
    --------
    Creates the directory unless ``ensure=False``.
    """
    return _resolve("cache", _DIRS.user_cache_dir, ensure=ensure)

state_dir(*, ensure=True)

Machine-local state that is not user-authored: saved form answers.

Warnings

Creates the directory unless ensure=False.

Source code in src/cjtrade/pkgs/paths.py
 93
 94
 95
 96
 97
 98
 99
100
def state_dir(*, ensure: bool = True) -> Path:
    """Machine-local state that is not user-authored: saved form answers.

    Warnings
    --------
    Creates the directory unless ``ensure=False``.
    """
    return _resolve("state", _DIRS.user_state_dir, ensure=ensure)

log_dir(*, ensure=True)

Log files.

Warnings

Creates the directory unless ensure=False.

Source code in src/cjtrade/pkgs/paths.py
103
104
105
106
107
108
109
110
def log_dir(*, ensure: bool = True) -> Path:
    """Log files.

    Warnings
    --------
    Creates the directory unless ``ensure=False``.
    """
    return _resolve("logs", _DIRS.user_log_dir, ensure=ensure)

price_db_path()

ArenaX historical price cache. Cache, not data: it is refetchable.

Warnings

Creates the cache directory if missing (not the file).

Source code in src/cjtrade/pkgs/paths.py
116
117
118
119
120
121
122
123
def price_db_path() -> Path:
    """ArenaX historical price cache. Cache, not data: it is refetchable.

    Warnings
    --------
    Creates the cache directory if missing (not the file).
    """
    return cache_dir() / "arenax_price.db"

mirror_db_path(broker, username='')

Local mirror of a broker's orders and fills.

Data, not cache: CJ_OrderMap here is the only link between a CJTrade order id and the broker's own id, so losing it orphans live orders.

Parameters:

Name Type Description Default
broker str

Broker name.

required
username str

If given, the file is <broker>_<username>.db.

''
Warnings

Creates the data directory if missing, but not mirrors/ or the file.

Source code in src/cjtrade/pkgs/paths.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def mirror_db_path(broker: str, username: str = "") -> Path:
    """Local mirror of a broker's orders and fills.

    Data, not cache: CJ_OrderMap here is the only link between a CJTrade order
    id and the broker's own id, so losing it orphans live orders.

    Parameters
    ----------
    broker : str
        Broker name.
    username : str, optional
        If given, the file is ``<broker>_<username>.db``.

    Warnings
    --------
    Creates the data directory if missing, but not ``mirrors/`` or the file.
    """
    stem = f"{broker}_{username}" if username else broker
    return data_dir() / "mirrors" / f"{stem}.db"

account_states_dir()

Per-session account snapshots, one immutable uuid-named file each.

Warnings

Creates the directory if missing.

Source code in src/cjtrade/pkgs/paths.py
147
148
149
150
151
152
153
154
155
156
def account_states_dir() -> Path:
    """Per-session account snapshots, one immutable uuid-named file each.

    Warnings
    --------
    Creates the directory if missing.
    """
    d = data_dir() / "account_states"
    d.mkdir(parents=True, exist_ok=True)
    return d

reports_dir()

Backtest reports: HTML tearsheets and pickled BacktestResults.

Data, not cache: a report describes one run of a strategy against one account state, and neither can be reconstructed once the account has moved on -- so unlike the price cache, deleting this loses something.

Warnings

Creates the directory if missing.

Source code in src/cjtrade/pkgs/paths.py
159
160
161
162
163
164
165
166
167
168
169
170
171
172
def reports_dir() -> Path:
    """Backtest reports: HTML tearsheets and pickled BacktestResults.

    Data, not cache: a report describes one run of a strategy against one
    account state, and neither can be reconstructed once the account has moved
    on -- so unlike the price cache, deleting this loses something.

    Warnings
    --------
    Creates the directory if missing.
    """
    d = data_dir() / "reports"
    d.mkdir(parents=True, exist_ok=True)
    return d

form_state_dir()

Remembered answers for pkgs.ui forms, keyed by schema stem.

Warnings

Creates the directory if missing.

Source code in src/cjtrade/pkgs/paths.py
175
176
177
178
179
180
181
182
183
184
def form_state_dir() -> Path:
    """Remembered answers for pkgs.ui forms, keyed by schema stem.

    Warnings
    --------
    Creates the directory if missing.
    """
    d = state_dir() / "form_state"
    d.mkdir(parents=True, exist_ok=True)
    return d

log_path(name)

A named log file, e.g. log_path("shioaji.log").

Warnings

Creates the log directory if missing (not the file).

Source code in src/cjtrade/pkgs/paths.py
187
188
189
190
191
192
193
194
def log_path(name: str) -> Path:
    """A named log file, e.g. log_path("shioaji.log").

    Warnings
    --------
    Creates the log directory if missing (not the file).
    """
    return log_dir() / name

describe()

Human-readable summary of every location, for diagnostics.

cjtrade subcommands print this so a user reporting a problem can say where their data actually lives instead of guessing.

Source code in src/cjtrade/pkgs/paths.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
def describe() -> str:
    """Human-readable summary of every location, for diagnostics.

    `cjtrade` subcommands print this so a user reporting a problem can say
    where their data actually lives instead of guessing.
    """
    override = _root_override()
    lines = [
        f"CJTRADE_HOME : {override if override else '(unset — using platform defaults)'}",
        f"data         : {data_dir(ensure=False)}",
        f"config       : {config_dir(ensure=False)}",
        f"cache        : {cache_dir(ensure=False)}",
        f"state        : {state_dir(ensure=False)}",
        f"logs         : {log_dir(ensure=False)}",
        f"reports      : {data_dir(ensure=False) / 'reports'}",
    ]
    return "\n".join(lines)

legacy_data_warning()

Warn when the pre-platformdirs ./data directory still holds files.

Deliberately does not move anything: the price cache runs into the hundreds of megabytes and has live -shm/-wal sidecars, so relocating it underneath a running process is a good way to corrupt it. Tell the user the command instead and let them pick the moment.

Source code in src/cjtrade/pkgs/paths.py
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
def legacy_data_warning() -> str | None:
    """Warn when the pre-platformdirs ./data directory still holds files.

    Deliberately does not move anything: the price cache runs into the hundreds
    of megabytes and has live -shm/-wal sidecars, so relocating it underneath a
    running process is a good way to corrupt it. Tell the user the command
    instead and let them pick the moment.
    """
    if not LEGACY_DATA_DIR.is_dir():
        return None
    leftovers = [p for p in LEGACY_DATA_DIR.iterdir() if p.name != ".gitkeep"]
    if not leftovers:
        return None
    return (
        f"Found {len(leftovers)} file(s) in the legacy ./data directory, which is "
        f"no longer read. To keep your price cache and account history:\n"
        f"    mv data/arenax_price.db* {cache_dir(ensure=False)}/\n"
        f"    mv data/account_states   {data_dir(ensure=False)}/\n"
        f"    mkdir -p {data_dir(ensure=False)}/mirrors && mv data/*.db "
        f"{data_dir(ensure=False)}/mirrors/\n"
        f"Otherwise ./data can be deleted; the cache will be refetched."
    )