capitalcom-cli 0.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- capital_cli/__init__.py +3 -0
- capital_cli/__main__.py +6 -0
- capital_cli/cli/__init__.py +1 -0
- capital_cli/cli/account_cmds.py +189 -0
- capital_cli/cli/app.py +88 -0
- capital_cli/cli/context.py +45 -0
- capital_cli/cli/live_guard.py +12 -0
- capital_cli/cli/market_cmds.py +165 -0
- capital_cli/cli/output.py +125 -0
- capital_cli/cli/runner.py +96 -0
- capital_cli/cli/session_cmds.py +127 -0
- capital_cli/cli/stream_cmds.py +263 -0
- capital_cli/cli/trade_cmds.py +549 -0
- capital_cli/cli/watchlist_cmds.py +132 -0
- capital_cli/core/__init__.py +1 -0
- capital_cli/core/config.py +152 -0
- capital_cli/core/errors.py +233 -0
- capital_cli/core/http_client.py +297 -0
- capital_cli/core/models.py +328 -0
- capital_cli/core/rate_limit.py +173 -0
- capital_cli/core/risk.py +417 -0
- capital_cli/core/session.py +219 -0
- capital_cli/core/state.py +97 -0
- capital_cli/core/utils.py +87 -0
- capital_cli/core/websocket_client.py +480 -0
- capitalcom_cli-0.4.0.dist-info/METADATA +433 -0
- capitalcom_cli-0.4.0.dist-info/RECORD +32 -0
- capitalcom_cli-0.4.0.dist-info/WHEEL +5 -0
- capitalcom_cli-0.4.0.dist-info/entry_points.txt +2 -0
- capitalcom_cli-0.4.0.dist-info/licenses/LICENSE +202 -0
- capitalcom_cli-0.4.0.dist-info/licenses/NOTICE +18 -0
- capitalcom_cli-0.4.0.dist-info/top_level.txt +1 -0
capital_cli/__init__.py
ADDED
capital_cli/__main__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Typer + Rich presentation layer."""
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"""capctl account ... — accounts, preferences, history, demo top-up."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import typer
|
|
8
|
+
|
|
9
|
+
from capital_cli.cli.runner import run
|
|
10
|
+
from capital_cli.core.config import get_config
|
|
11
|
+
from capital_cli.core.errors import ConfirmRequiredError
|
|
12
|
+
from capital_cli.core.http_client import get_client
|
|
13
|
+
from capital_cli.core.risk import get_risk_engine
|
|
14
|
+
from capital_cli.core.session import get_session_manager
|
|
15
|
+
|
|
16
|
+
app = typer.Typer(no_args_is_help=True, help="Accounts: list, preferences, history.")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@app.command("list")
|
|
20
|
+
def list_accounts(ctx: typer.Context) -> None:
|
|
21
|
+
"""List all trading accounts."""
|
|
22
|
+
out = ctx.obj.out
|
|
23
|
+
sm = get_session_manager()
|
|
24
|
+
client = get_client()
|
|
25
|
+
|
|
26
|
+
async def _do() -> dict[str, Any]:
|
|
27
|
+
await sm.ensure_logged_in()
|
|
28
|
+
data = (await client.get("/accounts")).json()
|
|
29
|
+
data["active_account_id"] = sm.account_id
|
|
30
|
+
return data
|
|
31
|
+
|
|
32
|
+
data = run(out, _do, label="account list")
|
|
33
|
+
if out.json_mode:
|
|
34
|
+
out.raw(data)
|
|
35
|
+
else:
|
|
36
|
+
rows = [
|
|
37
|
+
{
|
|
38
|
+
"accountId": a.get("accountId"),
|
|
39
|
+
"accountName": a.get("accountName"),
|
|
40
|
+
"balance": (a.get("balance") or {}).get("balance"),
|
|
41
|
+
"currency": a.get("currency"),
|
|
42
|
+
"active": a.get("accountId") == data.get("active_account_id"),
|
|
43
|
+
}
|
|
44
|
+
for a in data.get("accounts", [])
|
|
45
|
+
]
|
|
46
|
+
out.rows(
|
|
47
|
+
rows,
|
|
48
|
+
["accountId", "accountName", "balance", "currency", "active"],
|
|
49
|
+
title="Accounts",
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@app.command("prefs-get")
|
|
54
|
+
def prefs_get(ctx: typer.Context) -> None:
|
|
55
|
+
"""Get account preferences (hedging, leverage)."""
|
|
56
|
+
out = ctx.obj.out
|
|
57
|
+
sm = get_session_manager()
|
|
58
|
+
client = get_client()
|
|
59
|
+
|
|
60
|
+
async def _do() -> dict[str, Any]:
|
|
61
|
+
await sm.ensure_logged_in()
|
|
62
|
+
return (await client.get("/accounts/preferences")).json()
|
|
63
|
+
|
|
64
|
+
out.record(run(out, _do, label="account prefs-get"), title="Account preferences")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@app.command("prefs-set")
|
|
68
|
+
def prefs_set(
|
|
69
|
+
ctx: typer.Context,
|
|
70
|
+
hedging: bool | None = typer.Option(
|
|
71
|
+
None, "--hedging/--no-hedging", help="Enable/disable hedging mode."
|
|
72
|
+
),
|
|
73
|
+
leverage: list[str] | None = typer.Option(
|
|
74
|
+
None,
|
|
75
|
+
"--leverage",
|
|
76
|
+
help="Per asset class, e.g. --leverage CRYPTOCURRENCIES=2 (repeatable). "
|
|
77
|
+
"Asset classes: SHARES, CURRENCIES, INDICES, CRYPTOCURRENCIES, COMMODITIES.",
|
|
78
|
+
),
|
|
79
|
+
yes: bool = typer.Option(False, "--yes", "-y", help="Confirm this risk-gated change."),
|
|
80
|
+
) -> None:
|
|
81
|
+
"""Set account preferences: hedging mode and/or per-asset-class leverage (risk-gated)."""
|
|
82
|
+
out = ctx.obj.out
|
|
83
|
+
leverages: dict[str, int] = {}
|
|
84
|
+
for item in leverage or []:
|
|
85
|
+
if "=" not in item:
|
|
86
|
+
raise typer.BadParameter(f"Leverage must be ASSET=VALUE, got: {item!r}")
|
|
87
|
+
asset, _, value = item.partition("=")
|
|
88
|
+
try:
|
|
89
|
+
leverages[asset.strip().upper()] = int(value)
|
|
90
|
+
except ValueError:
|
|
91
|
+
raise typer.BadParameter(f"Leverage value must be an integer: {item!r}") from None
|
|
92
|
+
if hedging is None and not leverages:
|
|
93
|
+
raise typer.BadParameter("Provide --hedging/--no-hedging and/or --leverage.")
|
|
94
|
+
|
|
95
|
+
sm = get_session_manager()
|
|
96
|
+
client = get_client()
|
|
97
|
+
risk = get_risk_engine()
|
|
98
|
+
|
|
99
|
+
async def _do() -> dict[str, Any]:
|
|
100
|
+
await sm.ensure_logged_in()
|
|
101
|
+
risk.validate_mutation_guards(confirm=yes)
|
|
102
|
+
body: dict[str, Any] = {}
|
|
103
|
+
if hedging is not None:
|
|
104
|
+
body["hedgingMode"] = hedging
|
|
105
|
+
if leverages:
|
|
106
|
+
body["leverages"] = leverages
|
|
107
|
+
return (await client.put("/accounts/preferences", json=body)).json()
|
|
108
|
+
|
|
109
|
+
out.record(run(out, _do, label="account prefs-set"), title="Updated preferences")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
@app.command("history-activity")
|
|
113
|
+
def history_activity(
|
|
114
|
+
ctx: typer.Context,
|
|
115
|
+
last_period: int = typer.Option(600, "--last", help="Last N seconds (max 86400)."),
|
|
116
|
+
from_date: str | None = typer.Option(None, "--from", help="Start ISO 8601."),
|
|
117
|
+
to_date: str | None = typer.Option(None, "--to", help="End ISO 8601."),
|
|
118
|
+
detailed: bool = typer.Option(False, "--detailed", help="Include full activity details."),
|
|
119
|
+
deal_id: str | None = typer.Option(None, "--deal-id", help="Filter to a single deal ID."),
|
|
120
|
+
) -> None:
|
|
121
|
+
"""Get account activity history."""
|
|
122
|
+
out = ctx.obj.out
|
|
123
|
+
sm = get_session_manager()
|
|
124
|
+
client = get_client()
|
|
125
|
+
|
|
126
|
+
async def _do() -> dict[str, Any]:
|
|
127
|
+
await sm.ensure_logged_in()
|
|
128
|
+
params: dict[str, Any] = {"lastPeriod": last_period}
|
|
129
|
+
if from_date:
|
|
130
|
+
params["from"] = from_date
|
|
131
|
+
if to_date:
|
|
132
|
+
params["to"] = to_date
|
|
133
|
+
if detailed:
|
|
134
|
+
params["detailed"] = "true"
|
|
135
|
+
if deal_id:
|
|
136
|
+
params["dealId"] = deal_id
|
|
137
|
+
return (await client.get("/history/activity", params=params)).json()
|
|
138
|
+
|
|
139
|
+
out.raw(run(out, _do, label="account history-activity"))
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@app.command("history-transactions")
|
|
143
|
+
def history_transactions(
|
|
144
|
+
ctx: typer.Context,
|
|
145
|
+
last_period: int = typer.Option(600, "--last", help="Last N seconds."),
|
|
146
|
+
type_: str | None = typer.Option(None, "--type", help="Transaction type filter."),
|
|
147
|
+
from_date: str | None = typer.Option(None, "--from", help="Start ISO 8601."),
|
|
148
|
+
to_date: str | None = typer.Option(None, "--to", help="End ISO 8601."),
|
|
149
|
+
) -> None:
|
|
150
|
+
"""Get transaction history."""
|
|
151
|
+
out = ctx.obj.out
|
|
152
|
+
sm = get_session_manager()
|
|
153
|
+
client = get_client()
|
|
154
|
+
|
|
155
|
+
async def _do() -> dict[str, Any]:
|
|
156
|
+
await sm.ensure_logged_in()
|
|
157
|
+
params: dict[str, Any] = {"lastPeriod": last_period}
|
|
158
|
+
if type_:
|
|
159
|
+
params["type"] = type_
|
|
160
|
+
if from_date:
|
|
161
|
+
params["from"] = from_date
|
|
162
|
+
if to_date:
|
|
163
|
+
params["to"] = to_date
|
|
164
|
+
return (await client.get("/history/transactions", params=params)).json()
|
|
165
|
+
|
|
166
|
+
out.raw(run(out, _do, label="account history-transactions"))
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
@app.command()
|
|
170
|
+
def topup(
|
|
171
|
+
ctx: typer.Context,
|
|
172
|
+
amount: float = typer.Argument(..., help="Amount to add to the demo balance."),
|
|
173
|
+
yes: bool = typer.Option(False, "--yes", "-y", help="Confirm the top-up."),
|
|
174
|
+
) -> None:
|
|
175
|
+
"""Top up the demo account balance (demo environment only)."""
|
|
176
|
+
out = ctx.obj.out
|
|
177
|
+
sm = get_session_manager()
|
|
178
|
+
client = get_client()
|
|
179
|
+
config = get_config()
|
|
180
|
+
|
|
181
|
+
async def _do() -> dict[str, Any]:
|
|
182
|
+
if config.cap_env.value != "demo":
|
|
183
|
+
raise typer.BadParameter("Demo top-up is only available with --demo / CAP_ENV=demo.")
|
|
184
|
+
if config.cap_require_explicit_confirm and not yes:
|
|
185
|
+
raise ConfirmRequiredError()
|
|
186
|
+
await sm.ensure_logged_in()
|
|
187
|
+
return (await client.post("/accounts/topUp", json={"amount": amount})).json()
|
|
188
|
+
|
|
189
|
+
out.record(run(out, _do, label="account topup"), title="Demo top-up")
|
capital_cli/cli/app.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Root Typer application: global options and sub-command wiring."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import typer
|
|
8
|
+
|
|
9
|
+
from capital_cli import __version__
|
|
10
|
+
from capital_cli.cli import (
|
|
11
|
+
account_cmds,
|
|
12
|
+
market_cmds,
|
|
13
|
+
session_cmds,
|
|
14
|
+
stream_cmds,
|
|
15
|
+
trade_cmds,
|
|
16
|
+
watchlist_cmds,
|
|
17
|
+
)
|
|
18
|
+
from capital_cli.cli.context import init_state
|
|
19
|
+
|
|
20
|
+
app = typer.Typer(
|
|
21
|
+
no_args_is_help=True,
|
|
22
|
+
add_completion=True,
|
|
23
|
+
help="capctl — command-line client for the Capital.com Open API.",
|
|
24
|
+
rich_markup_mode="rich",
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _version_callback(value: bool) -> None:
|
|
29
|
+
if value:
|
|
30
|
+
typer.echo(f"capctl {__version__}")
|
|
31
|
+
raise typer.Exit()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@app.callback()
|
|
35
|
+
def main(
|
|
36
|
+
ctx: typer.Context,
|
|
37
|
+
json_output: bool = typer.Option(
|
|
38
|
+
False, "--json", help="Emit raw JSON instead of tables."
|
|
39
|
+
),
|
|
40
|
+
env_file: Path | None = typer.Option(
|
|
41
|
+
None, "--env-file", help="Path to a .env credentials file."
|
|
42
|
+
),
|
|
43
|
+
demo: bool = typer.Option(False, "--demo", help="Force the demo environment."),
|
|
44
|
+
live: bool = typer.Option(False, "--live", help="Force the live environment."),
|
|
45
|
+
account: str | None = typer.Option(
|
|
46
|
+
None, "--account", "-a", help="Account ID to use for this invocation."
|
|
47
|
+
),
|
|
48
|
+
verbose: bool = typer.Option(False, "--verbose", "-v", help="Enable debug logging."),
|
|
49
|
+
no_color: bool = typer.Option(
|
|
50
|
+
False, "--no-color", help="Disable colored output (also honors NO_COLOR)."
|
|
51
|
+
),
|
|
52
|
+
plain: bool = typer.Option(
|
|
53
|
+
False, "--plain", help="Tab-delimited rows for piping (no boxes/colors)."
|
|
54
|
+
),
|
|
55
|
+
version: bool | None = typer.Option(
|
|
56
|
+
None,
|
|
57
|
+
"--version",
|
|
58
|
+
callback=_version_callback,
|
|
59
|
+
is_eager=True,
|
|
60
|
+
help="Show version and exit.",
|
|
61
|
+
),
|
|
62
|
+
) -> None:
|
|
63
|
+
"""Global options applied to every subcommand."""
|
|
64
|
+
if demo and live:
|
|
65
|
+
raise typer.BadParameter("Use only one of --demo / --live.")
|
|
66
|
+
env = "demo" if demo else "live" if live else None
|
|
67
|
+
ctx.obj = init_state(
|
|
68
|
+
json_mode=json_output,
|
|
69
|
+
env_file=env_file,
|
|
70
|
+
env=env,
|
|
71
|
+
account=account,
|
|
72
|
+
verbose=verbose,
|
|
73
|
+
no_color=no_color,
|
|
74
|
+
plain=plain,
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
app.add_typer(session_cmds.app, name="session")
|
|
79
|
+
app.add_typer(market_cmds.app, name="market")
|
|
80
|
+
app.add_typer(account_cmds.app, name="account")
|
|
81
|
+
app.add_typer(trade_cmds.app, name="trade")
|
|
82
|
+
app.add_typer(watchlist_cmds.app, name="watchlist")
|
|
83
|
+
app.add_typer(stream_cmds.app, name="stream")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def run_cli() -> None:
|
|
87
|
+
"""Console-script entry point (see pyproject [project.scripts])."""
|
|
88
|
+
app()
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Global CLI state and resolution of global options into core config env."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from capital_cli.cli.output import Output
|
|
10
|
+
from capital_cli.core.config import reset_config
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class AppState:
|
|
15
|
+
"""Carried on the Typer context object (ctx.obj) for every command."""
|
|
16
|
+
|
|
17
|
+
out: Output
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def init_state(
|
|
21
|
+
*,
|
|
22
|
+
json_mode: bool,
|
|
23
|
+
env_file: Path | None,
|
|
24
|
+
env: str | None,
|
|
25
|
+
account: str | None,
|
|
26
|
+
verbose: bool,
|
|
27
|
+
no_color: bool = False,
|
|
28
|
+
plain: bool = False,
|
|
29
|
+
) -> AppState:
|
|
30
|
+
"""
|
|
31
|
+
Apply global options to the environment, then build shared state.
|
|
32
|
+
|
|
33
|
+
Core config is read lazily via get_config(); setting env vars here (and
|
|
34
|
+
resetting the cached config) guarantees commands see the overrides.
|
|
35
|
+
"""
|
|
36
|
+
if env_file is not None:
|
|
37
|
+
os.environ["CAP_ENV_FILE"] = str(env_file)
|
|
38
|
+
if env is not None:
|
|
39
|
+
os.environ["CAP_ENV"] = env
|
|
40
|
+
if account is not None:
|
|
41
|
+
os.environ["CAP_DEFAULT_ACCOUNT_ID"] = account
|
|
42
|
+
if verbose:
|
|
43
|
+
os.environ["CAP_LOG_LEVEL"] = "DEBUG"
|
|
44
|
+
reset_config()
|
|
45
|
+
return AppState(out=Output(json_mode=json_mode, no_color=no_color or None, plain=plain))
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""Emit a loud banner before actions that hit the live (real-money) account."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from capital_cli.cli.output import Output
|
|
6
|
+
from capital_cli.core.config import CapEnv, get_config
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def warn_if_live(out: Output) -> None:
|
|
10
|
+
"""Print a live-account banner to stderr when the environment is live."""
|
|
11
|
+
if get_config().cap_env == CapEnv.LIVE:
|
|
12
|
+
out.banner_live()
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""capctl market ... — market data."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import typer
|
|
8
|
+
|
|
9
|
+
from capital_cli.cli.runner import run
|
|
10
|
+
from capital_cli.core.http_client import get_client
|
|
11
|
+
from capital_cli.core.session import get_session_manager
|
|
12
|
+
|
|
13
|
+
app = typer.Typer(no_args_is_help=True, help="Market data: search, prices, sentiment.")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@app.command()
|
|
17
|
+
def search(
|
|
18
|
+
ctx: typer.Context,
|
|
19
|
+
term: str | None = typer.Argument(None, help="Search term, e.g. 'Bitcoin'."),
|
|
20
|
+
epics: str | None = typer.Option(None, "--epics", help="Comma-separated EPICs to filter."),
|
|
21
|
+
limit: int = typer.Option(50, "--limit", help="Max results."),
|
|
22
|
+
) -> None:
|
|
23
|
+
"""Search markets by term or EPICs."""
|
|
24
|
+
out = ctx.obj.out
|
|
25
|
+
sm = get_session_manager()
|
|
26
|
+
client = get_client()
|
|
27
|
+
|
|
28
|
+
async def _do() -> dict[str, Any]:
|
|
29
|
+
await sm.ensure_logged_in()
|
|
30
|
+
params: dict[str, Any] = {}
|
|
31
|
+
if term:
|
|
32
|
+
params["searchTerm"] = term
|
|
33
|
+
if epics:
|
|
34
|
+
params["epics"] = epics
|
|
35
|
+
data = (await client.get("/markets", params=params)).json()
|
|
36
|
+
if "markets" in data and len(data["markets"]) > limit:
|
|
37
|
+
data["markets"] = data["markets"][:limit]
|
|
38
|
+
return data
|
|
39
|
+
|
|
40
|
+
data = run(out, _do, label="market search")
|
|
41
|
+
if out.json_mode:
|
|
42
|
+
out.raw(data)
|
|
43
|
+
else:
|
|
44
|
+
out.rows(
|
|
45
|
+
data.get("markets", []),
|
|
46
|
+
["epic", "instrumentName", "bid", "offer", "marketStatus"],
|
|
47
|
+
title="Markets",
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@app.command()
|
|
52
|
+
def get(ctx: typer.Context, epic: str = typer.Argument(..., help="Market EPIC.")) -> None:
|
|
53
|
+
"""Get full market details and dealing rules."""
|
|
54
|
+
out = ctx.obj.out
|
|
55
|
+
sm = get_session_manager()
|
|
56
|
+
client = get_client()
|
|
57
|
+
|
|
58
|
+
async def _do() -> dict[str, Any]:
|
|
59
|
+
await sm.ensure_logged_in()
|
|
60
|
+
return (await client.get(f"/markets/{epic}")).json()
|
|
61
|
+
|
|
62
|
+
out.raw(run(out, _do, label="market get"))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@app.command("nav-root")
|
|
66
|
+
def nav_root(ctx: typer.Context) -> None:
|
|
67
|
+
"""Get the root market-navigation tree."""
|
|
68
|
+
out = ctx.obj.out
|
|
69
|
+
sm = get_session_manager()
|
|
70
|
+
client = get_client()
|
|
71
|
+
|
|
72
|
+
async def _do() -> dict[str, Any]:
|
|
73
|
+
await sm.ensure_logged_in()
|
|
74
|
+
return (await client.get("/marketnavigation")).json()
|
|
75
|
+
|
|
76
|
+
data = run(out, _do, label="market nav-root")
|
|
77
|
+
if out.json_mode:
|
|
78
|
+
out.raw(data)
|
|
79
|
+
else:
|
|
80
|
+
out.rows(data.get("nodes", []), ["id", "name"], title="Market categories")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@app.command("nav-node")
|
|
84
|
+
def nav_node(
|
|
85
|
+
ctx: typer.Context,
|
|
86
|
+
node_id: str = typer.Argument(..., help="Navigation node ID."),
|
|
87
|
+
limit: int | None = typer.Option(None, "--limit", help="Max child nodes/markets (<=500)."),
|
|
88
|
+
) -> None:
|
|
89
|
+
"""Get child nodes/markets under a navigation node."""
|
|
90
|
+
out = ctx.obj.out
|
|
91
|
+
sm = get_session_manager()
|
|
92
|
+
client = get_client()
|
|
93
|
+
|
|
94
|
+
async def _do() -> dict[str, Any]:
|
|
95
|
+
await sm.ensure_logged_in()
|
|
96
|
+
params: dict[str, Any] = {}
|
|
97
|
+
if limit is not None:
|
|
98
|
+
params["limit"] = limit
|
|
99
|
+
return (await client.get(f"/marketnavigation/{node_id}", params=params)).json()
|
|
100
|
+
|
|
101
|
+
out.raw(run(out, _do, label="market nav-node"))
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@app.command()
|
|
105
|
+
def prices(
|
|
106
|
+
ctx: typer.Context,
|
|
107
|
+
epic: str = typer.Argument(..., help="Market EPIC."),
|
|
108
|
+
resolution: str = typer.Option(
|
|
109
|
+
"MINUTE_15",
|
|
110
|
+
"--resolution",
|
|
111
|
+
help="MINUTE, MINUTE_5, MINUTE_15, MINUTE_30, HOUR, HOUR_4, DAY, WEEK.",
|
|
112
|
+
),
|
|
113
|
+
max_candles: int = typer.Option(200, "--max", help="Max candles (<=1000)."),
|
|
114
|
+
from_date: str | None = typer.Option(None, "--from", help="Start date ISO 8601."),
|
|
115
|
+
to_date: str | None = typer.Option(None, "--to", help="End date ISO 8601."),
|
|
116
|
+
) -> None:
|
|
117
|
+
"""Get historical OHLC prices."""
|
|
118
|
+
out = ctx.obj.out
|
|
119
|
+
sm = get_session_manager()
|
|
120
|
+
client = get_client()
|
|
121
|
+
|
|
122
|
+
async def _do() -> dict[str, Any]:
|
|
123
|
+
await sm.ensure_logged_in()
|
|
124
|
+
params: dict[str, Any] = {"resolution": resolution, "max": max_candles}
|
|
125
|
+
if from_date:
|
|
126
|
+
params["from"] = from_date
|
|
127
|
+
if to_date:
|
|
128
|
+
params["to"] = to_date
|
|
129
|
+
return (await client.get(f"/prices/{epic}", params=params)).json()
|
|
130
|
+
|
|
131
|
+
out.raw(run(out, _do, label="market prices"))
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
@app.command()
|
|
135
|
+
def sentiment(
|
|
136
|
+
ctx: typer.Context,
|
|
137
|
+
market_ids: str = typer.Argument(
|
|
138
|
+
..., help="Market ID, or comma-separated IDs for a batch (e.g. 'GOLD,SILVER')."
|
|
139
|
+
),
|
|
140
|
+
) -> None:
|
|
141
|
+
"""Get client sentiment (long vs short %) for one or several markets."""
|
|
142
|
+
out = ctx.obj.out
|
|
143
|
+
sm = get_session_manager()
|
|
144
|
+
client = get_client()
|
|
145
|
+
ids = [m.strip() for m in market_ids.split(",") if m.strip()]
|
|
146
|
+
if not ids:
|
|
147
|
+
raise typer.BadParameter("Provide at least one market ID.")
|
|
148
|
+
|
|
149
|
+
async def _do() -> dict[str, Any]:
|
|
150
|
+
await sm.ensure_logged_in()
|
|
151
|
+
if len(ids) == 1:
|
|
152
|
+
return (await client.get(f"/clientsentiment/{ids[0]}")).json()
|
|
153
|
+
return (await client.get("/clientsentiment", params={"marketIds": ",".join(ids)})).json()
|
|
154
|
+
|
|
155
|
+
data = run(out, _do, label="market sentiment")
|
|
156
|
+
if out.json_mode:
|
|
157
|
+
out.raw(data)
|
|
158
|
+
elif len(ids) == 1:
|
|
159
|
+
out.record(data, title=f"Sentiment: {ids[0]}")
|
|
160
|
+
else:
|
|
161
|
+
out.rows(
|
|
162
|
+
data.get("clientSentiments", []),
|
|
163
|
+
["marketId", "longPositionPercentage", "shortPositionPercentage"],
|
|
164
|
+
title="Client sentiment",
|
|
165
|
+
)
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""Output rendering: Rich tables for humans, raw JSON for scripts."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from rich.console import Console
|
|
11
|
+
from rich.table import Table
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def resolve_no_color(flag: bool = False) -> bool:
|
|
15
|
+
"""Decide whether to disable ANSI color (clig.dev / NO_COLOR conventions)."""
|
|
16
|
+
if flag:
|
|
17
|
+
return True
|
|
18
|
+
if os.environ.get("NO_COLOR") is not None: # presence alone disables color (no-color.org)
|
|
19
|
+
return True
|
|
20
|
+
if os.environ.get("CAPCTL_NO_COLOR"):
|
|
21
|
+
return True
|
|
22
|
+
if os.environ.get("TERM") == "dumb":
|
|
23
|
+
return True
|
|
24
|
+
return False
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _fmt(value: Any) -> str:
|
|
28
|
+
"""Format a scalar for table display."""
|
|
29
|
+
if value is None:
|
|
30
|
+
return "-"
|
|
31
|
+
if isinstance(value, bool):
|
|
32
|
+
return "✓" if value else "✗"
|
|
33
|
+
if isinstance(value, (dict, list)):
|
|
34
|
+
return json.dumps(value, default=str)
|
|
35
|
+
return str(value)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Output:
|
|
39
|
+
"""Renders command results either as Rich tables or as JSON."""
|
|
40
|
+
|
|
41
|
+
def __init__(
|
|
42
|
+
self,
|
|
43
|
+
json_mode: bool = False,
|
|
44
|
+
*,
|
|
45
|
+
no_color: bool | None = None,
|
|
46
|
+
plain: bool = False,
|
|
47
|
+
) -> None:
|
|
48
|
+
self.json_mode = json_mode
|
|
49
|
+
self.plain = plain
|
|
50
|
+
self.no_color = resolve_no_color() if no_color is None else no_color
|
|
51
|
+
self.console = Console(no_color=self.no_color)
|
|
52
|
+
self.err = Console(stderr=True, no_color=self.no_color)
|
|
53
|
+
|
|
54
|
+
def _print_json(self, payload: Any) -> None:
|
|
55
|
+
self.console.print_json(json.dumps(payload, default=str))
|
|
56
|
+
|
|
57
|
+
def record(self, payload: dict[str, Any], *, title: str | None = None) -> None:
|
|
58
|
+
"""Render a single object as a two-column key/value table."""
|
|
59
|
+
if self.json_mode:
|
|
60
|
+
self._print_json(payload)
|
|
61
|
+
return
|
|
62
|
+
if self.plain:
|
|
63
|
+
for key, value in payload.items():
|
|
64
|
+
print(f"{key}\t{_fmt(value)}")
|
|
65
|
+
return
|
|
66
|
+
table = Table(show_header=False, title=title, title_justify="left", expand=False)
|
|
67
|
+
table.add_column("Field", style="bold cyan", no_wrap=True)
|
|
68
|
+
table.add_column("Value")
|
|
69
|
+
for key, value in payload.items():
|
|
70
|
+
table.add_row(str(key), _fmt(value))
|
|
71
|
+
self.console.print(table)
|
|
72
|
+
|
|
73
|
+
def rows(
|
|
74
|
+
self,
|
|
75
|
+
items: Sequence[dict[str, Any]],
|
|
76
|
+
columns: Sequence[str],
|
|
77
|
+
*,
|
|
78
|
+
title: str | None = None,
|
|
79
|
+
) -> None:
|
|
80
|
+
"""Render a list of objects as a multi-column table."""
|
|
81
|
+
if self.json_mode:
|
|
82
|
+
self._print_json(list(items))
|
|
83
|
+
return
|
|
84
|
+
if self.plain:
|
|
85
|
+
for item in items:
|
|
86
|
+
print("\t".join(_fmt(item.get(col)) for col in columns))
|
|
87
|
+
return
|
|
88
|
+
if not items:
|
|
89
|
+
self.console.print("[dim]No results.[/]")
|
|
90
|
+
return
|
|
91
|
+
table = Table(title=title, title_justify="left", header_style="bold cyan")
|
|
92
|
+
for col in columns:
|
|
93
|
+
table.add_column(col)
|
|
94
|
+
for item in items:
|
|
95
|
+
table.add_row(*[_fmt(item.get(col)) for col in columns])
|
|
96
|
+
self.console.print(table)
|
|
97
|
+
|
|
98
|
+
def raw(self, payload: Any) -> None:
|
|
99
|
+
"""Print a payload as-is (JSON in json mode, pretty otherwise)."""
|
|
100
|
+
if self.json_mode:
|
|
101
|
+
self._print_json(payload)
|
|
102
|
+
else:
|
|
103
|
+
self.console.print(payload)
|
|
104
|
+
|
|
105
|
+
def error(self, code: str, message: str) -> None:
|
|
106
|
+
if self.json_mode:
|
|
107
|
+
self.err.print_json(
|
|
108
|
+
json.dumps({"ok": False, "error": {"code": code, "message": message}})
|
|
109
|
+
)
|
|
110
|
+
else:
|
|
111
|
+
self.err.print(f"[bold red]Error[/] [dim]({code})[/]: {message}")
|
|
112
|
+
|
|
113
|
+
def note(self, message: str) -> None:
|
|
114
|
+
if not self.json_mode:
|
|
115
|
+
self.err.print(f"[dim]{message}[/]")
|
|
116
|
+
|
|
117
|
+
def success(self, message: str) -> None:
|
|
118
|
+
if not self.json_mode:
|
|
119
|
+
self.err.print(f"[green]✓[/] {message}")
|
|
120
|
+
|
|
121
|
+
def banner_live(self) -> None:
|
|
122
|
+
"""Loud stderr banner before a live (real-money) action."""
|
|
123
|
+
# Intentionally not gated on json_mode: stdout stays pure (stderr only),
|
|
124
|
+
# and this real-money safety signal must always surface.
|
|
125
|
+
self.err.print("[bold white on red] ⚠ LIVE ACCOUNT — real money [/]")
|