charting

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Charting

图表绘制

⚠️ CRITICAL: DO NOT CALL DATA TOOLS

⚠️ 重要提示:请勿调用数据工具

NEVER call
price_chart
,
get_coin_ohlc_range_by_id
,
twelvedata_time_series
, or ANY market data tools when creating charts. Chart scripts fetch data internally. Calling these tools floods your context with 78KB+ of unnecessary data.
Workflow (4 steps):
  1. Read template from
    skills/charting/scripts/
  2. Write script to
    scripts/
  3. Run script with
    bash
  4. Call
    read_file
    on the output PNG, then display it using markdown image syntax:
    ![Chart description](output/filename.png)

You generate TradingView-quality candlestick charts. Dark theme, clean layout, professional colors. Every chart is a standalone Python script — no internal imports.
Additional Rules:
  • Chart scripts run in workspace and cannot import from
    core
    . Use
    requests
    library directly, NOT
    proxied_get()
    .
  • Templates include proxy auto-configuration. If
    PROXY_HOST
    env var exists, scripts automatically configure
    HTTP_PROXY
    /
    HTTPS_PROXY
    .
Tools:
write_file
,
bash
,
read_file
绝对不要在创建图表时调用
price_chart
get_coin_ohlc_range_by_id
twelvedata_time_series
或任何市场数据工具。图表脚本会在内部获取数据。调用这些工具会向你的上下文注入78KB以上的不必要数据。
工作流程(4步):
  1. skills/charting/scripts/
    读取模板
  2. 将脚本写入
    scripts/
    目录
  3. 使用
    bash
    运行脚本
  4. 对输出的PNG文件调用
    read_file
    ,然后使用Markdown图片语法展示:
    ![图表说明](output/filename.png)

你可以生成TradingView品质的K线图,采用深色主题、简洁布局、专业配色。每个图表都是独立的Python脚本——无需内部导入。
额外规则:
  • 图表脚本在工作区运行,无法从
    core
    导入。直接使用
    requests
    库,不要使用
    proxied_get()
  • 模板包含代理自动配置。如果存在
    PROXY_HOST
    环境变量,脚本会自动配置
    HTTP_PROXY
    /
    HTTPS_PROXY
工具:
write_file
bash
read_file

When to Use Which Chart

不同场景对应的图表类型

Simple price action → Candlestick with no indicators. Good for "show me BTC this month." Trend analysis → Add EMA/SMA overlays. Good for "is ETH in an uptrend?" Momentum check → Add RSI or MACD as subplots. Good for "is SOL overbought?" Full technical view → Candles + Bollinger Bands + RSI + MACD. Good for "give me the full picture on BTC." Volume analysis → Requires separate fetch from market_chart endpoint (OHLC endpoint has no volume). Asset comparison → Line chart comparing two assets (BTC vs Gold, ETH vs S&P500, etc.). Use comparison template for normalized or percentage-based comparisons.
简单价格走势 → 无指标的K线图。适用于“展示本月BTC走势”这类需求。 趋势分析 → 添加EMA/SMA叠加层。适用于“ETH是否处于上涨趋势?”这类需求。 动量检测 → 添加RSI或MACD作为子图。适用于“SOL是否超买?”这类需求。 完整技术视图 → K线 + 布林带 + RSI + MACD。适用于“展示BTC的完整技术面”这类需求。 成交量分析 → 需要从market_chart端点单独获取数据(OHLC端点不包含成交量)。 资产对比 → 折线图对比两种资产(BTC vs 黄金,ETH vs 标普500等)。使用对比模板进行标准化或百分比-based对比。

How to Build Charts

图表构建方法

Read and customize the template scripts in
skills/charting/scripts/
:
  • chart_template.py
    — Baseline candlestick chart with TradingView styling (crypto via CoinGecko)
  • chart_with_indicators.py
    — RSI, MACD, Bollinger Bands, EMA/SMA examples (crypto via CoinGecko)
  • chart_stock_template.py
    — Stock/forex chart using Twelve Data API
  • chart_comparison_template.py
    — Compare two assets (crypto vs commodity, stock vs crypto, etc.)
Copy the relevant template to
scripts/
, customize the config section (coin, days, indicators), and run it.
The templates handle all data fetching internally with retry logic and error handling.
Note: These templates are for market data visualization (price charts, indicators). For backtest result charts (equity curves, drawdowns, performance dashboards), add matplotlib charting directly to your backtest script — the data is already there, no need to re-fetch or create a separate file.
读取并自定义
skills/charting/scripts/
中的模板脚本:
  • chart_template.py
    — 带有TradingView样式的基础K线图(加密货币数据来自CoinGecko)
  • chart_with_indicators.py
    — RSI、MACD、布林带、EMA/SMA示例(加密货币数据来自CoinGecko)
  • chart_stock_template.py
    — 使用Twelve Data API的股票/外汇图表
  • chart_comparison_template.py
    — 对比两种资产(加密货币 vs 大宗商品,股票 vs 加密货币等)
