charting
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCharting
图表绘制
⚠️ CRITICAL: DO NOT CALL DATA TOOLS
⚠️ 重要提示:请勿调用数据工具
NEVER call , , , or ANY market data tools when creating charts. Chart scripts fetch data internally. Calling these tools floods your context with 78KB+ of unnecessary data.
price_chartget_coin_ohlc_range_by_idtwelvedata_time_seriesWorkflow (4 steps):
- Read template from
skills/charting/scripts/ - Write script to
scripts/ - Run script with
bash - Call on the output PNG, then display it using markdown image syntax:
read_file
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 . Use
corelibrary directly, NOTrequests.proxied_get() - Templates include proxy auto-configuration. If env var exists, scripts automatically configure
PROXY_HOST/HTTP_PROXY.HTTPS_PROXY
Tools: , ,
write_filebashread_file绝对不要在创建图表时调用、、或任何市场数据工具。图表脚本会在内部获取数据。调用这些工具会向你的上下文注入78KB以上的不必要数据。
price_chartget_coin_ohlc_range_by_idtwelvedata_time_series工作流程(4步):
- 从读取模板
skills/charting/scripts/ - 将脚本写入目录
scripts/ - 使用运行脚本
bash - 对输出的PNG文件调用,然后使用Markdown图片语法展示:
read_file
你可以生成TradingView品质的K线图,采用深色主题、简洁布局、专业配色。每个图表都是独立的Python脚本——无需内部导入。
额外规则:
- 图表脚本在工作区运行,无法从导入。直接使用
core库,不要使用requests。proxied_get() - 模板包含代理自动配置。如果存在环境变量,脚本会自动配置
PROXY_HOST/HTTP_PROXY。HTTPS_PROXY
工具:、、
write_filebashread_fileWhen 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/- — Baseline candlestick chart with TradingView styling (crypto via CoinGecko)
chart_template.py - — RSI, MACD, Bollinger Bands, EMA/SMA examples (crypto via CoinGecko)
chart_with_indicators.py - — Stock/forex chart using Twelve Data API
chart_stock_template.py - — Compare two assets (crypto vs commodity, stock vs crypto, etc.)
chart_comparison_template.py
Copy the relevant template to , customize the config section (coin, days, indicators), and run it.
scripts/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/- — 带有TradingView样式的基础K线图(加密货币数据来自CoinGecko)
chart_template.py - — RSI、MACD、布林带、EMA/SMA示例(加密货币数据来自CoinGecko)
chart_with_indicators.py - — 使用Twelve Data API的股票/外汇图表
chart_stock_template.py - — 对比两种资产(加密货币 vs 大宗商品,股票 vs 加密货币等)
chart_comparison_template.py
将相关模板复制到目录,自定义配置部分(币种、天数、指标),然后运行脚本。
scripts/模板内置了重试逻辑和错误处理,会自动处理所有数据获取工作。
注意: 这些模板用于市场数据可视化(价格图表、指标)。对于回测结果图表(权益曲线、回撤、绩效仪表盘),直接在回测脚本中添加matplotlib绘图即可——数据已经存在,无需重新获取或创建单独文件。
TradingView Color Palette
TradingView配色方案
| Element | Color | Hex |
|---|---|---|
| Up candles | Teal | |
| Down candles | Red | |
| Background | Dark | |
| Grid | Subtle dotted | |
| Text / axes | Light gray | |
| MA lines | Blue / Orange | |
| RSI line | Purple | |
| MACD line | Blue | |
| Signal line | Orange | |
Do not deviate from this palette unless the user asks.
| 元素 | 颜色 | 十六进制码 |
|---|---|---|
| 上涨K线 | 蓝绿色 | |
| 下跌K线 | 红色 | |
| 背景 | 深色 | |
| 网格 | 浅虚线 | |
| 文本/坐标轴 | 浅灰色 | |
| MA均线 | 蓝色/橙色 | |
| RSI线 | 紫色 | |
| MACD线 | 蓝色 | |
| 信号线 | 橙色 | |
除非用户要求,否则请勿偏离此配色方案。
Data Source APIs
数据源API
CoinGecko (Crypto Only)
CoinGecko(仅加密货币)
Endpoint:
Auth: Header
Use for: BTC, ETH, SOL, and all cryptocurrencies
https://pro-api.coingecko.com/api/v3/coins/{coin_id}/ohlc/rangex-cg-pro-api-key: {COINGECKO_API_KEY}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], ...]端点:
认证: 请求头
适用场景: BTC、ETH、SOL及所有加密货币
https://pro-api.coingecko.com/api/v3/coins/{coin_id}/ohlc/rangex-cg-pro-api-key: {COINGECKO_API_KEY}示例:
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:
Auth: Query param
Use for: Stocks (AAPL, MSFT), Forex (EUR/USD), Commodities (XAU/USD for gold)
https://api.twelvedata.com/time_seriesapikey={TWELVEDATA_API_KEY}Common Symbols:
- Stocks: ,
AAPL,MSFT,GOOGL,TSLASPY - Forex: ,
EUR/USD,GBP/JPYUSD/CHF - Commodities: (gold),
XAU/USD(silver),XAG/USD(crude oil)CL/USD
Intervals: , , , , , , , ,
1min5min15min30min1h4h1day1week1monthExample:
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()端点:
认证: 查询参数
适用场景: 股票(AAPL、MSFT)、外汇(EUR/USD)、大宗商品(XAU/USD代表黄金)
https://api.twelvedata.com/time_seriesapikey={TWELVEDATA_API_KEY}常见交易对:
- 股票:,
AAPL,MSFT,GOOGL,TSLASPY - 外汇:,
EUR/USD,GBP/JPYUSD/CHF - 大宗商品:(黄金),
XAU/USD(白银),XAG/USD(原油)CL/USD
时间间隔: , , , , , , , ,
1min5min15min30min1h4h1day1week1month示例:
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 Range | Auto-Selected Interval | Rationale |
|---|---|---|
| ≤31 days | Hourly | High granularity for short-term analysis |
| 32-365 days | Daily | Sufficient detail, lower data volume |
| >365 days | Daily | Daily is optimal for long-term trends |
Override: Set or in the config to override auto-selection.
INTERVAL = "daily"INTERVAL = "hourly"模板现在会自动选择最优时间间隔,在最小化数据量的同时保持可视化质量:
| 时间范围 | 自动选择的时间间隔 | 理由 |
|---|---|---|
| ≤31天 | 小时级 | 高粒度适合短期分析 |
| 32-365天 | 日线级 | 细节足够,数据量更小 |
| >365天 | 日线级 | 日线级最适合长期趋势分析 |
手动覆盖: 在配置中设置或以覆盖自动选择。
INTERVAL = "daily"INTERVAL = "hourly"Key Gotchas
关键注意事项
- facecolor: You MUST set
savefigandfacecolor='#131722'inedgecolor='#131722', or the saved PNG reverts to white background.savefig - Title spacing: Prefix titles with to add spacing from the top edge.
\n - : Use when you need post-plot customization (price formatting, annotations). When using it, call
returnfig=Truemanually — don't passfig.savefig()tosavefig.mpf.plot() - No volume in OHLC: CoinGecko OHLC endpoint returns only. Use
[timestamp_ms, open, high, low, close]or fetch volume separately fromvolume=Falseendpoint.coin_chart - Panel ratios: Set when adding indicator subplots. E.g.,
panel_ratiosfor candles + volume + one indicator,(4, 1, 2)for two indicators.(5, 1, 2, 2) - Figure size: Default . Increase to
(14, 8)or(14, 10)when adding subplots.(14, 12)
- 背景色: 必须在
savefig中设置savefig和facecolor='#131722',否则保存的PNG会恢复为白色背景。edgecolor='#131722' - 标题间距: 在标题前添加以增加与顶部边缘的间距。
\n - : 当需要对绘图进行后期自定义(价格格式化、注释)时使用。使用此参数时,需手动调用
returnfig=True——不要将fig.savefig()传递给savefig。mpf.plot() - OHLC无成交量: CoinGecko的OHLC端点仅返回。使用
[timestamp_ms, open, high, low, close]或从volume=False端点单独获取成交量数据。coin_chart - 面板比例: 添加指标子图时设置。例如,
panel_ratios对应K线 + 成交量 + 一个指标,(4, 1, 2)对应两个指标。(5, 1, 2, 2) - 图表尺寸: 默认。添加子图时可增大到
(14, 8)或(14, 10)。(14, 12)
Rules
规则
- Paths are relative to workspace. Write to , not
scripts/foo.py. The bash CWD is already workspace.workspace/scripts/foo.py - Always save to directory. Use
output/.os.makedirs("output", exist_ok=True) - Always run the script with to verify it works.
bash("python3 scripts/<name>.py") - Always call on the generated PNG, then use markdown image syntax to display it:
read_file - Scripts must be standalone. Use +
requests. No internal imports, no dotenv.os.getenv() - CRITICAL: Do NOT use proxied_get() in chart scripts. Chart scripts are standalone and run in the workspace - they cannot import from . Always use
core.http_clientandrequests.get()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.requests.post() - Env vars are inherited. works directly.
os.getenv("COINGECKO_API_KEY") - 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。bash的当前工作目录已设为工作区。workspace/scripts/foo.py - 始终保存到目录。 使用
output/。os.makedirs("output", exist_ok=True) - 始终使用运行脚本以验证其可正常工作。
bash("python3 scripts/<name>.py") - 始终对生成的PNG调用,然后使用Markdown图片语法展示:
read_file - 脚本必须独立运行。 使用+
requests。不要使用内部导入,不要使用dotenv。os.getenv() - 重要提示:请勿在图表脚本中使用proxied_get()。 图表脚本是独立的,在工作区运行——无法从导入。请始终直接使用
core.http_client和requests.get()。这是对PLATFORM.md代理规则的例外,因为这些脚本在主Star Child进程之外执行。模板展示了正确的实现方式。requests.post() - 环境变量可继承。 可直接使用。
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 / env vars. If 401 errors occur:
PROXY_HOSTPROXY_PORTCheck environment:
bash
bash("env | grep -E 'PROXY|REQUESTS_CA'")Expected vars:
- /
PROXY_HOST- Proxy address (templates use these to set HTTP_PROXY/HTTPS_PROXY)PROXY_PORT - - Proxy CA cert for SSL
REQUESTS_CA_BUNDLE - /
COINGECKO_API_KEY- Can be fake in proxied environmentsTWELVEDATA_API_KEY
If vars are missing, this is an environment configuration issue, not a script issue.
模板会从/环境变量自动配置代理。如果出现401错误:
PROXY_HOSTPROXY_PORT检查环境:
bash
bash("env | grep -E 'PROXY|REQUESTS_CA'")预期环境变量:
- /
PROXY_HOST- 代理地址(模板使用这些变量设置HTTP_PROXY/HTTPS_PROXY)PROXY_PORT - - 用于SSL的代理CA证书
REQUESTS_CA_BUNDLE - /
COINGECKO_API_KEY- 在代理环境中可以是模拟值TWELVEDATA_API_KEY
如果缺少变量,这是环境配置问题,而非脚本问题。