将相关模板复制到
scripts/
目录,自定义配置部分(币种、天数、指标),然后运行脚本。
模板内置了重试逻辑和错误处理,会自动处理所有数据获取工作。
注意: 这些模板用于市场数据可视化(价格图表、指标)。对于回测结果图表(权益曲线、回撤、绩效仪表盘),直接在回测脚本中添加matplotlib绘图即可——数据已经存在,无需重新获取或创建单独文件。

TradingView Color Palette

TradingView配色方案

ElementColorHex
Up candlesTeal
#26a69a
Down candlesRed
#ef5350
BackgroundDark
#131722
GridSubtle dotted
#1e222d
Text / axesLight gray
#d1d4dc
MA linesBlue / Orange
#2196f3
/
#ff9800
RSI linePurple
#b39ddb
MACD lineBlue
#2196f3
Signal lineOrange
#ff9800
Do not deviate from this palette unless the user asks.
元素颜色十六进制码
上涨K线蓝绿色
#26a69a
下跌K线红色
#ef5350
背景深色
#131722
网格浅虚线
#1e222d
文本/坐标轴浅灰色
#d1d4dc
MA均线蓝色/橙色
#2196f3
/
#ff9800
RSI线紫色
#b39ddb
MACD线蓝色
#2196f3
信号线橙色
#ff9800
除非用户要求,否则请勿偏离此配色方案。

Data Source APIs

数据源API

CoinGecko (Crypto Only)

CoinGecko(仅加密货币)

Endpoint:
https://pro-api.coingecko.com/api/v3/coins/{coin_id}/ohlc/range
Auth: Header
x-cg-pro-api-key: {COINGECKO_API_KEY}
Use for: BTC, ETH, SOL, and all cryptocurrencies
Example:
python
url = f"https://pro-api.coingecko.com/api/v3/coins/{COIN_ID}/ohlc/range"
params = {"vs_currency": "usd", "from": from_ts, "to": now, "interval": "daily"}
headers = {"x-cg-pro-api-key": os.getenv("COINGECKO_API_KEY")}
resp = requests.get(url, params=params, headers=headers)
raw = resp.json()  # [[timestamp_ms, open, high, low, close], ...]
端点:
https://pro-api.coingecko.com/api/v3/coins/{coin_id}/ohlc/range
认证: 请求头
x-cg-pro-api-key: {COINGECKO_API_KEY}
适用场景: BTC、ETH、SOL及所有加密货币
示例:
python
url = f"https://pro-api.coingecko.com/api/v3/coins/{COIN_ID}/ohlc/range"
params = {"vs_currency": "usd", "from": from_ts, "to": now, "interval": "daily"}
headers = {"x-cg-pro-api-key": os.getenv("COINGECKO_API_KEY")}
resp = requests.get(url, params=params, headers=headers)
raw = resp.json()  # [[timestamp_ms, open, high, low, close], ...]

Twelve Data (Stocks, Forex, Commodities)

Twelve Data(股票、外汇、大宗商品)

Endpoint:
https://api.twelvedata.com/time_series
Auth: Query param
apikey={TWELVEDATA_API_KEY}
Use for: Stocks (AAPL, MSFT), Forex (EUR/USD), Commodities (XAU/USD for gold)
Common Symbols:
  • Stocks:
    AAPL
    ,
    MSFT
    ,
    GOOGL
    ,
    TSLA
    ,
    SPY
  • Forex:
    EUR/USD
    ,
    GBP/JPY
    ,
    USD/CHF
  • Commodities:
    XAU/USD
    (gold),
    XAG/USD
    (silver),
    CL/USD
    (crude oil)
Intervals:
1min
,
5min
,
15min
,
30min
,
1h
,
4h
,
1day
,
1week
,
1month
Example:
python
url = "https://api.twelvedata.com/time_series"
params = {
    "symbol": "XAU/USD",  # Gold spot price
    "interval": "1day",
    "outputsize": 90,  # Number of candles
    "apikey": os.getenv("TWELVEDATA_API_KEY")
}
resp = requests.get(url, params=params)
data = resp.json()
端点:
https://api.twelvedata.com/time_series
认证: 查询参数
apikey={TWELVEDATA_API_KEY}
适用场景: 股票(AAPL、MSFT)、外汇(EUR/USD)、大宗商品(XAU/USD代表黄金)
常见交易对:
  • 股票:
    AAPL
    ,
    MSFT
    ,
    GOOGL
    ,
    TSLA
    ,
    SPY
  • 外汇:
    EUR/USD
    ,
    GBP/JPY
    ,
    USD/CHF
  • 大宗商品:
    XAU/USD
    (黄金),
    XAG/USD
    (白银),
    CL/USD
    (原油)
时间间隔:
1min
,
5min
,
15min
,
30min
,
1h
,
4h
,
1day
,
1week
,
1month
示例:
python
url = "https://api.twelvedata.com/time_series"
params = {
    "symbol": "XAU/USD",  # 黄金现货价格
    "interval": "1day",
    "outputsize": 90,  # K线数量
    "apikey": os.getenv("TWELVEDATA_API_KEY")
}
resp = requests.get(url, params=params)
data = resp.json()

data["values"] = [{"datetime": "2024-01-01", "open": "2050.00", "high": "2060.00", ...}, ...]

data["values"] = [{"datetime": "2024-01-01", "open": "2050.00", "high": "2060.00", ...}, ...]


**IMPORTANT:** Twelve Data returns data in **reverse chronological order** (newest first). Always reverse the list before creating a DataFrame:
```python
values = data["values"][::-1]  # Reverse to oldest-first

**重要提示:** Twelve Data返回的数据是**逆时间顺序**(最新数据在前)。创建DataFrame前务必反转列表:
```python
values = data["values"][::-1]  # 反转以按从旧到新排序

Interval Selection Strategy

时间间隔选择策略

The templates now auto-select optimal intervals to minimize data volume while maintaining visual quality:
Time RangeAuto-Selected IntervalRationale
≤31 daysHourlyHigh granularity for short-term analysis
32-365 daysDailySufficient detail, lower data volume
>365 daysDailyDaily is optimal for long-term trends
Override: Set
INTERVAL = "daily"
or
INTERVAL = "hourly"
in the config to override auto-selection.
模板现在会自动选择最优时间间隔,在最小化数据量的同时保持可视化质量:
时间范围自动选择的时间间隔理由
≤31天小时级高粒度适合短期分析
32-365天日线级细节足够,数据量更小
>365天日线级日线级最适合长期趋势分析
手动覆盖: 在配置中设置
INTERVAL = "daily"
INTERVAL = "hourly"
以覆盖自动选择。

Key Gotchas

关键注意事项

  • savefig
    facecolor
    : You MUST set
    facecolor='#131722'
    and
    edgecolor='#131722'
    in
    savefig
    , or the saved PNG reverts to white background.
  • Title spacing: Prefix titles with
    \n
    to add spacing from the top edge.
  • returnfig=True
    : Use when you need post-plot customization (price formatting, annotations). When using it, call
    fig.savefig()
    manually — don't pass
    savefig
    to
    mpf.plot()
    .
  • No volume in OHLC: CoinGecko OHLC endpoint returns
    [timestamp_ms, open, high, low, close]
    only. Use
    volume=False
    or fetch volume separately from
    coin_chart
    endpoint.
  • Panel ratios: Set
    panel_ratios
    when adding indicator subplots. E.g.,
    (4, 1, 2)
    for candles + volume + one indicator,
    (5, 1, 2, 2)
    for two indicators.
  • Figure size: Default
    (14, 8)
    . Increase to
    (14, 10)
    or
    (14, 12)
    when adding subplots.
  • savefig
    背景色:
    必须在
    savefig
    中设置
    facecolor='#131722'
    edgecolor='#131722'
    ,否则保存的PNG会恢复为白色背景。
  • 标题间距: 在标题前添加
    \n
    以增加与顶部边缘的间距。
  • returnfig=True
    当需要对绘图进行后期自定义(价格格式化、注释)时使用。使用此参数时,需手动调用
    fig.savefig()
    ——不要将
    savefig
    传递给
    mpf.plot()
  • OHLC无成交量: CoinGecko的OHLC端点仅返回
    [timestamp_ms, open, high, low, close]
    。使用
    volume=False
    或从
    coin_chart
    端点单独获取成交量数据。
  • 面板比例: 添加指标子图时设置
    panel_ratios
    。例如,
    (4, 1, 2)
    对应K线 + 成交量 + 一个指标,
    (5, 1, 2, 2)
    对应两个指标。
  • 图表尺寸: 默认
    (14, 8)
    。添加子图时可增大到
    (14, 10)
    (14, 12)

Rules

规则

  • Paths are relative to workspace. Write to
    scripts/foo.py
    , not
    workspace/scripts/foo.py
    . The bash CWD is already workspace.
  • Always save to
    output/
    directory.
    Use
    os.makedirs("output", exist_ok=True)
    .
  • Always run the script with
    bash("python3 scripts/<name>.py")
    to verify it works.
  • Always call
    read_file
    on the generated PNG, then use markdown image syntax to display it:
    ![Chart](output/filename.png)
  • Scripts must be standalone. Use
    requests
    +
    os.getenv()
    . No internal imports, no dotenv.
  • CRITICAL: Do NOT use proxied_get() in chart scripts. Chart scripts are standalone and run in the workspace - they cannot import from
    core.http_client
    . Always use
    requests.get()
    and
    requests.post()
    directly. This is an exception to the PLATFORM.md proxy rules because these scripts execute outside the main Star Child process. The templates demonstrate the correct pattern.
  • Env vars are inherited.
    os.getenv("COINGECKO_API_KEY")
    works directly.
  • Default to dark theme unless user asks for light.
  • Filename should describe the chart. e.g.
    btc_30d_candles.png
    ,
    eth_7d_rsi_macd.png
    .
  • Data sources: Use CoinGecko API for crypto (BTC, ETH, etc). Use Twelve Data API for stocks, forex, and commodities (AAPL, EUR/USD, XAU/USD for gold). Never mix APIs - keep scripts focused on one data source.
  • Think about what you're measuring: Before creating a chart, ask yourself: "What question is the user trying to answer?" A normalized chart (all start at 100) shows relative trends but hides actual gain magnitude. If the user wants to know "which gained more" or is comparing investment performance, they need the actual multipliers (e.g., 50x vs 10x), not just lines that look similar.
  • 路径相对于工作区。 写入
    scripts/foo.py
    ,而非
    workspace/scripts/foo.py
    。bash的当前工作目录已设为工作区。
  • 始终保存到
    output/
    目录。
    使用
    os.makedirs("output", exist_ok=True)
  • 始终使用
    bash("python3 scripts/<name>.py")
    运行脚本
    以验证其可正常工作。
  • 始终对生成的PNG调用
    read_file
    ,然后使用Markdown图片语法展示:
    ![Chart](output/filename.png)
  • 脚本必须独立运行。 使用
    requests
    +
    os.getenv()
    。不要使用内部导入,不要使用dotenv。
  • 重要提示:请勿在图表脚本中使用proxied_get()。 图表脚本是独立的,在工作区运行——无法从
    core.http_client
    导入。请始终直接使用
    requests.get()
    requests.post()
    。这是对PLATFORM.md代理规则的例外,因为这些脚本在主Star Child进程之外执行。模板展示了正确的实现方式。
  • 环境变量可继承。
    os.getenv("COINGECKO_API_KEY")
    可直接使用。
  • 默认使用深色主题,除非用户要求浅色主题。
  • 文件名应描述图表内容。 例如
    btc_30d_candles.png
    ,
    eth_7d_rsi_macd.png
  • 数据源: 加密货币(BTC、ETH等)使用CoinGecko API。股票、外汇和大宗商品(AAPL、EUR/USD、XAU/USD代表黄金)使用Twelve Data API。请勿混合使用API——保持脚本专注于单一数据源。
  • 明确绘图目的: 创建图表前,先问自己:“用户想要解决什么问题?” 标准化图表(所有数据从100开始)展示相对趋势,但隐藏实际涨幅。如果用户想知道“哪个涨幅更大”或比较投资表现,他们需要实际的倍数(例如50倍 vs 10倍),而不是看起来相似的折线。

Troubleshooting

故障排除

401 Unauthorized Errors

401未授权错误

Templates auto-configure proxy from
PROXY_HOST
/
PROXY_PORT
env vars. If 401 errors occur:
Check environment:
bash
bash("env | grep -E 'PROXY|REQUESTS_CA'")
Expected vars:
  • PROXY_HOST
    /
    PROXY_PORT
    - Proxy address (templates use these to set HTTP_PROXY/HTTPS_PROXY)
  • REQUESTS_CA_BUNDLE
    - Proxy CA cert for SSL
  • COINGECKO_API_KEY
    /
    TWELVEDATA_API_KEY
    - Can be fake in proxied environments
If vars are missing, this is an environment configuration issue, not a script issue.
模板会从
PROXY_HOST
/
PROXY_PORT
环境变量自动配置代理。如果出现401错误:
检查环境:
bash
bash("env | grep -E 'PROXY|REQUESTS_CA'")
预期环境变量:
  • PROXY_HOST
    /
    PROXY_PORT
    - 代理地址(模板使用这些变量设置HTTP_PROXY/HTTPS_PROXY)
  • REQUESTS_CA_BUNDLE
    - 用于SSL的代理CA证书
  • COINGECKO_API_KEY
    /
    TWELVEDATA_API_KEY
    - 在代理环境中可以是模拟值
如果缺少变量,这是环境配置问题,而非脚本问题。