超级版1

This commit is contained in:
tukuaiai 2025-12-13 17:00:54 +08:00
parent 5e6f46c096
commit 53100d627b
108 changed files with 240878 additions and 21 deletions

142
README.md
View File

@ -10,9 +10,9 @@
<div align="center">
# Vibe Coding 终极指南 V1.2
# vibe coding 至尊超级终极无敌指南 V114514
**一个通过与 AI 结对编程,将想法变为现实的终极工作流程。**
**一个通过与 AI 结对编程,将想法变为现实的终极工作**
---
@ -29,11 +29,14 @@
<a href="https://t.me/glue_coding"><img src="https://img.shields.io/badge/chat-telegram-blue?style=for-the-badge&logo=telegram" alt="交流群"></a>
</p>
[📚 相关文档](#-相关文档) •
[🚀 入门指南](#-入门指南) •
[⚙️ 完整设置流程](#-完整设置流程) •
[📚 相关文档](#-相关文档)
[🚀 入门指南](#-入门指南)
[⚙️ 完整设置流程](#-完整设置流程)
[📞 联系方式](#-联系方式)
[✨ 赞助地址](#-赞助地址)
[🤝 参与贡献](#-参与贡献)
</div>
---
@ -44,6 +47,68 @@
> **核心理念**: *规划就是一切。* 谨慎让 AI 自主规划,否则你的代码库会变成一团无法管理的乱麻。
## 🧭 道
* **凡是 ai 能做的,就不要人工做**
* **一切问题问 ai**
* **上下文是 vibe coding 的第一性要素,垃圾进,垃圾出**
* **系统性思考,实体,链接,功能/目的,三个维度**
* **数据与函数即是编程的一切**
* **输入,处理,输出刻画整个过程**
* **多问 ai 是什么?,为什么?,怎么做?**
* **先结构,后代码,一定要规划好框架,不然后面技术债还不完**
* **奥卡姆剃刀定理,如无必要,勿增代码**
* **帕累托法则关注重要的那20%**
* **逆向思考,先明确你的需求,从需求逆向构建代码**
* **重复,多试几次,实在不行重新开个窗口,**
* **专注,极致的专注可以击穿代码,一次只做一件事(神人除外)**
## 🧩 法
* **一句话目标 + 非目标**
* **正交性,功能不要太重复了,(这个分场景)**
* **能抄不写,不重复造轮子,先问 ai 有没有合适的仓库,下载下来改**
* **一定要看官方文档,先把官方文档爬下来喂给 ai**
* **按职责拆模块**
* **接口先行,实现后补**
* **一次只改一个模块**
* **文档即上下文,不是事后补**
## 🛠️ 术
* 明确写清:**能改什么,不能改什么**
* Debug 只给:**预期 vs 实际 + 最小复现**
* 测试可交给 AI**断言人审**
* 代码一多就**切会话**
## 📋 器
- [**Claude Opus 4.5**](https://claude.ai/new),在 Claude Code 中使用 很贵但是尼区ios订阅要便宜几百人民币快+效果好,顶中顶中顶,有 cli 和 ide 插件
- [**gpt-5.1-codex.1-codex (xhigh)**](https://chatgpt.com/codex/),在 Codex CLI 中使用顶中顶除了慢其他没得挑大项目复杂逻辑唯一解买chatgpt会员就能用有 cli 和 ide 插件
- [**Droid**](https://factory.ai/news/terminal-bench),这个里面的 Claude Opus 4.5比 Claude Code 还强,顶,有 cli
- [**Kiro**](https://kiro.dev/),这个里面的 Claude Opus 4.5 现在免费就是cli有点拉看不到正在运行的情况有客户端和 cli
- [**gemini**](https://geminicli.com/),目前免费用,干脏活,用 Claude Code 或者 codex 写好的脚本,拿他来执行可以,整理文档和找思路就它了有客户端和 cli
- [**antigravity**](https://antigravity.google/),谷歌的,可以免费用 Claude Opus 4.5 和 gemini 3.0 pro 大善人
- [**aistudio**](https://aistudio.google.com/prompts/new_chat),谷歌家的,免费用 gemini 3.0 pro 和 Nano Banana
- [**gemini-enterprise**](https://cloud.google.com/gemini-enterprise),谷歌企业版,现在能免费用 Nano Banana pro
- [**augment**](https://app.augmentcode.com/),它的上下文引擎和提示词优化按钮真的神中神中神,小白就用它就行了,点击按钮自动帮你写好提示词,懒人必备
- [**cursor**](https://cursor.com/),已经占领用户心智高地,人尽皆知
- [**Windsurf**](https://windsurf.com/),新用户有免费额度
- [**GitHub Copilot**](https://github.com/features/copilot),没用过
- [**kimik2**](https://www.kimi.com/)国产还行干脏活写简单任务用之前2r一个key一周1024次调用挺爽
- [**GLM**](https://bigmodel.cn/),国产,听说很强,听说和 Claude Sonnet 4 差不多?
- [**Qwen**](https://qwenlm.github.io/qwen-code-docs/zh/cli/)国产阿里的cli有免费额度
- [**提示词库,直接复制粘贴即可使用**](https://docs.google.com/spreadsheets/d/1ngoQOhJqdguwNAilCl1joNwTje7FWWN9WiI2bo5VhpU/edit?gid=2093180351#gid=2093180351&range=A1)
- [**其他编程工具的系统提示词学习库**](https://github.com/x1xhlol/system-prompts-and-models-of-ai-tools)
- [**Skills制作器 ai 你下好之后让 ai 用这个仓库按照你的需求生成 Skills 即可)**](https://github.com/yusufkaraaslan/Skill_Seekers)
- [**元提示词,生成提示词的提示词**](https://docs.google.com/spreadsheets/d/1ngoQOhJqdguwNAilCl1joNwTje7FWWN9WiI2bo5VhpU/edit?gid=1770874220#gid=1770874220)
- [**通用项目架构模板这个就是框架复制给ai一键搭好目录结构**](./documents/通用项目架构模板.md) - 提供了多种项目类型的标准目录结构、核心设计原则、最佳实践建议及技术选型参考。
- [**augment提示词优化器**](https://app.augmentcode.com/),这个提示词优化是真的好用,强烈强烈强烈强烈强烈强烈强烈强烈强烈强烈强烈强烈推荐
- [**思维导图神器让ai生成项目架构的.mmd图复制到这个里面就能可视化查看啦提示词在下面的“系统架构可视化生成Mermaid”里面**](https://www.mermaidchart.com/)
- [**notebooklm资料ai解读和技术文档放这里可以听音频看思维导图和 Nano Banana 生成的图片什么的**](https://notebooklm.google.com/)
- [**zreadai读仓库神器复制github仓库链接进去就能分析减少用轮子的工作量了**](https://zread.ai/)
- [**元技能 Skills 就是生成 Skills 的 Skills**](./skills/claude-skills/SKILL.md)
---
## 📚 相关文档/资源
@ -52,7 +117,10 @@
- [**我的频道**](https://t.me/tradecat_ai_channel)
- [**小登论道:我的学习经验**](./documents/小登论道.md)
- [**编程书籍推荐**](./documents/编程书籍推荐.md)
- [**skill生成器把任何资料转agent的skill技能**](https://github.com/yusufkaraaslan/Skill_Seekers)
- [**元提示词,生成提示词的提示词**](https://docs.google.com/spreadsheets/d/1ngoQOhJqdguwNAilCl1joNwTje7FWWN9WiI2bo5VhpU/edit?gid=1770874220#gid=1770874220)
- [**元技能 Skills 就是生成 Skills 的 Skills**](./skills/claude-skills/SKILL.md)
- [**skills技能仓库复制即用**](./skills)
- [**Skills生成器把任何资料转agent的Skills技能**](https://github.com/yusufkaraaslan/Skill_Seekers)
- [**google表格提示词数据库我系统性收集和制作的几百个适用于各个场景的用户提示词和系统提示词在线表格**](https://docs.google.com/spreadsheets/d/1ngoQOhJqdguwNAilCl1joNwTje7FWWN9WiI2bo5VhpU/edit?gid=2093180351#gid=2093180351&range=A1)
- [**系统提示词收集仓库**](https://github.com/x1xhlol/system-prompts-and-models-of-ai-tools)
- [**prompts-library 提示词库xlsx与md文件夹互转工具与使用说明有几百个适用于各个领域的提示词与元提示词**](./prompts-library/)
@ -66,6 +134,7 @@
- [**CONTRIBUTING.md**](./CONTRIBUTING.md)
- [**CODE_OF_CONDUCT.md**](./CODE_OF_CONDUCT.md)
- [**系统提示词构建原则.md**](./documents/系统提示词构建原则.md) - 深入探讨构建高效、可靠AI系统提示词的核心原则、沟通互动、任务执行、编码规范与安全防护等全方位指南。
- [**系统架构可视化生成Mermaid**](./prompts/coding_prompts/系统架构可视化生成Mermaid.md) - 根据项目直接生成 .mmd 导入思维导图网站直观看架构图,序列图等等
- [**开发经验.md**](./documents/开发经验.md) - 包含变量命名、文件结构、编码规范、系统架构原则、微服务、Redis和消息队列等开发经验与项目规范的详细整理。
- [**vibe-coding-经验收集.md**](./documents/vibe-coding-经验收集.md) - AI开发最佳实践与系统提示词优化技巧的经验收集。
- [**通用项目架构模板.md**](./documents/通用项目架构模板.md) - 提供了多种项目类型的标准目录结构、核心设计原则、最佳实践建议及技术选型参考。
@ -147,6 +216,12 @@
│ ├── 数据管道.md # 数据管道处理提示词。
│ ├── ... (其他用户提示词)
├── skills/ # 集中存放所有类型的 skills 技能。
│ ├── claude-skills # 生成 SKILL 的元 SKILL
│ │ ├── SKILL.md
│ │ ├── ... (其他)
│ ├── ... (其他 skill)
└── backups/ # 项目备份脚本。
├── 一键备份.sh # 一键执行备份的 Shell 脚本。
└── 快速备份.py # 实际执行逻辑的 Python 脚本。
@ -488,11 +563,39 @@ gantt
---
## 🤝 参与贡献
## 📞 联系方式
我们热烈欢迎各种形式的贡献!如果您对本项目有任何想法或建议,请随时开启一个 [Issue](https://github.com/tukuaiai/vibe-coding-cn/issues) 或提交一个 [Pull Request](https://github.com/tukuaiai/vibe-coding-cn/pulls)。
推特https://x.com/123olp
在您开始之前,请花点时间阅读我们的 [**贡献指南 (CONTRIBUTING.md)**](CONTRIBUTING.md) 和 [**行为准则 (CODE_OF_CONDUCT.md)**](CODE_OF_CONDUCT.md)。
telegramhttps://t.me/desci0
telegram交流群https://t.me/glue_coding
telegram频道https://t.me/tradecat_ai_channel
邮箱不一定能及时看到tukuai.ai@gmail.com
---
## ✨ 赞助地址
救救孩子钱包被ai们榨干了求让孩子蹭蹭会员求求求求求求求求求了可以tg或者x联系我🙏🙏🙏
**Tron (TRC20)**: `TQtBXCSTwLFHjBqTS4rNUp7ufiGx51BRey`
**Solana**: `HjYhozVf9AQmfv7yv79xSNs6uaEU5oUk2USasYQfUYau`
**Ethereum (ERC20)**: `0xa396923a71ee7D9480b346a17dDeEb2c0C287BBC`
**BNB Smart Chain (BEP20)**: `0xa396923a71ee7D9480b346a17dDeEb2c0C287BBC`
**Bitcoin**: `bc1plslluj3zq3snpnnczplu7ywf37h89dyudqua04pz4txwh8z5z5vsre7nlm`
**Sui**: `0xb720c98a48c77f2d49d375932b2867e793029e6337f1562522640e4f84203d2e`
**币安uid支付**: `572155580`
---
### ✨ 贡献者们
@ -505,6 +608,14 @@ gantt
---
## 🤝 参与贡献
我们热烈欢迎各种形式的贡献!如果您对本项目有任何想法或建议,请随时开启一个 [Issue](https://github.com/tukuaiai/vibe-coding-cn/issues) 或提交一个 [Pull Request](https://github.com/tukuaiai/vibe-coding-cn/pulls)。
在您开始之前,请花点时间阅读我们的 [**贡献指南 (CONTRIBUTING.md)**](CONTRIBUTING.md) 和 [**行为准则 (CODE_OF_CONDUCT.md)**](CODE_OF_CONDUCT.md)。
---
## 📜 许可证
本项目采用 [MIT](LICENSE) 许可证。
@ -527,17 +638,6 @@ gantt
---
## ✨ 赞助地址
您的支持是我们持续改进项目的动力!
- **Tron (TRC20)**: `TQtBXCSTwLFHjBqTS4rNUp7ufiGx51BRey`
- **Solana**: `HjYhozVf9AQmfv7yv79xSNs6uaEU5oUk2USasYQfUYau`
- **Ethereum (ERC20)**: `0xa396923a71ee7D9480b346a17dDeEb2c0C287BBC`
- **BNB Smart Chain (BEP20)**: `0xa396923a71ee7D9480b346a17dDeEb2c0C287BBC`
- **Bitcoin**: `bc1plslluj3zq3snpnnczplu7ywf37h89dyudqua04pz4txwh8z5z5vsre7nlm`
- **Sui**: `0xb720c98a48c77f2d49d375932b2867e793029e6337f1562522640e4f84203d2e`
**Made with ❤️ and a lot of ☕ by [tukuaiai](https://github.com/tukuaiai),[Nicolas Zullo](https://x.com/NicolasZu)and [123olp](https://x.com/123olp)**
[⬆ 回到顶部](#vibe-coding-终极指南-v12)
[⬆ 回到顶部](#vibe-coding-至尊超级终极无敌指南-V114514)

105
skills/ccxt/SKILL.md Normal file

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,69 @@
# Ccxt - Cli
**Pages:** 1
---
## Search code, repositories, users, issues, pull requests...
**URL:** https://github.com/ccxt/ccxt/wiki/CLI
**Contents:**
- CCXT CLI (Command-Line Interface)
- Install globally
- Install
- Usage
- Inspecting Exchange Properties
- Calling A Unified Method By Name
- Calling An Exchange-Specific Method By Name
- Authentication And Overrides
- Unified API vs Exchange-Specific API
- Run with jq
CCXT includes an example that allows calling all exchange methods and properties from command line. One doesn't even have to be a programmer or write code any user can use it!
The CLI interface is a program in CCXT that takes the exchange name and some params from the command line and executes a corresponding call from CCXT printing the output of the call back to the user. Thus, with CLI you can use CCXT out of the box, not a single line of code needed.
CCXT command line interface is very handy and useful for:
For the CCXT library users we highly recommend to try CLI at least a few times to get a feel of it. For the CCXT library developers CLI is more than just a recommendation, it's a must.
The best way to learn and understand CCXT CLI is by experimentation, trial and error. Warning: CLI executes your command and does not ask for a confirmation after you launch it, so be careful with numbers, confusing amounts with prices can cause a loss of funds.
The same CLI design is implemented in all supported languages, TypeScript, JavaScript, Python and PHP for the purposes of example code for the developers. In other words, the existing CLI contains three implementations that are in many ways identical. The code in those three CLI examples is intended to be "easily understandable".
The source code of the CLI is available here:
Clone the CCXT repository:
Change directory to the cloned repository:
Install the dependencies:
The CLI script requires at least one argument, that is, the exchange id (the list of supported exchanges and their ids). If you don't specify the exchange id, the script will print the list of all exchange ids for reference.
Upon launch, CLI will create and initialize the exchange instance and will also call exchange.loadMarkets() on that exchange. If you don't specify any other command-line arguments to CLI except the exchange id argument, then the CLI script will print out all the contents of the exchange object, including the list of all the methods and properties and all the loaded markets (the output may be extremely long in that case).
Normally, following the exchange id argument one would specify a method name to call with its arguments or an exchange property to inspect on the exchange instance.
If the only parameter you specify to CLI is the exchange id, then it will print out the contents of the exchange instance including all properties, methods, markets, currencies, etc. Warning: exchange contents are HUGE and this will dump A LOT of output to your screen!
You can specify the name of the property of the exchange to narrow the output down to a reasonable size.
You can easily view which methods are supported on the various exchanges:
Calling unified methods is easy:
Exchange specific parameters can be set in the last argument of every unified method:
Here's an example of fetching the order book on okx in sandbox mode using the implicit API and the exchange specific instId and sz parameters:
Public exchange APIs don't require authentication. You can use the CLI to call any method of a public API. The difference between public APIs and private APIs is described in the Manual, here: Public/Private API.
For private API calls, by default the CLI script will look for API keys in the keys.local.json file in the root of the repository cloned to your working directory and will also look up exchange credentials in the environment variables. More details here: Adding Exchange Credentials.
CLI supports all possible methods and properties that exist on the exchange instance.
(If the page is not being rendered for you, you can refer to the mirror at https://docs.ccxt.com/)
---

View File

@ -0,0 +1,29 @@
# Ccxt - Exchanges
**Pages:** 2
---
## Search code, repositories, users, issues, pull requests...
**URL:** https://github.com/ccxt/ccxt/wiki/Exchange-Markets
**Contents:**
- Supported Exchanges
(If the page is not being rendered for you, you can refer to the mirror at https://docs.ccxt.com/)
---
## Search code, repositories, users, issues, pull requests...
**URL:** https://github.com/ccxt/ccxt/wiki/Exchange-Markets-By-Country
**Contents:**
- Exchanges By Country
The ccxt library currently supports the following cryptocurrency exchange markets and trading APIs:
(If the page is not being rendered for you, you can refer to the mirror at https://docs.ccxt.com/)
---

View File

@ -0,0 +1,111 @@
# Ccxt - Faq
**Pages:** 1
---
## Search code, repositories, users, issues, pull requests...
**URL:** https://github.com/ccxt/ccxt/wiki/FAQ
**Contents:**
- Frequently Asked Questions
- I'm trying to run the code, but it's not working, how do I fix it?
- What is required to get help?
- I am calling a method and I get an error, what am I doing wrong?
- I got an incorrect result from a method call, can you help?
- Can you implement feature foo in exchange bar?
- When will you add feature foo for exchange bar ? What's the estimated time? When should we expect this?
- When will you add the support for an exchange requested in the Issues?
- How long should I wait for a feature to be added? I need to decide whether to implement it myself or to wait for the CCXT Dev Team to implement it for me.
- What's your progress on adding the feature foo that was requested earlier? How do you do implementing exchange bar?
If your question is formulated in a short manner like the above, we won't help. We don't teach programming. If you're unable to read and understand the Manual or you can't follow precisely the guides from the CONTRIBUTING doc on how to report an issue, we won't help either. Read the CONTRIBUTING guides on how to report an issue and read the Manual. You should not risk anyone's money and time without reading the entire Manual very carefully. You should not risk anything if you're not used to a lot of reading with tons of details. Also, if you don't have the confidence with the programming language you're using, there are much better places for coding fundamentals and practice. Search for python tutorials, js videos, play with examples, this is how other people climb up the learning curve. No shortcuts, if you want to learn something.
When asking a question:
Use the search button for duplicates first!
Post your request and response in verbose mode! Add exchange.verbose = true right before the line you're having issues with, and copypaste what you see on your screen. It's written and mentioned everywhere, in the Troubleshooting section, in the README and in many answers to similar questions among previous issues and pull requests. No excuses. The verbose output should include both the request and response from the exchange.
Include the full error callstack!
Write your programming language and language version number
Write the CCXT / CCXT Pro library version number
Which method you're trying to call
Post your code to reproduce the problem. Make it a complete short runnable program, don't swallow the lines and make it as compact as you can (5-10 lines of code), including the exchange instantation code. Remove all irrelevant parts from it, leaving just the essence of the code to reproduce the issue.
DO NOT POST YOUR apiKey AND secret! Keep them safe (remove them before posting)!
You're not reporting the issue properly ) Please, help the community to help you ) Read this and follow the steps: https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-submit-an-issue. Once again, your code to reproduce the issue and your verbose request and response ARE REQUIRED. Just the error traceback, or just the response, or just the request, or just the code is not enough!
Basically the same answer as the previous question. Read and follow precisely: https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-submit-an-issue. Once again, your code to reproduce the issue and your verbose request and response ARE REQUIRED. Just the error traceback, or just the response, or just the request, or just the code is not enough!
Yes, we can. And we will, if nobody else does that before us. There's very little point in asking this type of questions, because the answer is always positive. When someone asks if we can do this or that, the question is not about our abilities, it all boils down to time and management needed for implementing all accumulated feature requests.
Moreover, this is an open-source library which is a work in progress. This means, that this project is intended to be developed by the community of users, who are using it. What you're asking is not whether we can or cannot implement it, in fact you're actually telling us to go do that particular task and this is not how we see a voluntary collaboration. Your contributions, PRs and commits are welcome: https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code.
We don't give promises or estimates on the free open-source work. If you wish to speed it up, feel free to reach out to us via info@ccxt.trade.
We don't give promises or estimates on the open-source work. The reasoning behind this is explained in the previous paragraph.
Again, we can't promise on the dates for adding this or that exchange, due to reasons outlined above. The answer will always remain the same: as soon as we can.
Please, go for implemeting it yourself, do not wait for us. We will add it as soon as we can. Also, your contributions are very welcome:
This type of questions is usually a waste of time, because answering it usually requires too much time for context-switching, and it often takes more time to answer this question, than to actually satisfy the request with code for a new feature or a new exchange. The progress of this open-source project is also open, so, whenever you're wondering how it is doing, take a look into commit history.
If it is not merged, it means that the PR contains errors, that should be fixed first. If it could be merged as is we would merge it, and you wouldn't have asked this question in the first place. The most frequent reason for not merging a PR is a violation of any of the CONTRIBUTING guidelines. Those guidelines should be taken literally, cannot skip a single line or word from there if you want your PR to be merged quickly. Code contributions that do not break the guidelines get merged almost immediately (usually, within hours).
Unfortunately, we don't always have the time to quickly list out each and every single error in the code that prevents it from merging. It is often easier and faster to just go and fix the error rather than explain what one should do to fix it. Most of them are already outlined in the CONTRIBUTING guidelines. The main rule of thumb is to follow all guidelines literally.
Our build system generates exchange-specific JavaScript, Python and PHP code for us automatically, so it is transpiled from TypeScript, and there's no need to fix all languages separately one by one.
Thus, if it is fixed in TypeScript, it is fixed in JavaScript NPM, Python pip and PHP Composer as well. The automatic build usually takes 15-20 minutes. Just upgrade your version with npm, pip or composer after the new version arrives and you'll be fine.
Some exchanges support createOrder with the additional "attached" stopLoss & takeProfit sub-orders - view StopLoss And TakeProfit Orders Attached To A Position. However, some exchanges might not support that feature and you will need to run separate createOrder methods to add conditional order (e.g. *trigger order | stoploss order | takeprofit order) to the already open position - view [Conditional orders](Manual.md#Conditional Orders). You can also check them by looking at exchange.has['createOrderWithTakeProfitAndStopLoss'], exchange.has['createStopLossOrder'] and exchange.has['createTakeProfitOrder'], however they are not as precise as .features property.
To create a market-buy order with cost, first, you need to check if the exchange supports that feature (exchange.has['createMarketBuyOrderWithCost']). If it does, then you can use the createMarketBuyOrderWithCost` method. Example:
Many exchanges require the amount to be in the quote currency (they don't accept the base amount) when placing spot-market buy orders. In those cases, the exchange will have the option createMarketBuyRequiresPrice set to true.
Example: If you wanted to buy BTC/USDT with a market buy-order, you would need to provide an amount = 5 USDT instead of 0.000X. We have a check to prevent errors that explicitly require the price because users will usually provide the amount in the base currency.
So by default, if you do, create_order(symbol, 'market,' 'buy,' 10) will throw an error if the exchange has that option (createOrder() requires the price argument for market buy orders to calculate the total cost to spend (amount * price), alternatively set the createMarketBuyOrderRequiresPrice option or param to false...).
If the exchange requires the cost and the user provided the base amount, we need to request an extra parameter price and multiply them to get the cost. If you're aware of this behavior, you can simply disable createMarketBuyOrderRequiresPrice and pass the cost in the amount parameter, but disabling it does not mean you can place the order using the base amount instead of the quote.
If you do create_order(symbol, 'market', 'buy', 0.001, 20000) ccxt will use the required price to calculate the cost by doing 0.01*20000 and send that value to the exchange.
If you want to provide the cost directly in the amount argument, you can do exchange.options['createMarketBuyOrderRequiresPrice'] = False (you acknowledge that the amount will be the cost for market-buy) and then you can do create_order(symbol, 'market', 'buy', 10)
This is basically to avoid a user doing this: create_order('SHIB/USDT', market, buy, 1000000) and thinking he's trying to buy 1kk of shib but in reality he's buying 1kk USDT worth of SHIB. For that reason, by default ccxt always accepts the base currency in the amount parameter.
Alternatively, you can use the functions createMarketBuyOrderWithCost/ createMarketSellOrderWithCost if they are available.
See more: Market Buys
Spot trading involves buying or selling a financial instrument (like a cryptocurrency) for immediate delivery. It's straightforward, involving the direct exchange of assets.
Swap trading, on the other hand, involves derivative contracts where two parties exchange financial instruments or cash flows at a set date in the future, based on the underlying asset. Swaps are often used for leverage, speculation, or hedging and do not necessarily involve the exchange of the underlying asset until the contract expires.
Besides that, you will be handling contracts if you're trading swaps and not the base currency (e.g., BTC) directly, so if you create an order with amount = 1, the amount in BTC will vary depending on the contractSize. You can check the contract size by doing:
A reduceOnly order is a type of order that can only reduce a position, not increase it. To place a reduceOnly order, you typically use the createOrder method with a reduceOnly parameter set to true. This ensures that the order will only execute if it decreases the size of an open position, and it will either partially fill or not fill at all if executing it would increase the position size.
See more: Trailing Orders
To check the endpoint used by a unified method in the CCXT library, you would typically need to refer to the source code of the library for the specific exchange implementation you're interested in. The unified methods in CCXT abstract away the details of the specific endpoints they interact with, so this information is not directly exposed via the library's API. For detailed inspection, you can look at the implementation of the method for the particular exchange in the CCXT library's source code on GitHub.
See more: Unified API
The funding rate structure has three different funding rate values that can be returned:
As an example, say it is 12:30. The previousFundingRate happened at 12:00 and we're looking to see what the upcoming funding rate will be by checking the fundingRate value. In this example, given 4-hour intervals, the fundingRate will happen in the future at 4:00 and the nextFundingRate is the predicted rate that will happen at 8:00.
(If the page is not being rendered for you, you can refer to the mirror at https://docs.ccxt.com/)
---

View File

@ -0,0 +1,72 @@
# Ccxt - Getting Started
**Pages:** 1
---
## Search code, repositories, users, issues, pull requests...
**URL:** https://github.com/ccxt/ccxt/wiki/Install
**Contents:**
- Install
- JavaScript (NPM)
- JavaScript (for use with the <script> tag):
- Custom JavaScript Builds
- Python
- PHP
- .net/C#
- Docker
- Proxy
The easiest way to install the ccxt library is to use builtin package managers:
This library is shipped as an all-in-one module implementation with minimalistic dependencies and requirements:
You can also clone it into your project directory from ccxt GitHub repository and copy files manually into your working directory with language extension appropriate for your environment.
An alternative way of installing this library is to build a custom bundle from source. Choose exchanges you need in exchanges.cfg.
JavaScript version of ccxt works both in Node and web browsers. Requires ES6 and async/await syntax support (Node 15+). When compiling with Webpack and Babel, make sure it is not excluded in your babel-loader config.
ccxt crypto trading library in npm
All-in-one browser bundle (dependencies included), served from a CDN of your choice:
You can obtain a live-updated version of the bundle by removing the version number from the URL (the @a.b.c thing) or the /latest/ on our cdn — however, we do not recommend to do that, as it may break your app eventually. Also, please keep in mind that we are not responsible for the correct operation of those CDN servers.
We also provide webpack minified and tree-shaken versions of the library starting from version 3.0.35 - Visit https://cdn.ccxt.com to browse the prebundled versions we distribute.
Note: the file sizes are subject to change.
Here is an example using a custom bybit bundle from our cdn in the browser
The default entry point for the browser is window.ccxt and it creates a global ccxt object:
It takes time to load all scripts and resources. The problem with in-browser usage is that the entire CCXT library weighs a few megabytes which is a lot for a web application. Sometimes it is also critical for a Node app. Therefore to lower the loading time you might want to make your own custom build of CCXT for your app with just the exchanges you need. CCXT uses webpack to remove dead code paths to make the package smaller.
ccxt algotrading library in PyPI
The library supports concurrent asynchronous mode with asyncio and async/await in Python 3.5.3+
The autoloadable version of ccxt can be installed with Packagist/Composer (PHP 8.1+).
It can also be installed from the source code: ccxt.php
It requires common PHP modules:
The library supports concurrent asynchronous mode using tools from ReactPHP in PHP 8.1+. Read the Manual for more details.
ccxt in C# with Nugget (netstandard 2.0 and netstandard 2.1)
You can get CCXT installed in a container along with all the supported languages and dependencies. This may be useful if you want to contribute to CCXT (e.g. run the build scripts and tests — please see the Contributing document for the details on that).
You don't need the Docker image if you're not going to develop CCXT. If you just want to use CCXT just install it as a regular package into your project.
Using docker-compose (in the cloned CCXT repository):
If you are unable to obtain data from exchanges due to location restrictions read the proxy section.
(If the page is not being rendered for you, you can refer to the mirror at https://docs.ccxt.com/)
---

View File

@ -0,0 +1,35 @@
# Ccxt Documentation Index
## Categories
### Cli
**File:** `cli.md`
**Pages:** 1
### Exchanges
**File:** `exchanges.md`
**Pages:** 2
### Faq
**File:** `faq.md`
**Pages:** 1
### Getting Started
**File:** `getting_started.md`
**Pages:** 1
### Manual
**File:** `manual.md`
**Pages:** 2
### Other
**File:** `other.md`
**Pages:** 1
### Pro
**File:** `pro.md`
**Pages:** 1
### Specification
**File:** `specification.md`
**Pages:** 2

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,27 @@
# Ccxt - Other
**Pages:** 1
---
## Search code, repositories, users, issues, pull requests...
**URL:** https://github.com/ccxt/ccxt/wiki
**Contents:**
- General Information
- How To Install
- How To Use
- WebSocket Support
- Troubleshooting
- Examples
- New Exchanges
- API Reference
Welcome to the ccxt wiki!
We recommend to visit our full documentation at https://docs.ccxt.com
(If the page is not being rendered for you, you can refer to the mirror at https://docs.ccxt.com/)
---

View File

@ -0,0 +1,18 @@
# Ccxt - Pro
**Pages:** 1
---
## Search code, repositories, users, issues, pull requests...
**URL:** https://github.com/ccxt/ccxt/wiki/ccxt.pro
**Contents:**
- CCXT Pro
CCXT supports WebSockets (Pro part) for many exchanges.
(If the page is not being rendered for you, you can refer to the mirror at https://docs.ccxt.com/)
---

View File

@ -0,0 +1,44 @@
# Ccxt - Specification
**Pages:** 2
---
## Search code, repositories, users, issues, pull requests...
**URL:** https://github.com/ccxt/ccxt/wiki/Requirements
**Contents:**
- CCXT Integration Requirements
- Public API
- Exchange Information, Fee Schedule and Trading Rules
- Market Data
- Private API
- Trading
- Trading History
- Funding
The exchange is required to implement the following list of methods and structures in order to get integrated with CCXT.
(If the page is not being rendered for you, you can refer to the mirror at https://docs.ccxt.com/)
---
## Search code, repositories, users, issues, pull requests...
**URL:** https://github.com/ccxt/ccxt/wiki/Certification
**Contents:**
- CCXT Certification Program ·
- Requirements
- Contact Us
The structure of CCXT defines a good, portable and cross-compatible standard for exchanges' API interfaces, that is implemented in the CCXT Unified API. Exchanges are welcome to apply for our certification program. Certification is technically supervised and quality-assured by members of the CCXT Dev Team. That implies that an exchange having a "certified" badge is properly implemented and tested by the authors of CCXT. Certification means less bugs, more functionality, priority support and a much more stable and efficient implementation in general.
Getting integrated and certified requires the exchange to implement a quality API. Please, see the full list of technical requirements here: https://github.com/ccxt/ccxt/wiki/Requirements
For inquiries on getting your exchange integrated, listed and certified: info@ccxt.trade
(If the page is not being rendered for you, you can refer to the mirror at https://docs.ccxt.com/)
---

View File

@ -0,0 +1,470 @@
---
name: claude-code-guide
description: Claude Code 高级开发指南 - 全面的中文教程涵盖工具使用、REPL 环境、开发工作流、MCP 集成、高级模式和最佳实践。适合学习 Claude Code 的高级功能和开发技巧。
---
# Claude Code 高级开发指南
全面的 Claude Code 中文学习指南,涵盖从基础到高级的所有核心概念、工具使用、开发工作流和最佳实践。
## 何时使用此技能
当需要以下帮助时使用此技能:
- 学习 Claude Code 的核心功能和工具
- 掌握 REPL 环境的高级用法
- 理解开发工作流和任务管理
- 使用 MCP 集成外部系统
- 实现高级开发模式
- 应用 Claude Code 最佳实践
- 解决常见问题和错误
- 进行大文件分析和处理
## 快速参考
### Claude Code 核心工具7个
1. **REPL** - JavaScript 运行时环境
- 完整的 ES6+ 支持
- 预加载库D3.js, MathJS, Lodash, Papaparse, SheetJS
- 支持 async/await, BigInt, WebAssembly
- 文件读取:`window.fs.readFile()`
2. **Artifacts** - 可视化输出
- React, Three.js, 图表库
- HTML/SVG 渲染
- 交互式组件
3. **Web Search** - 网络搜索
- 仅美国可用
- 域名过滤支持
4. **Web Fetch** - 获取网页内容
- HTML 转 Markdown
- 内容提取和分析
5. **Conversation Search** - 对话搜索
- 搜索历史对话
- 上下文检索
6. **Recent Chats** - 最近对话
- 访问最近会话
- 对话历史
7. **End Conversation** - 结束对话
- 清理和总结
- 会话管理
### 大文件分析工作流
```bash
# 阶段 1定量评估
wc -l filename.md # 行数统计
wc -w filename.md # 词数统计
wc -c filename.md # 字符数统计
# 阶段 2结构分析
grep "^#{1,6} " filename.md # 提取标题层次
grep "```" filename.md # 识别代码块
grep -c "keyword" filename.md # 关键词频率
# 阶段 3内容提取
Read filename.md offset=0 limit=50 # 文件开头
Read filename.md offset=N limit=100 # 目标部分
Read filename.md offset=-50 limit=50 # 文件结尾
```
### REPL 高级用法
```javascript
// 数据处理
const data = [1, 2, 3, 4, 5];
const sum = data.reduce((a, b) => a + b, 0);
// 使用预加载库
// Lodash
_.chunk([1, 2, 3, 4], 2); // [[1,2], [3,4]]
// MathJS
math.sqrt(16); // 4
// D3.js
d3.range(10); // [0,1,2,3,4,5,6,7,8,9]
// 读取文件
const content = await window.fs.readFile('path/to/file');
// 异步操作
const result = await fetch('https://api.example.com/data');
const json = await result.json();
```
### 斜杠命令系统
**内置命令:**
- `/help` - 显示帮助
- `/clear` - 清除对话
- `/plugin` - 管理插件
- `/settings` - 配置设置
**自定义命令:**
创建 `.claude/commands/mycommand.md`
```markdown
根据需求执行特定任务的指令
```
使用:`/mycommand`
### 开发工作流模式
#### 1. 文件分析工作流
```bash
# 探索 → 理解 → 实现
ls -la # 列出文件
Read file.py # 读取内容
grep "function" file.py # 搜索模式
# 然后实现修改
```
#### 2. 算法验证工作流
```bash
# 设计 → 验证 → 实现
# 1. 在 REPL 中测试逻辑
# 2. 验证边界情况
# 3. 实现到代码
```
#### 3. 数据探索工作流
```bash
# 检查 → 分析 → 可视化
# 1. 读取数据文件
# 2. REPL 中分析
# 3. Artifacts 可视化
```
## 核心概念
### 工具权限系统
**自动授予权限的工具:**
- REPL
- Artifacts
- Web Search/Fetch
- Conversation Search
**需要授权的工具:**
- Bash (读/写文件系统)
- Edit (修改文件)
- Write (创建文件)
### 项目上下文
Claude 自动识别:
- Git 仓库状态
- 编程语言(从文件扩展名)
- 项目结构
- 依赖配置
### 内存系统
**对话内存:**
- 存储在当前会话
- 200K token 窗口
- 自动上下文管理
**持久内存(实验性):**
- 跨会话保存
- 用户偏好记忆
- 项目上下文保留
## MCP 集成
### 什么是 MCP
Model Context Protocol - 连接 Claude 到外部系统的协议。
### MCP 服务器配置
配置文件:`~/.config/claude/mcp_config.json`
```json
{
"mcpServers": {
"my-server": {
"command": "node",
"args": ["path/to/server.js"],
"env": {
"API_KEY": "your-key"
}
}
}
}
```
### 使用 MCP 工具
Claude 会自动发现 MCP 工具并在对话中使用:
```
"使用 my-server 工具获取数据"
```
## 钩子系统
### 钩子类型
`.claude/settings.json` 配置:
```json
{
"hooks": {
"tool-pre-use": "echo 'About to use tool'",
"tool-post-use": "echo 'Tool used'",
"user-prompt-submit": "echo 'Processing prompt'"
}
}
```
### 常见钩子用途
- 自动格式化代码
- 运行测试
- Git 提交检查
- 日志记录
- 通知发送
## 高级模式
### 多代理协作
使用 Task 工具启动子代理:
```
"启动一个专门的代理来优化这个算法"
```
子代理特点:
- 独立上下文
- 专注单一任务
- 返回结果到主代理
### 智能任务管理
使用 TodoWrite 工具:
```
"创建任务列表来跟踪这个项目"
```
任务状态:
- `pending` - 待处理
- `in_progress` - 进行中
- `completed` - 已完成
### 代码生成模式
**渐进式开发:**
1. 生成基础结构
2. 添加核心功能
3. 实现细节
4. 测试和优化
**验证驱动:**
1. 写测试用例
2. 实现功能
3. 运行测试
4. 修复问题
## 质量保证
### 自动化测试
```bash
# 运行测试
npm test
pytest
# 类型检查
mypy script.py
tsc --noEmit
# 代码检查
eslint src/
flake8 .
```
### 代码审查模式
使用子代理进行审查:
```
"启动代码审查代理检查这个文件"
```
审查重点:
- 代码质量
- 安全问题
- 性能优化
- 最佳实践
## 错误恢复
### 常见错误模式
1. **工具使用错误**
- 检查权限
- 验证语法
- 确认路径
2. **文件操作错误**
- 确认文件存在
- 检查读写权限
- 验证路径正确
3. **API 调用错误**
- 检查网络连接
- 验证 API 密钥
- 确认请求格式
### 渐进式修复策略
1. 隔离问题
2. 最小化复现
3. 逐步修复
4. 验证解决方案
## 最佳实践
### 开发原则
1. **清晰优先** - 明确需求和目标
2. **渐进实现** - 分步骤开发
3. **持续验证** - 频繁测试
4. **适当抽象** - 合理模块化
### 工具使用原则
1. **正确的工具** - 选择合适的工具
2. **工具组合** - 多工具协同
3. **权限最小化** - 只请求必要权限
4. **错误处理** - 优雅处理失败
### 性能优化
1. **批量操作** - 合并多个操作
2. **增量处理** - 处理大文件
3. **缓存结果** - 避免重复计算
4. **异步优先** - 使用 async/await
## 安全考虑
### 沙箱模型
每个工具在隔离环境中运行:
- REPL无文件系统访问
- Bash需要明确授权
- Web仅特定域名
### 最佳安全实践
1. **最小权限** - 仅授予必要权限
2. **代码审查** - 检查生成的代码
3. **敏感数据** - 不要共享密钥
4. **定期审计** - 检查钩子和配置
## 故障排除
### 工具无法使用
**症状:** 工具调用失败
**解决方案:**
- 检查权限设置
- 验证语法正确
- 确认文件路径
- 查看错误消息
### REPL 性能问题
**症状:** REPL 执行缓慢
**解决方案:**
- 减少数据量
- 使用流式处理
- 优化算法
- 分批处理
### MCP 连接失败
**症状:** MCP 服务器无响应
**解决方案:**
- 检查配置文件
- 验证服务器运行
- 确认环境变量
- 查看服务器日志
## 实用示例
### 示例 1数据分析
```javascript
// 在 REPL 中
const data = await window.fs.readFile('data.csv');
const parsed = Papa.parse(data, { header: true });
const values = parsed.data.map(row => parseFloat(row.value));
const avg = _.mean(values);
const std = math.std(values);
console.log(`平均值: ${avg}, 标准差: ${std}`);
```
### 示例 2文件搜索
```bash
# 在 Bash 中
grep -r "TODO" src/
find . -name "*.py" -type f
```
### 示例 3网络数据获取
```
"使用 web_fetch 获取 https://api.example.com/data 的内容,
然后在 REPL 中分析 JSON 数据"
```
## 参考文件
此技能包含详细文档:
- **README.md** (9,594 行) - 完整的 Claude Code 高级指南
包含以下主题:
- 核心工具深度解析
- REPL 高级协同模式
- 开发工作流详解
- MCP 集成完整指南
- 钩子系统配置
- 高级模式和最佳实践
- 故障排除和安全考虑
使用 `view` 命令查看参考文件获取详细信息。
## 资源
- **GitHub 仓库**: https://github.com/karminski/claude-code-guide-study
- **原始版本**: https://github.com/Cranot/claude-code-guide
- **Anthropic 官方文档**: https://docs.claude.com
## 注意事项
本指南结合了:
- 官方功能和公告
- 实际使用观察到的模式
- 概念性方法和最佳实践
- 第三方工具集成
请在使用时参考最新的官方文档。
---
**使用这个技能深入掌握 Claude Code 的强大功能!**

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,328 @@
# Claude Code 高级开发指南文档索引
## 文档概览
### README.md
**文件:** `README.md`
**行数:** 9,594 行
**语言:** 中文
这是一份极其详细和全面的 Claude Code 学习指南,涵盖从基础到高级的所有内容。
## 主要章节
### 1. 快速导航与参考
- 即时命令参考
- 功能快速参考
- 高级用户快捷方式
- 任务状态参考
- 常见工作流卡片
### 2. 核心智能系统
- Claude 工具的关键发现
- 高级 REPL 协同模式
- 专用内核架构集成
- 元待办事项系统
- 高级协同实现
### 3. 核心概念
- 7 个核心工具详解
- 权限系统
- 项目上下文
- 内存管理
- 文件操作
### 4. 斜杠命令系统
- 系统命令
- 自定义命令
- 命令模板
- 命令组织
### 5. 钩子系统
- 钩子类型
- 事件触发
- 安全模式
- 自动化工作流
### 6. MCP 集成
- MCP 服务器配置
- OAuth 认证
- 外部系统集成
- 子代理使用
### 7. 开发工作流
- 文件分析工作流
- 算法验证工作流
- 数据探索工作流
- 任务管理模式
### 8. 质量保证
- 自动化测试
- 代码审查
- 多代理协作
- 验证策略
### 9. 错误恢复
- 常见错误模式
- 渐进式修复
- 调试技巧
- 问题诊断
### 10. 实用示例
- 数据分析
- 文件处理
- API 集成
- 可视化创建
- 测试自动化
### 11. 高级模式
- 研究系统
- Smart Flows
- 认知方法
- 多代理编排
### 12. 最佳实践
- 开发原则
- 工具使用
- 性能优化
- 代码质量
### 13. 故障排除
- 常见问题
- 解决方案
- 诊断步骤
- 工具调试
### 14. 安全考虑
- 沙箱模型
- 权限管理
- 安全审计
- 最佳安全实践
### 15. 工具协同掌握
- 工具组合模式
- 高级集成
- 性能优化
- 实战案例
## 核心工具详解
### 1. REPL (JavaScript 运行时)
- 完整 ES6+ 支持
- 预加载 5 个库:
- D3.js (数据可视化)
- MathJS (数学计算)
- Lodash (实用工具)
- Papaparse (CSV 解析)
- SheetJS (Excel 处理)
- 异步支持 (async/await)
- BigInt 支持
- WebAssembly 支持
- 文件读取能力
### 2. Artifacts (可视化输出)
- React 组件
- Three.js 3D 渲染
- HTML/SVG 生成
- 图表和可视化
- 交互式界面
### 3. Web Search (网络搜索)
- 搜索网络内容
- 域名过滤
- 仅美国可用
### 4. Web Fetch (内容获取)
- 获取网页内容
- HTML 转 Markdown
- 内容提取
### 5. Conversation Search (对话搜索)
- 搜索历史对话
- 上下文检索
### 6. Recent Chats (最近对话)
- 访问最近会话
- 对话历史管理
### 7. End Conversation (结束对话)
- 会话清理
- 对话总结
## 大文件分析方法论
指南提供系统化的大文件处理方法:
### 第一阶段:定量评估
使用 `wc` 命令确定文件规模
### 第二阶段:结构分析
使用 `grep` 提取结构信息
### 第三阶段:内容提取
使用 `Read` 工具战略性采样
## REPL 高级用法
### 数据科学能力
- 处理 100,000+ 元素数组
- 统计分析
- 数据转换
- 可视化准备
### 预加载库示例
```javascript
// Lodash
_.chunk([1,2,3,4], 2)
// MathJS
math.sqrt(16)
// D3.js
d3.range(10)
// Papaparse
Papa.parse(csvData)
// SheetJS
XLSX.read(data)
```
## 工作流模式
### 文件分析工作流
探索 → 理解 → 实现
### 算法验证工作流
设计 → 验证 → 实现
### 数据探索工作流
检查 → 分析 → 可视化
### 质量保证工作流
测试 → 审查 → 优化
## MCP 集成详解
### 配置文件位置
`~/.config/claude/mcp_config.json`
### MCP 服务器类型
- API 集成服务器
- 数据库连接服务器
- 文件系统服务器
- 自定义工具服务器
### 认证方式
- API 密钥
- OAuth 2.0
- 环境变量
- 配置文件
## 钩子系统
### 钩子触发时机
- 工具使用前/后
- 用户提示提交
- 文件修改
- 命令执行
### 钩子用途
- 代码格式化
- 自动测试
- Git 操作
- 日志记录
- 通知发送
## 高级模式
### 多代理协作
- 主代理编排
- 子代理专门化
- 结果聚合
- 任务分解
### 智能任务管理
- 任务创建
- 状态追踪
- 进度报告
- 优先级管理
### 认知增强
- 记忆利用
- 上下文管理
- 知识整合
- 推理优化
## 最佳实践总结
### 开发原则
1. 清晰优先
2. 渐进实现
3. 持续验证
4. 适当抽象
### 工具使用原则
1. 选择正确工具
2. 组合工具能力
3. 最小化权限
4. 处理错误
### 性能优化原则
1. 批量操作
2. 增量处理
3. 缓存结果
4. 异步优先
## 安全注意事项
### 沙箱隔离
每个工具在独立沙箱中运行
### 权限管理
- 自动授予权限的工具
- 需要授权的工具
- 权限最小化原则
### 敏感数据处理
- 不要共享 API 密钥
- 不要提交密码
- 使用环境变量
- 定期审计配置
## 快速链接
- **GitHub**: https://github.com/karminski/claude-code-guide-study
- **原始版本**: https://github.com/Cranot/claude-code-guide
- **Star 数**: 444+
- **Fork 数**: 174+
## 使用建议
这份指南内容极其丰富9,594 行),建议:
1. **初学者**: 从核心概念开始
2. **中级用户**: 关注开发工作流
3. **高级用户**: 深入高级模式
4. **问题解决**: 查看故障排除章节
## 特色内容
### 系统化大文件分析
详细的三阶段方法论
### REPL 深度解析
超越基础的高级用法
### MCP 完整指南
从配置到实战
### 多代理编排
高级协作模式
### 认知增强策略
提升 Claude 能力的方法
---
**这是目前最全面的 Claude Code 中文学习资源!**

View File

@ -0,0 +1,313 @@
---
name: claude-cookbooks
description: Claude AI cookbooks - code examples, tutorials, and best practices for using Claude API. Use when learning Claude API integration, building Claude-powered applications, or exploring Claude capabilities.
---
# Claude Cookbooks Skill
Comprehensive code examples and guides for building with Claude AI, sourced from the official Anthropic cookbooks repository.
## When to Use This Skill
This skill should be triggered when:
- Learning how to use Claude API
- Implementing Claude integrations
- Building applications with Claude
- Working with tool use and function calling
- Implementing multimodal features (vision, image analysis)
- Setting up RAG (Retrieval Augmented Generation)
- Integrating Claude with third-party services
- Building AI agents with Claude
- Optimizing prompts for Claude
- Implementing advanced patterns (caching, sub-agents, etc.)
## Quick Reference
### Basic API Usage
```python
import anthropic
client = anthropic.Anthropic(api_key="your-api-key")
# Simple message
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[{
"role": "user",
"content": "Hello, Claude!"
}]
)
```
### Tool Use (Function Calling)
```python
# Define a tool
tools = [{
"name": "get_weather",
"description": "Get current weather for a location",
"input_schema": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name"}
},
"required": ["location"]
}
}]
# Use the tool
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
tools=tools,
messages=[{"role": "user", "content": "What's the weather in San Francisco?"}]
)
```
### Vision (Image Analysis)
```python
# Analyze an image
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/jpeg",
"data": base64_image
}
},
{"type": "text", "text": "Describe this image"}
]
}]
)
```
### Prompt Caching
```python
# Use prompt caching for efficiency
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
system=[{
"type": "text",
"text": "Large system prompt here...",
"cache_control": {"type": "ephemeral"}
}],
messages=[{"role": "user", "content": "Your question"}]
)
```
## Key Capabilities Covered
### 1. Classification
- Text classification techniques
- Sentiment analysis
- Content categorization
- Multi-label classification
### 2. Retrieval Augmented Generation (RAG)
- Vector database integration
- Semantic search
- Context retrieval
- Knowledge base queries
### 3. Summarization
- Document summarization
- Meeting notes
- Article condensing
- Multi-document synthesis
### 4. Text-to-SQL
- Natural language to SQL queries
- Database schema understanding
- Query optimization
- Result interpretation
### 5. Tool Use & Function Calling
- Tool definition and schema
- Parameter validation
- Multi-tool workflows
- Error handling
### 6. Multimodal
- Image analysis and OCR
- Chart/graph interpretation
- Visual question answering
- Image generation integration
### 7. Advanced Patterns
- Agent architectures
- Sub-agent delegation
- Prompt optimization
- Cost optimization with caching
## Repository Structure
The cookbooks are organized into these main categories:
- **capabilities/** - Core AI capabilities (classification, RAG, summarization, text-to-SQL)
- **tool_use/** - Function calling and tool integration examples
- **multimodal/** - Vision and image-related examples
- **patterns/** - Advanced patterns like agents and workflows
- **third_party/** - Integrations with external services (Pinecone, LlamaIndex, etc.)
- **claude_agent_sdk/** - Agent SDK examples and templates
- **misc/** - Additional utilities (PDF upload, JSON mode, evaluations, etc.)
## Reference Files
This skill includes comprehensive documentation in `references/`:
- **main_readme.md** - Main repository overview
- **capabilities.md** - Core capabilities documentation
- **tool_use.md** - Tool use and function calling guides
- **multimodal.md** - Vision and multimodal capabilities
- **third_party.md** - Third-party integrations
- **patterns.md** - Advanced patterns and agents
- **index.md** - Complete reference index
## Common Use Cases
### Building a Customer Service Agent
1. Define tools for CRM access, ticket creation, knowledge base search
2. Use tool use API to handle function calls
3. Implement conversation memory
4. Add fallback mechanisms
See: `references/tool_use.md#customer-service`
### Implementing RAG
1. Create embeddings of your documents
2. Store in vector database (Pinecone, etc.)
3. Retrieve relevant context on query
4. Augment Claude's response with context
See: `references/capabilities.md#rag`
### Processing Documents with Vision
1. Convert document to images or PDF
2. Use vision API to extract content
3. Structure the extracted data
4. Validate and post-process
See: `references/multimodal.md#vision`
### Building Multi-Agent Systems
1. Define specialized agents for different tasks
2. Implement routing logic
3. Use sub-agents for delegation
4. Aggregate results
See: `references/patterns.md#agents`
## Best Practices
### API Usage
- Use appropriate model for task (Sonnet for balance, Haiku for speed, Opus for complex tasks)
- Implement retry logic with exponential backoff
- Handle rate limits gracefully
- Monitor token usage for cost optimization
### Prompt Engineering
- Be specific and clear in instructions
- Provide examples when needed
- Use system prompts for consistent behavior
- Structure outputs with JSON mode when needed
### Tool Use
- Define clear, specific tool schemas
- Validate inputs and outputs
- Handle errors gracefully
- Keep tool descriptions concise but informative
### Multimodal
- Use high-quality images (higher resolution = better results)
- Be specific about what to extract/analyze
- Respect size limits (5MB per image)
- Use appropriate image formats (JPEG, PNG, GIF, WebP)
## Performance Optimization
### Prompt Caching
- Cache large system prompts
- Cache frequently used context
- Monitor cache hit rates
- Balance caching vs. fresh content
### Cost Optimization
- Use Haiku for simple tasks
- Implement prompt caching for repeated context
- Set appropriate max_tokens
- Batch similar requests
### Latency Optimization
- Use streaming for long responses
- Minimize message history
- Optimize image sizes
- Use appropriate timeout values
## Resources
### Official Documentation
- [Anthropic Developer Docs](https://docs.claude.com)
- [API Reference](https://docs.claude.com/claude/reference)
- [Anthropic Support](https://support.anthropic.com)
### Community
- [Anthropic Discord](https://www.anthropic.com/discord)
- [GitHub Cookbooks Repo](https://github.com/anthropics/claude-cookbooks)
### Learning Resources
- [Claude API Fundamentals Course](https://github.com/anthropics/courses/tree/master/anthropic_api_fundamentals)
- [Prompt Engineering Guide](https://docs.claude.com/claude/docs/guide-to-anthropics-prompt-engineering-resources)
## Working with This Skill
### For Beginners
Start with `references/main_readme.md` and explore basic examples in `references/capabilities.md`
### For Specific Features
- Tool use → `references/tool_use.md`
- Vision → `references/multimodal.md`
- RAG → `references/capabilities.md#rag`
- Agents → `references/patterns.md#agents`
### For Code Examples
Each reference file contains practical, copy-pasteable code examples
## Examples Available
The cookbook includes 50+ practical examples including:
- Customer service chatbot with tool use
- RAG with Pinecone vector database
- Document summarization
- Image analysis and OCR
- Chart/graph interpretation
- Natural language to SQL
- Content moderation filter
- Automated evaluations
- Multi-agent systems
- Prompt caching optimization
## Notes
- All examples use official Anthropic Python SDK
- Code is production-ready with error handling
- Examples follow current API best practices
- Regular updates from Anthropic team
- Community contributions welcome
## Skill Source
This skill was created from the official Anthropic Claude Cookbooks repository:
https://github.com/anthropics/claude-cookbooks
Repository cloned and processed on: 2025-10-29

View File

@ -0,0 +1,225 @@
# Contributing to Claude Cookbooks
Thank you for your interest in contributing to the Claude Cookbooks! This guide will help you get started with development and ensure your contributions meet our quality standards.
## Development Setup
### Prerequisites
- Python 3.11 or higher
- [uv](https://docs.astral.sh/uv/) package manager (recommended) or pip
### Quick Start
1. **Install uv** (recommended package manager):
```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
```
Or with Homebrew:
```bash
brew install uv
```
2. **Clone the repository**:
```bash
git clone https://github.com/anthropics/anthropic-cookbook.git
cd anthropic-cookbook
```
3. **Set up the development environment**:
```bash
# Create virtual environment and install dependencies
uv sync --all-extras
# Or with pip:
pip install -e ".[dev]"
```
4. **Install pre-commit hooks**:
```bash
uv run pre-commit install
# Or: pre-commit install
```
5. **Set up your API key**:
```bash
cp .env.example .env
# Edit .env and add your Claude API key
```
## Quality Standards
This repository uses automated tools to maintain code quality:
### The Notebook Validation Stack
- **[nbconvert](https://nbconvert.readthedocs.io/)**: Notebook execution for testing
- **[ruff](https://docs.astral.sh/ruff/)**: Fast Python linter and formatter with native Jupyter support
- **Claude AI Review**: Intelligent code review using Claude
**Note**: Notebook outputs are intentionally kept in this repository as they demonstrate expected results for users.
### Claude Code Slash Commands
This repository includes slash commands that work in both Claude Code (for local development) and GitHub Actions CI. These commands are automatically available when you work in this repository with Claude Code.
**Available Commands**:
- `/link-review` - Validate links in markdown and notebooks
- `/model-check` - Verify Claude model usage is current
- `/notebook-review` - Comprehensive notebook quality check
**Usage in Claude Code**:
```bash
# Run the same validations that CI will run
/notebook-review skills/my-notebook.ipynb
/model-check
/link-review README.md
```
These commands use the exact same validation logic as our CI pipeline, helping you catch issues before pushing. The command definitions are stored in `.claude/commands/` for both local and CI use.
### Before Committing
1. **Run quality checks**:
```bash
uv run ruff check skills/ --fix
uv run ruff format skills/
uv run python scripts/validate_notebooks.py
```
3. **Test notebook execution** (optional, requires API key):
```bash
uv run jupyter nbconvert --to notebook \
--execute skills/classification/guide.ipynb \
--ExecutePreprocessor.kernel_name=python3 \
--output test_output.ipynb
```
### Pre-commit Hooks
Pre-commit hooks will automatically run before each commit to ensure code quality:
- Format code with ruff
- Validate notebook structure
If a hook fails, fix the issues and try committing again.
## Contribution Guidelines
### Notebook Best Practices
1. **Use environment variables for API keys**:
```python
import os
api_key = os.environ.get("ANTHROPIC_API_KEY")
```
2. **Use current Claude models**:
- Use model aliases for better maintainability when available
- Latest Haiku model: `claude-haiku-4-5-20251001` (Haiku 4.5)
- Check current models at: https://docs.claude.com/en/docs/about-claude/models/overview
- Claude will automatically validate model usage in PR reviews
3. **Keep notebooks focused**:
- One concept per notebook
- Clear explanations and comments
- Include expected outputs as markdown cells
4. **Test your notebooks**:
- Ensure they run from top to bottom without errors
- Use minimal tokens for example API calls
- Include error handling
### Git Workflow
1. **Create a feature branch**:
```bash
git checkout -b <your-name>/<feature-description>
# Example: git checkout -b alice/add-rag-example
```
2. **Use conventional commits**:
```bash
# Format: <type>(<scope>): <subject>
# Types:
feat # New feature
fix # Bug fix
docs # Documentation
style # Formatting
refactor # Code restructuring
test # Tests
chore # Maintenance
ci # CI/CD changes
# Examples:
git commit -m "feat(skills): add text-to-sql notebook"
git commit -m "fix(api): use environment variable for API key"
git commit -m "docs(readme): update installation instructions"
```
3. **Keep commits atomic**:
- One logical change per commit
- Write clear, descriptive messages
- Reference issues when applicable
4. **Push and create PR**:
```bash
git push -u origin your-branch-name
gh pr create # Or use GitHub web interface
```
### Pull Request Guidelines
1. **PR Title**: Use conventional commit format
2. **Description**: Include:
- What changes you made
- Why you made them
- How to test them
- Related issue numbers
3. **Keep PRs focused**: One feature/fix per PR
4. **Respond to feedback**: Address review comments promptly
## Testing
### Local Testing
Run the validation suite:
```bash
# Check all notebooks
uv run python scripts/validate_notebooks.py
# Run pre-commit on all files
uv run pre-commit run --all-files
```
### CI/CD
Our GitHub Actions workflows will automatically:
- Validate notebook structure
- Lint code with ruff
- Test notebook execution (for maintainers)
- Check links
- Claude reviews code and model usage
External contributors will have limited API testing to conserve resources.
## Getting Help
- **Issues**: [GitHub Issues](https://github.com/anthropics/anthropic-cookbook/issues)
- **Discussions**: [GitHub Discussions](https://github.com/anthropics/anthropic-cookbook/discussions)
- **Discord**: [Anthropic Discord](https://www.anthropic.com/discord)
## Security
- Never commit API keys or secrets
- Use environment variables for sensitive data
- Report security issues privately to security@anthropic.com
## License
By contributing, you agree that your contributions will be licensed under the same license as the project (MIT License).

View File

@ -0,0 +1,68 @@
# Claude Cookbooks
The Claude Cookbooks provide code and guides designed to help developers build with Claude, offering copy-able code snippets that you can easily integrate into your own projects.
## Prerequisites
To make the most of the examples in this cookbook, you'll need an Claude API key (sign up for free [here](https://www.anthropic.com)).
While the code examples are primarily written in Python, the concepts can be adapted to any programming language that supports interaction with the Claude API.
If you're new to working with the Claude API, we recommend starting with our [Claude API Fundamentals course](https://github.com/anthropics/courses/tree/master/anthropic_api_fundamentals) to get a solid foundation.
## Explore Further
Looking for more resources to enhance your experience with Claude and AI assistants? Check out these helpful links:
- [Anthropic developer documentation](https://docs.claude.com/claude/docs/guide-to-anthropics-prompt-engineering-resources)
- [Anthropic support docs](https://support.anthropic.com)
- [Anthropic Discord community](https://www.anthropic.com/discord)
## Contributing
The Claude Cookbooks thrives on the contributions of the developer community. We value your input, whether it's submitting an idea, fixing a typo, adding a new guide, or improving an existing one. By contributing, you help make this resource even more valuable for everyone.
To avoid duplication of efforts, please review the existing issues and pull requests before contributing.
If you have ideas for new examples or guides, share them on the [issues page](https://github.com/anthropics/anthropic-cookbook/issues).
## Table of recipes
### Capabilities
- [Classification](https://github.com/anthropics/anthropic-cookbook/tree/main/capabilities/classification): Explore techniques for text and data classification using Claude.
- [Retrieval Augmented Generation](https://github.com/anthropics/anthropic-cookbook/tree/main/capabilities/retrieval_augmented_generation): Learn how to enhance Claude's responses with external knowledge.
- [Summarization](https://github.com/anthropics/anthropic-cookbook/tree/main/capabilities/summarization): Discover techniques for effective text summarization with Claude.
### Tool Use and Integration
- [Tool use](https://github.com/anthropics/anthropic-cookbook/tree/main/tool_use): Learn how to integrate Claude with external tools and functions to extend its capabilities.
- [Customer service agent](https://github.com/anthropics/anthropic-cookbook/blob/main/tool_use/customer_service_agent.ipynb)
- [Calculator integration](https://github.com/anthropics/anthropic-cookbook/blob/main/tool_use/calculator_tool.ipynb)
- [SQL queries](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/how_to_make_sql_queries.ipynb)
### Third-Party Integrations
- [Retrieval augmented generation](https://github.com/anthropics/anthropic-cookbook/tree/main/third_party): Supplement Claude's knowledge with external data sources.
- [Vector databases (Pinecone)](https://github.com/anthropics/anthropic-cookbook/blob/main/third_party/Pinecone/rag_using_pinecone.ipynb)
- [Wikipedia](https://github.com/anthropics/anthropic-cookbook/blob/main/third_party/Wikipedia/wikipedia-search-cookbook.ipynb/)
- [Web pages](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/read_web_pages_with_haiku.ipynb)
- [Embeddings with Voyage AI](https://github.com/anthropics/anthropic-cookbook/blob/main/third_party/VoyageAI/how_to_create_embeddings.md)
### Multimodal Capabilities
- [Vision with Claude](https://github.com/anthropics/anthropic-cookbook/tree/main/multimodal):
- [Getting started with images](https://github.com/anthropics/anthropic-cookbook/blob/main/multimodal/getting_started_with_vision.ipynb)
- [Best practices for vision](https://github.com/anthropics/anthropic-cookbook/blob/main/multimodal/best_practices_for_vision.ipynb)
- [Interpreting charts and graphs](https://github.com/anthropics/anthropic-cookbook/blob/main/multimodal/reading_charts_graphs_powerpoints.ipynb)
- [Extracting content from forms](https://github.com/anthropics/anthropic-cookbook/blob/main/multimodal/how_to_transcribe_text.ipynb)
- [Generate images with Claude](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/illustrated_responses.ipynb): Use Claude with Stable Diffusion for image generation.
### Advanced Techniques
- [Sub-agents](https://github.com/anthropics/anthropic-cookbook/blob/main/multimodal/using_sub_agents.ipynb): Learn how to use Haiku as a sub-agent in combination with Opus.
- [Upload PDFs to Claude](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/pdf_upload_summarization.ipynb): Parse and pass PDFs as text to Claude.
- [Automated evaluations](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/building_evals.ipynb): Use Claude to automate the prompt evaluation process.
- [Enable JSON mode](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/how_to_enable_json_mode.ipynb): Ensure consistent JSON output from Claude.
- [Create a moderation filter](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/building_moderation_filter.ipynb): Use Claude to create a content moderation filter for your application.
- [Prompt caching](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/prompt_caching.ipynb): Learn techniques for efficient prompt caching with Claude.
## Additional Resources
- [Anthropic on AWS](https://github.com/aws-samples/anthropic-on-aws): Explore examples and solutions for using Claude on AWS infrastructure.
- [AWS Samples](https://github.com/aws-samples/): A collection of code samples from AWS which can be adapted for use with Claude. Note that some samples may require modification to work optimally with Claude.

View File

@ -0,0 +1,19 @@
# Claude Capabilities
Welcome to the Capabilities section of the Claude Cookbooks! This directory contains a collection of guides that showcase specific capabilities where Claude excels. Each guide provides an in-depth exploration of a particular capability, discussing potential use cases, prompt engineering techniques to optimize results, and approaches for evaluating Claude's performance.
## Guides
- **[Classification with Claude](./classification/guide.ipynb)**: Discover how Claude can revolutionize classification tasks, especially in scenarios with complex business rules and limited training data. This guide walks you through data preparation, prompt engineering with retrieval-augmented generation (RAG), testing, and evaluation.
- **[Retrieval Augmented Generation with Claude](./retrieval_augmented_generation/guide.ipynb)**: Learn how to enhance Claude's capabilities with domain-specific knowledge using RAG. This guide demonstrates how to build a RAG system from scratch, optimize its performance, and create an evaluation suite. You'll learn how techniques like summary indexing and re-ranking can significantly improve precision, recall, and overall accuracy in question-answering tasks.
- **[Retrieval Augmented Generation with Contextual Embeddings](./contextual-embeddings/guide.ipynb)**: Learn how to use a new technique to improve the performance of your RAG system. In traditional RAG, documents are typically split into smaller chunks for efficient retrieval. While this approach works well for many applications, it can lead to problems when individual chunks lack sufficient context. Contextual Embeddings solve this problem by adding relevant context to each chunk before embedding. You'll learn how to use contextual embeddings with semantic search, BM25 search, and reranking to improve performance.
- **[Summarization with Claude](./summarization/guide.ipynb)**: Explore Claude's ability to summarize and synthesize information from multiple sources. This guide covers a variety of summarization techniques, including multi-shot, domain-based, and chunking methods, as well as strategies for handling long-form content and multiple documents. We also explore evaluating summaries, which can be a balance of art, subjectivity, and the right approach!
- **[Text-to-SQL with Claude](./text_to_sql/guide.ipynb)**: This guide covers how to generate complex SQL queries from natural language using prompting techniques, self-improvement, and RAG. We'll also explore how to evaluate and improve the accuracy of generated SQL queries, with evals that test for syntax, data correctness, row count, and more.
## Getting Started
To get started with these guides, simply navigate to the desired guide's directory and follow the instructions provided in the `guide.ipynb` file. Each guide is self-contained and includes all the necessary code, data, and evaluation scripts to reproduce the examples and experiments.

View File

@ -0,0 +1,31 @@
# Claude Cookbooks - Reference Index
This skill contains code and guides for building with Claude AI.
## Categories
### Capabilities
- [Classification](capabilities.md#classification)
- [Retrieval Augmented Generation](capabilities.md#rag)
- [Summarization](capabilities.md#summarization)
- [Text to SQL](capabilities.md#text-to-sql)
### Tool Use and Integration
- [Tool Use Basics](tool_use.md#basics)
- [Customer Service Agent](tool_use.md#customer-service)
- [Calculator Integration](tool_use.md#calculator)
### Multimodal
- [Vision with Claude](multimodal.md#vision)
- [Image Generation](multimodal.md#generation)
- [Charts and Graphs](multimodal.md#charts)
### Advanced Patterns
- [Agents](patterns.md#agents)
- [Sub-agents](patterns.md#sub-agents)
- [Prompt Caching](patterns.md#caching)
### Third Party Integrations
- [Vector Databases](third_party.md#vector-db)
- [Embeddings](third_party.md#embeddings)
- [LlamaIndex](third_party.md#llamaindex)

View File

@ -0,0 +1,68 @@
# Claude Cookbooks
The Claude Cookbooks provide code and guides designed to help developers build with Claude, offering copy-able code snippets that you can easily integrate into your own projects.
## Prerequisites
To make the most of the examples in this cookbook, you'll need an Claude API key (sign up for free [here](https://www.anthropic.com)).
While the code examples are primarily written in Python, the concepts can be adapted to any programming language that supports interaction with the Claude API.
If you're new to working with the Claude API, we recommend starting with our [Claude API Fundamentals course](https://github.com/anthropics/courses/tree/master/anthropic_api_fundamentals) to get a solid foundation.
## Explore Further
Looking for more resources to enhance your experience with Claude and AI assistants? Check out these helpful links:
- [Anthropic developer documentation](https://docs.claude.com/claude/docs/guide-to-anthropics-prompt-engineering-resources)
- [Anthropic support docs](https://support.anthropic.com)
- [Anthropic Discord community](https://www.anthropic.com/discord)
## Contributing
The Claude Cookbooks thrives on the contributions of the developer community. We value your input, whether it's submitting an idea, fixing a typo, adding a new guide, or improving an existing one. By contributing, you help make this resource even more valuable for everyone.
To avoid duplication of efforts, please review the existing issues and pull requests before contributing.
If you have ideas for new examples or guides, share them on the [issues page](https://github.com/anthropics/anthropic-cookbook/issues).
## Table of recipes
### Capabilities
- [Classification](https://github.com/anthropics/anthropic-cookbook/tree/main/capabilities/classification): Explore techniques for text and data classification using Claude.
- [Retrieval Augmented Generation](https://github.com/anthropics/anthropic-cookbook/tree/main/capabilities/retrieval_augmented_generation): Learn how to enhance Claude's responses with external knowledge.
- [Summarization](https://github.com/anthropics/anthropic-cookbook/tree/main/capabilities/summarization): Discover techniques for effective text summarization with Claude.
### Tool Use and Integration
- [Tool use](https://github.com/anthropics/anthropic-cookbook/tree/main/tool_use): Learn how to integrate Claude with external tools and functions to extend its capabilities.
- [Customer service agent](https://github.com/anthropics/anthropic-cookbook/blob/main/tool_use/customer_service_agent.ipynb)
- [Calculator integration](https://github.com/anthropics/anthropic-cookbook/blob/main/tool_use/calculator_tool.ipynb)
- [SQL queries](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/how_to_make_sql_queries.ipynb)
### Third-Party Integrations
- [Retrieval augmented generation](https://github.com/anthropics/anthropic-cookbook/tree/main/third_party): Supplement Claude's knowledge with external data sources.
- [Vector databases (Pinecone)](https://github.com/anthropics/anthropic-cookbook/blob/main/third_party/Pinecone/rag_using_pinecone.ipynb)
- [Wikipedia](https://github.com/anthropics/anthropic-cookbook/blob/main/third_party/Wikipedia/wikipedia-search-cookbook.ipynb/)
- [Web pages](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/read_web_pages_with_haiku.ipynb)
- [Embeddings with Voyage AI](https://github.com/anthropics/anthropic-cookbook/blob/main/third_party/VoyageAI/how_to_create_embeddings.md)
### Multimodal Capabilities
- [Vision with Claude](https://github.com/anthropics/anthropic-cookbook/tree/main/multimodal):
- [Getting started with images](https://github.com/anthropics/anthropic-cookbook/blob/main/multimodal/getting_started_with_vision.ipynb)
- [Best practices for vision](https://github.com/anthropics/anthropic-cookbook/blob/main/multimodal/best_practices_for_vision.ipynb)
- [Interpreting charts and graphs](https://github.com/anthropics/anthropic-cookbook/blob/main/multimodal/reading_charts_graphs_powerpoints.ipynb)
- [Extracting content from forms](https://github.com/anthropics/anthropic-cookbook/blob/main/multimodal/how_to_transcribe_text.ipynb)
- [Generate images with Claude](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/illustrated_responses.ipynb): Use Claude with Stable Diffusion for image generation.
### Advanced Techniques
- [Sub-agents](https://github.com/anthropics/anthropic-cookbook/blob/main/multimodal/using_sub_agents.ipynb): Learn how to use Haiku as a sub-agent in combination with Opus.
- [Upload PDFs to Claude](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/pdf_upload_summarization.ipynb): Parse and pass PDFs as text to Claude.
- [Automated evaluations](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/building_evals.ipynb): Use Claude to automate the prompt evaluation process.
- [Enable JSON mode](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/how_to_enable_json_mode.ipynb): Ensure consistent JSON output from Claude.
- [Create a moderation filter](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/building_moderation_filter.ipynb): Use Claude to create a content moderation filter for your application.
- [Prompt caching](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/prompt_caching.ipynb): Learn techniques for efficient prompt caching with Claude.
## Additional Resources
- [Anthropic on AWS](https://github.com/aws-samples/anthropic-on-aws): Explore examples and solutions for using Claude on AWS infrastructure.
- [AWS Samples](https://github.com/aws-samples/): A collection of code samples from AWS which can be adapted for use with Claude. Note that some samples may require modification to work optimally with Claude.

View File

@ -0,0 +1,66 @@
# Multimodal Capabilities with Claude
Source: anthropics/claude-cookbooks/multimodal
## Vision Capabilities
### Getting Started with Images
- **Location**: `multimodal/getting_started_with_vision.ipynb`
- **Topics**: Image upload, analysis, OCR, visual question answering
### Best Practices for Vision
- **Location**: `multimodal/best_practices_for_vision.ipynb`
- **Topics**: Image quality, prompt engineering for vision, error handling
### Charts and Graphs
- **Location**: `multimodal/reading_charts_graphs_powerpoints.ipynb`
- **Topics**: Data extraction from charts, graph interpretation, PowerPoint analysis
### Form Extraction
- **Location**: `multimodal/how_to_transcribe_text.ipynb`
- **Topics**: OCR, structured data extraction, form processing
## Image Generation
### Illustrated Responses
- **Location**: `misc/illustrated_responses.ipynb`
- **Topics**: Integration with Stable Diffusion, image generation prompts
## Code Examples
```python
# Vision API example
import anthropic
client = anthropic.Anthropic()
# Analyze an image
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/jpeg",
"data": image_base64
}
},
{
"type": "text",
"text": "What's in this image?"
}
]
}]
)
```
## Tips
1. **Image Quality**: Higher resolution images provide better results
2. **Prompt Clarity**: Be specific about what you want to extract or analyze
3. **Format Support**: JPEG, PNG, GIF, WebP supported
4. **Size Limits**: Max 5MB per image

View File

@ -0,0 +1,20 @@
# Building Effective Agents Cookbook
Reference implementation for [Building Effective Agents](https://anthropic.com/research/building-effective-agents) by Erik Schluntz and Barry Zhang.
This repository contains example minimal implementations of common agent workflows discussed in the blog:
- Basic Building Blocks
- Prompt Chaining
- Routing
- Multi-LLM Parallelization
- Advanced Workflows
- Orchestrator-Subagents
- Evaluator-Optimizer
## Getting Started
See the Jupyter notebooks for detailed examples:
- [Basic Workflows](basic_workflows.ipynb)
- [Evaluator-Optimizer Workflow](evaluator_optimizer.ipynb)
- [Orchestrator-Workers Workflow](orchestrator_workers.ipynb)

View File

@ -0,0 +1,39 @@
# Third Party Integrations
Source: anthropics/claude-cookbooks/third_party
## Vector Databases
### Pinecone
- **Location**: `third_party/Pinecone/rag_using_pinecone.ipynb`
- **Use Case**: Retrieval Augmented Generation with vector search
- **Key Concepts**: Embeddings, similarity search, RAG pipeline
## Embeddings
### Voyage AI
- **Location**: `third_party/VoyageAI/how_to_create_embeddings.md`
- **Use Case**: Creating high-quality embeddings for semantic search
- **Key Concepts**: Embedding models, dimensionality, similarity metrics
## Search Integrations
### Wikipedia
- **Location**: `third_party/Wikipedia/wikipedia-search-cookbook.ipynb`
- **Use Case**: Augment Claude with Wikipedia knowledge
- **Key Concepts**: API integration, knowledge retrieval
### Web Pages
- **Location**: `misc/read_web_pages_with_haiku.ipynb`
- **Use Case**: Extract and analyze web page content
- **Key Concepts**: Web scraping, content extraction
## LlamaIndex
- **Location**: `third_party/LlamaIndex/`
- **Use Case**: Advanced document indexing and retrieval
- **Key Concepts**: Index creation, query engines, document loaders
## Deepgram
- **Location**: `third_party/Deepgram/`
- **Use Case**: Audio transcription integration
- **Key Concepts**: Speech-to-text, audio processing

View File

@ -0,0 +1,55 @@
# Tool Use with Claude
Source: anthropics/claude-cookbooks/tool_use
## Overview
Learn how to integrate Claude with external tools and functions to extend its capabilities.
## Key Examples
### Customer Service Agent
- **Location**: `tool_use/customer_service_agent.ipynb`
- **Description**: Build an intelligent customer service agent using Claude with tool integration
- **Key Concepts**: Function calling, state management, conversation flow
### Calculator Integration
- **Location**: `tool_use/calculator_tool.ipynb`
- **Description**: Integrate external calculation tools with Claude
- **Key Concepts**: Tool definitions, parameter passing, result handling
### Memory Demo
- **Location**: `tool_use/memory_demo/`
- **Description**: Implement persistent memory for Claude conversations
- **Key Concepts**: Context management, state persistence
## Best Practices
1. **Tool Definition**: Define clear, specific tool schemas
2. **Error Handling**: Implement robust error handling for tool calls
3. **Validation**: Validate tool inputs and outputs
4. **Context**: Maintain context across tool interactions
## Common Patterns
```python
# Tool definition example
tools = [{
"name": "calculator",
"description": "Performs basic arithmetic operations",
"input_schema": {
"type": "object",
"properties": {
"operation": {"type": "string"},
"a": {"type": "number"},
"b": {"type": "number"}
},
"required": ["operation", "a", "b"]
}
}]
```
## Related Resources
- [Anthropic Tool Use Documentation](https://docs.claude.com/claude/docs/tool-use)
- [API Reference](https://docs.claude.com/claude/reference)

View File

@ -0,0 +1,362 @@
"""
Production-ready memory tool handler for Claude's memory_20250818 tool.
This implementation provides secure, client-side execution of memory operations
with path validation, error handling, and comprehensive security measures.
"""
import shutil
from pathlib import Path
from typing import Any
class MemoryToolHandler:
"""
Handles execution of Claude's memory tool commands.
The memory tool enables Claude to read, write, and manage files in a memory
system through a standardized tool interface. This handler provides client-side
implementation with security controls.
Attributes:
base_path: Root directory for memory storage
memory_root: The /memories directory within base_path
"""
def __init__(self, base_path: str = "./memory_storage"):
"""
Initialize the memory tool handler.
Args:
base_path: Root directory for all memory operations
"""
self.base_path = Path(base_path).resolve()
self.memory_root = self.base_path / "memories"
self.memory_root.mkdir(parents=True, exist_ok=True)
def _validate_path(self, path: str) -> Path:
"""
Validate and resolve memory paths to prevent directory traversal attacks.
Args:
path: The path to validate (must start with /memories)
Returns:
Resolved absolute Path object within memory_root
Raises:
ValueError: If path is invalid or attempts to escape memory directory
"""
if not path.startswith("/memories"):
raise ValueError(
f"Path must start with /memories, got: {path}. "
"All memory operations must be confined to the /memories directory."
)
# Remove /memories prefix and any leading slashes
relative_path = path[len("/memories") :].lstrip("/")
# Resolve to absolute path within memory_root
if relative_path:
full_path = (self.memory_root / relative_path).resolve()
else:
full_path = self.memory_root.resolve()
# Verify the resolved path is still within memory_root
try:
full_path.relative_to(self.memory_root.resolve())
except ValueError as e:
raise ValueError(
f"Path '{path}' would escape /memories directory. "
"Directory traversal attempts are not allowed."
) from e
return full_path
def execute(self, **params: Any) -> dict[str, str]:
"""
Execute a memory tool command.
Args:
**params: Command parameters from Claude's tool use
Returns:
Dict with either 'success' or 'error' key
Supported commands:
- view: Show directory contents or file contents
- create: Create or overwrite a file
- str_replace: Replace text in a file
- insert: Insert text at a specific line
- delete: Delete a file or directory
- rename: Rename or move a file/directory
"""
command = params.get("command")
try:
if command == "view":
return self._view(params)
elif command == "create":
return self._create(params)
elif command == "str_replace":
return self._str_replace(params)
elif command == "insert":
return self._insert(params)
elif command == "delete":
return self._delete(params)
elif command == "rename":
return self._rename(params)
else:
return {
"error": f"Unknown command: '{command}'. "
"Valid commands are: view, create, str_replace, insert, delete, rename"
}
except ValueError as e:
return {"error": str(e)}
except Exception as e:
return {"error": f"Unexpected error executing {command}: {e}"}
def _view(self, params: dict[str, Any]) -> dict[str, str]:
"""View directory contents or file contents."""
path = params.get("path")
view_range = params.get("view_range")
if not path:
return {"error": "Missing required parameter: path"}
full_path = self._validate_path(path)
# Handle directory listing
if full_path.is_dir():
try:
items = []
for item in sorted(full_path.iterdir()):
if item.name.startswith("."):
continue
items.append(f"{item.name}/" if item.is_dir() else item.name)
if not items:
return {"success": f"Directory: {path}\n(empty)"}
return {
"success": f"Directory: {path}\n" + "\n".join([f"- {item}" for item in items])
}
except Exception as e:
return {"error": f"Cannot read directory {path}: {e}"}
# Handle file reading
elif full_path.is_file():
try:
content = full_path.read_text(encoding="utf-8")
lines = content.splitlines()
# Apply view range if specified
if view_range:
start_line = max(1, view_range[0]) - 1 # Convert to 0-indexed
end_line = len(lines) if view_range[1] == -1 else view_range[1]
lines = lines[start_line:end_line]
start_num = start_line + 1
else:
start_num = 1
# Format with line numbers
numbered_lines = [f"{i + start_num:4d}: {line}" for i, line in enumerate(lines)]
return {"success": "\n".join(numbered_lines)}
except UnicodeDecodeError:
return {"error": f"Cannot read {path}: File is not valid UTF-8 text"}
except Exception as e:
return {"error": f"Cannot read file {path}: {e}"}
else:
return {"error": f"Path not found: {path}"}
def _create(self, params: dict[str, Any]) -> dict[str, str]:
"""Create or overwrite a file."""
path = params.get("path")
file_text = params.get("file_text", "")
if not path:
return {"error": "Missing required parameter: path"}
full_path = self._validate_path(path)
# Don't allow creating directories directly
if not path.endswith((".txt", ".md", ".json", ".py", ".yaml", ".yml")):
return {
"error": f"Cannot create {path}: Only text files are supported. "
"Use file extensions: .txt, .md, .json, .py, .yaml, .yml"
}
try:
# Create parent directories if needed
full_path.parent.mkdir(parents=True, exist_ok=True)
# Write the file
full_path.write_text(file_text, encoding="utf-8")
return {"success": f"File created successfully at {path}"}
except Exception as e:
return {"error": f"Cannot create file {path}: {e}"}
def _str_replace(self, params: dict[str, Any]) -> dict[str, str]:
"""Replace text in a file."""
path = params.get("path")
old_str = params.get("old_str")
new_str = params.get("new_str", "")
if not path or old_str is None:
return {"error": "Missing required parameters: path, old_str"}
full_path = self._validate_path(path)
if not full_path.is_file():
return {"error": f"File not found: {path}"}
try:
content = full_path.read_text(encoding="utf-8")
# Check if old_str exists
count = content.count(old_str)
if count == 0:
return {
"error": f"String not found in {path}. The exact text must exist in the file."
}
elif count > 1:
return {
"error": f"String appears {count} times in {path}. "
"The string must be unique. Use more specific context."
}
# Perform replacement
new_content = content.replace(old_str, new_str, 1)
full_path.write_text(new_content, encoding="utf-8")
return {"success": f"File {path} has been edited successfully"}
except Exception as e:
return {"error": f"Cannot edit file {path}: {e}"}
def _insert(self, params: dict[str, Any]) -> dict[str, str]:
"""Insert text at a specific line."""
path = params.get("path")
insert_line = params.get("insert_line")
insert_text = params.get("insert_text", "")
if not path or insert_line is None:
return {"error": "Missing required parameters: path, insert_line"}
full_path = self._validate_path(path)
if not full_path.is_file():
return {"error": f"File not found: {path}"}
try:
lines = full_path.read_text(encoding="utf-8").splitlines()
# Validate insert_line
if insert_line < 0 or insert_line > len(lines):
return {
"error": f"Invalid insert_line {insert_line}. "
f"Must be between 0 and {len(lines)}"
}
# Insert the text
lines.insert(insert_line, insert_text.rstrip("\n"))
# Write back
full_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
return {"success": f"Text inserted at line {insert_line} in {path}"}
except Exception as e:
return {"error": f"Cannot insert into {path}: {e}"}
def _delete(self, params: dict[str, Any]) -> dict[str, str]:
"""Delete a file or directory."""
path = params.get("path")
if not path:
return {"error": "Missing required parameter: path"}
# Prevent deletion of root memories directory
if path == "/memories":
return {"error": "Cannot delete the /memories directory itself"}
full_path = self._validate_path(path)
# Verify the path is within /memories to prevent accidental deletion outside the memory directory
# This provides an additional safety check beyond _validate_path
try:
full_path.relative_to(self.memory_root.resolve())
except ValueError:
return {
"error": f"Invalid operation: Path '{path}' is not within /memories directory. "
"Only paths within /memories can be deleted."
}
if not full_path.exists():
return {"error": f"Path not found: {path}"}
try:
if full_path.is_file():
full_path.unlink()
return {"success": f"File deleted: {path}"}
elif full_path.is_dir():
shutil.rmtree(full_path)
return {"success": f"Directory deleted: {path}"}
except Exception as e:
return {"error": f"Cannot delete {path}: {e}"}
def _rename(self, params: dict[str, Any]) -> dict[str, str]:
"""Rename or move a file/directory."""
old_path = params.get("old_path")
new_path = params.get("new_path")
if not old_path or not new_path:
return {"error": "Missing required parameters: old_path, new_path"}
old_full_path = self._validate_path(old_path)
new_full_path = self._validate_path(new_path)
if not old_full_path.exists():
return {"error": f"Source path not found: {old_path}"}
if new_full_path.exists():
return {
"error": f"Destination already exists: {new_path}. "
"Cannot overwrite existing files/directories."
}
try:
# Create parent directories if needed
new_full_path.parent.mkdir(parents=True, exist_ok=True)
# Perform rename/move
old_full_path.rename(new_full_path)
return {"success": f"Renamed {old_path} to {new_path}"}
except Exception as e:
return {"error": f"Cannot rename {old_path} to {new_path}: {e}"}
def clear_all_memory(self) -> dict[str, str]:
"""
Clear all memory files (useful for testing or starting fresh).
WARNING: This method is for demonstration and testing purposes only.
In production, you should carefully consider whether you need to delete
all memory files, as this will permanently remove all learned patterns
and stored knowledge. Consider using selective deletion instead.
Returns:
Dict with success message
"""
try:
if self.memory_root.exists():
shutil.rmtree(self.memory_root)
self.memory_root.mkdir(parents=True, exist_ok=True)
return {"success": "All memory cleared successfully"}
except Exception as e:
return {"error": f"Cannot clear memory: {e}"}

Binary file not shown.

View File

@ -0,0 +1,123 @@
# Skills
Skills are folders of instructions, scripts, and resources that Claude loads dynamically to improve performance on specialized tasks. Skills teach Claude how to complete specific tasks in a repeatable way, whether that's creating documents with your company's brand guidelines, analyzing data using your organization's specific workflows, or automating personal tasks.
For more information, check out:
- [What are skills?](https://support.claude.com/en/articles/12512176-what-are-skills)
- [Using skills in Claude](https://support.claude.com/en/articles/12512180-using-skills-in-claude)
- [How to create custom skills](https://support.claude.com/en/articles/12512198-creating-custom-skills)
- [Equipping agents for the real world with Agent Skills](https://anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills)
# About This Repository
This repository contains example skills that demonstrate what's possible with Claude's skills system. These examples range from creative applications (art, music, design) to technical tasks (testing web apps, MCP server generation) to enterprise workflows (communications, branding, etc.).
Each skill is self-contained in its own directory with a `SKILL.md` file containing the instructions and metadata that Claude uses. Browse through these examples to get inspiration for your own skills or to understand different patterns and approaches.
The example skills in this repo are open source (Apache 2.0). We've also included the document creation & editing skills that power [Claude's document capabilities](https://www.anthropic.com/news/create-files) under the hood in the [`document-skills/`](./document-skills/) folder. These are source-available, not open source, but we wanted to share these with developers as a reference for more complex skills that are actively used in a production AI application.
**Note:** These are reference examples for inspiration and learning. They showcase general-purpose capabilities rather than organization-specific workflows or sensitive content.
## Disclaimer
**These skills are provided for demonstration and educational purposes only.** While some of these capabilities may be available in Claude, the implementations and behaviors you receive from Claude may differ from what is shown in these examples. These examples are meant to illustrate patterns and possibilities. Always test skills thoroughly in your own environment before relying on them for critical tasks.
# Example Skills
This repository includes a diverse collection of example skills demonstrating different capabilities:
## Creative & Design
- **algorithmic-art** - Create generative art using p5.js with seeded randomness, flow fields, and particle systems
- **canvas-design** - Design beautiful visual art in .png and .pdf formats using design philosophies
- **slack-gif-creator** - Create animated GIFs optimized for Slack's size constraints
## Development & Technical
- **artifacts-builder** - Build complex claude.ai HTML artifacts using React, Tailwind CSS, and shadcn/ui components
- **mcp-server** - Guide for creating high-quality MCP servers to integrate external APIs and services
- **webapp-testing** - Test local web applications using Playwright for UI verification and debugging
## Enterprise & Communication
- **brand-guidelines** - Apply Anthropic's official brand colors and typography to artifacts
- **internal-comms** - Write internal communications like status reports, newsletters, and FAQs
- **theme-factory** - Style artifacts with 10 pre-set professional themes or generate custom themes on-the-fly
## Meta Skills
- **skill-creator** - Guide for creating effective skills that extend Claude's capabilities
- **template-skill** - A basic template to use as a starting point for new skills
# Document Skills
The `document-skills/` subdirectory contains skills that Anthropic developed to help Claude create various document file formats. These skills demonstrate advanced patterns for working with complex file formats and binary data:
- **docx** - Create, edit, and analyze Word documents with support for tracked changes, comments, formatting preservation, and text extraction
- **pdf** - Comprehensive PDF manipulation toolkit for extracting text and tables, creating new PDFs, merging/splitting documents, and handling forms
- **pptx** - Create, edit, and analyze PowerPoint presentations with support for layouts, templates, charts, and automated slide generation
- **xlsx** - Create, edit, and analyze Excel spreadsheets with support for formulas, formatting, data analysis, and visualization
**Important Disclaimer:** These document skills are point-in-time snapshots and are not actively maintained or updated. Versions of these skills ship pre-included with Claude. They are primarily intended as reference examples to illustrate how Anthropic approaches developing more complex skills that work with binary file formats and document structures.
# Try in Claude Code, Claude.ai, and the API
## Claude Code
You can register this repository as a Claude Code Plugin marketplace by running the following command in Claude Code:
```
/plugin marketplace add anthropics/skills
```
Then, to install a specific set of skills:
1. Select `Browse and install plugins`
2. Select `anthropic-agent-skills`
3. Select `document-skills` or `example-skills`
4. Select `Install now`
Alternatively, directly install either Plugin via:
```
/plugin install document-skills@anthropic-agent-skills
/plugin install example-skills@anthropic-agent-skills
```
After installing the plugin, you can use the skill by just mentioning it. For instance, if you install the `document-skills` plugin from the marketplace, you can ask Claude Code to do something like: "Use the PDF skill to extract the form fields from path/to/some-file.pdf"
## Claude.ai
These example skills are all already available to paid plans in Claude.ai.
To use any skill from this repository or upload custom skills, follow the instructions in [Using skills in Claude](https://support.claude.com/en/articles/12512180-using-skills-in-claude#h_a4222fa77b).
## Claude API
You can use Anthropic's pre-built skills, and upload custom skills, via the Claude API. See the [Skills API Quickstart](https://docs.claude.com/en/api/skills-guide#creating-a-skill) for more.
# Creating a Basic Skill
Skills are simple to create - just a folder with a `SKILL.md` file containing YAML frontmatter and instructions. You can use the **template-skill** in this repository as a starting point:
```markdown
---
name: my-skill-name
description: A clear description of what this skill does and when to use it
---
# My Skill Name
[Add your instructions here that Claude will follow when this skill is active]
## Examples
- Example usage 1
- Example usage 2
## Guidelines
- Guideline 1
- Guideline 2
```
The frontmatter requires only two fields:
- `name` - A unique identifier for your skill (lowercase, hyphens for spaces)
- `description` - A complete description of what the skill does and when to use it
The markdown content below contains the instructions, examples, and guidelines that Claude will follow. For more details, see [How to create custom skills](https://support.claude.com/en/articles/12512198-creating-custom-skills).
# Partner Skills
Skills are a great way to teach Claude how to get better at using specific pieces of software. As we see awesome example skills from partners, we may highlight some of them here:
- **Notion** - [Notion Skills for Claude](https://www.notion.so/notiondevs/Notion-Skills-for-Claude-28da4445d27180c7af1df7d8615723d0)

View File

@ -0,0 +1,111 @@
# Claude Skills Documentation Index
## Categories
### README
**File:** `README.md`
**Pages:** 1 (122 lines)
Complete overview of Claude Skills including:
- What are skills and how they work
- Example skills by category
- Document skills (source-available)
- Usage across platforms (Claude Code, Claude.ai, API)
- Creating basic skills
- Partner skills
## Quick Links
- What are skills → `README.md` (line 1-9)
- Example skills list → `README.md` (line 24-45)
- Document skills → `README.md` (line 47-56)
- Claude Code setup → `README.md` (line 58-78)
- Claude.ai usage → `README.md` (line 80-84)
- Claude API → `README.md` (line 86-88)
- Creating a skill → `README.md` (line 90-117)
- Partner skills → `README.md` (line 119-122)
## Topics Covered
### Getting Started
- What skills are
- How skills work
- Platform availability
- Installation methods
### Example Skills by Category
**Creative & Design:**
- Algorithmic art generation
- Canvas design
- Slack GIF creation
**Development & Technical:**
- HTML artifacts builder
- MCP server creation
- Webapp testing
**Enterprise & Communication:**
- Brand guidelines
- Internal communications
- Theme factory
**Meta Skills:**
- Skill creator guide
- Template skill
### Document Skills (Advanced)
- DOCX (Word documents)
- PDF (PDF manipulation)
- PPTX (PowerPoint presentations)
- XLSX (Excel spreadsheets)
### Creating Skills
- Basic structure (folder + SKILL.md)
- YAML frontmatter requirements
- Markdown instructions
- Template usage
### Platform Integration
- Claude Code plugin marketplace
- Claude.ai skills interface
- Claude API integration
- Cross-platform portability
## Skill Structure
```
skill-name/
├── SKILL.md # Required: Main instructions
├── references/ # Optional: Documentation
├── scripts/ # Optional: Helper scripts
└── assets/ # Optional: Resources
```
## YAML Frontmatter
```yaml
---
name: skill-name
description: Clear description of what the skill does
---
```
## External Resources
- **Support Articles:**
- What are skills?
- Using skills in Claude
- Creating custom skills
- **Blog Posts:**
- Equipping agents with Agent Skills
- **API Documentation:**
- Skills API Quickstart
- Creating skills via API
## License
Example skills: Apache 2.0 (open source)
Document skills: Source-available (reference only)

80
skills/coingecko/SKILL.md Normal file
View File

@ -0,0 +1,80 @@
---
name: coingecko
description: CoinGecko API documentation - cryptocurrency market data API, price feeds, market cap, volume, historical data. Use when integrating CoinGecko API, building crypto price trackers, or accessing cryptocurrency market data.
---
# Coingecko Skill
Comprehensive assistance with coingecko development, generated from official documentation.
## When to Use This Skill
This skill should be triggered when:
- Working with coingecko
- Asking about coingecko features or APIs
- Implementing coingecko solutions
- Debugging coingecko code
- Learning coingecko best practices
## Quick Reference
### Common Patterns
*Quick reference patterns will be added as you use the skill.*
## Reference Files
This skill includes comprehensive documentation in `references/`:
- **authentication.md** - Authentication documentation
- **coins.md** - Coins documentation
- **contract.md** - Contract documentation
- **exchanges.md** - Exchanges documentation
- **introduction.md** - Introduction documentation
- **market_data.md** - Market Data documentation
- **nfts.md** - Nfts documentation
- **other.md** - Other documentation
- **pricing.md** - Pricing documentation
- **reference.md** - Reference documentation
- **trending.md** - Trending documentation
Use `view` to read specific reference files when detailed information is needed.
## Working with This Skill
### For Beginners
Start with the getting_started or tutorials reference files for foundational concepts.
### For Specific Features
Use the appropriate category reference file (api, guides, etc.) for detailed information.
### For Code Examples
The quick reference section above contains common patterns extracted from the official docs.
## Resources
### references/
Organized documentation extracted from official sources. These files contain:
- Detailed explanations
- Code examples with language annotations
- Links to original documentation
- Table of contents for quick navigation
### scripts/
Add helper scripts here for common automation tasks.
### assets/
Add templates, boilerplate, or example projects here.
## Notes
- This skill was automatically generated from official documentation
- Reference files preserve the structure and examples from source docs
- Code examples include language detection for better syntax highlighting
- Quick reference patterns are extracted from common usage examples in the docs
## Updating
To refresh this skill with updated documentation:
1. Re-run the scraper with the same configuration
2. The skill will be rebuilt with the latest information

View File

@ -0,0 +1,200 @@
# Coingecko - Authentication
**Pages:** 3
---
## Authentication (Public/Demo)
**URL:** llms-txt#authentication-(public/demo)
**Contents:**
- CoinGecko API Authentication Method
- API Key Usage Credits
Source: https://docs.coingecko.com/v3.0.1/reference/authentication
Authentication method for CoinGecko Public API (Demo plan users)
<Note>
### **Notes**
* Demo API Key is only available for CoinGecko Public Demo API Plan, the root URL for CoinGecko Public Demo API must be `https://api.coingecko.com/api/v3/`.
* ⚠️ You are recommended to store the API key securely in your own backend and use a proxy to insert the key into the request URL.
* The authentication method below is for CoinGecko Public Demo API only. For **paid plan users with Pro-API key**, please refer to [this page](/reference/authentication) instead.
* User Guide: [How to sign up for CoinGecko Demo API and generate an API key?](https://support.coingecko.com/hc/en-us/articles/21880397454233)
* It's highly recommended to use the **Headers method** when making API requests for better security. Using query string parameters can risk exposing your API key.
</Note>
## CoinGecko API Authentication Method
If this is your first time using the Demo API key, you can supply API Key to the root URL using one of these ways:
1. Header (Recommended): `x-cg-demo-api-key`
2. Query String Parameter: `x_cg_demo_api_key`
| Authentication Method | Example using [Ping](/v3.0.1/reference/ping-server) Endpoint |
| ---------------------- | ------------------------------------------------------------------------------------------ |
| Header (cURL) | `curl -X GET "https://api.coingecko.com/api/v3/ping" -H "x-cg-demo-api-key: YOUR_API_KEY"` |
| Query String Parameter | `https://api.coingecko.com/api/v3/ping?x_cg_demo_api_key=YOUR_API_KEY` |
## API Key Usage Credits
* Each request made to any endpoint counts as a single call (1 call = 1 credit).
* Your monthly credit & rate limit are determined by the paid plan to which you subscribe. For more details, please refer to this [page](https://www.coingecko.com/en/api/pricing).
* To check the API usage, please go to the [developer dashboard](https://www.coingecko.com/en/developers/dashboard) or follow the guide [here](/v3.0.1/reference/setting-up-your-api-key#4-api-usage-report).
---
## Authentication (Pro API)
**URL:** llms-txt#authentication-(pro-api)
**Contents:**
- CoinGecko API Authentication Method
- 🔥 Accessing Onchain DEX data
- API Key Usage Credits
Source: https://docs.coingecko.com/reference/authentication
Authentication method for CoinGecko Pro API (Paid plan subscribers with Pro-API keys)
<Note>
### **Notes**
* Pro API Key is only available for [CoinGecko API paid plan](https://www.coingecko.com/en/api/pricing) subscribers, the root URL for CoinGecko Pro API must be `https://pro-api.coingecko.com/api/v3/`.
* You are recommended to store the API key securely in your own backend and use a proxy to insert the key into the request URL.
* It's highly recommended to use the Headers method when making API requests for better security. Using query string parameters can risk exposing your API key.
</Note>
## CoinGecko API Authentication Method
If this is your first time using the Pro API key, you can supply API Key to the root URL using one of these ways:
1. Header (Recommended): `x-cg-pro-api-key`
2. Query String Parameter: `x_cg_pro_api_key`
| Authentication Method | Example using [Ping](/reference/ping-server) Endpoint |
| ---------------------- | --------------------------------------------------------------------------------------------- |
| Header (cURL) | `curl -X GET "https://pro-api.coingecko.com/api/v3/ping" -H "x-cg-pro-api-key: YOUR_API_KEY"` |
| Query String Parameter | `https://pro-api.coingecko.com/api/v3/ping?x_cg_pro_api_key=YOUR_API_KEY` |
## 🔥 Accessing Onchain DEX data
You can now use the Pro-API key (exclusive to any paid plan subscriber) to call onchain DEX data powered by [GeckoTerminal](https://www.geckoterminal.com/).
<Note>
### **Notes**
* Authentication method for onchain endpoints is exactly same as other endpoints.
* When using the CG Pro API to access onchain DEX data, include the `/onchain` endpoint path in the request.
</Note>
| Authentication Method | Example using [Simple Token Price](/reference/onchain-simple-price) Endpoint |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Header (cURL) | `curl -X GET "<https://pro-api.coingecko.com/api/v3/onchain/simple/networks/eth/token_price/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2>" -H "x-cg-pro-api-key: YOUR_API_KEY"` |
| Query String Parameter | `https://pro-api.coingecko.com/api/v3/onchain/simple/networks/eth/token_price/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2?x_cg_pro_api_key=YOUR_API_KEY` |
## API Key Usage Credits
* Each request made to any endpoint counts as a single call (1 call = 1 credit).
* Each successful API request (Status 200) will deduct 1 credit from your monthly credit allowance.
* Unsuccessful Requests (Status 4xx, 5xx, etc) will not count towards credit deduction.
* Regardless of the HTTP status code returned (including 4xx and 5xx errors), all API requests will count towards your **minute rate limit**.
* Your monthly credit & rate limit are determined by the paid plan to which you subscribe. For more details, please refer to this [page](https://www.coingecko.com/en/api/pricing).
* To check the API usage, please go to the [developer dashboard](https://www.coingecko.com/en/developers/dashboard) or follow the guide [here](/reference/setting-up-your-api-key#4-api-usage-report)
---
## Setting Up Your API Key
**URL:** llms-txt#setting-up-your-api-key
**Contents:**
- 1. Creating a new API Key
- 2. Making API Request
- 3. Edit or Delete API Key
- 4. API Usage Report
- 5. Others
- Call Consumption Alerts
- Overage Option (Beta)
Source: https://docs.coingecko.com/docs/setting-up-your-api-key
👋 **New to CoinGecko API?** Sign up for an account [here](https://www.coingecko.com/en/api/pricing)
## 1. Creating a new API Key
* Once you have signed up and logged in to your CoinGecko account, go to [Developer Dashboard](https://www.coingecko.com/en/developers/dashboard):
<Frame>
<img src="https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/d5fdca3-image.png?fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=01b58675fd1f038e4998877c0dde2cce" data-og-width="2535" width="2535" data-og-height="1454" height="1454" data-path="images/reference/d5fdca3-image.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/d5fdca3-image.png?w=280&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=73cd461df259d6584539d8fa4182e8c7 280w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/d5fdca3-image.png?w=560&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=b450ef8d7ff960560975cfbcf02c9cd8 560w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/d5fdca3-image.png?w=840&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=a712cb1278b923471296f9eff1a66bcb 840w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/d5fdca3-image.png?w=1100&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=ad1648c3f6875aad6a69b7d885545f9f 1100w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/d5fdca3-image.png?w=1650&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=bb4f72d8c718de14aa95dc77195b1b6f 1650w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/d5fdca3-image.png?w=2500&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=a04a90a2ac24c43094ed536a92d6c125 2500w" />
</Frame>
* Click on **+ Add New Key** button to create a new API key:
<Frame>
<img src="https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/0e2f30d-image.png?fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=49cf69a9b5ada9685301fe90281ec4ca" data-og-width="2380" width="2380" data-og-height="1695" height="1695" data-path="images/reference/0e2f30d-image.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/0e2f30d-image.png?w=280&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=dae015f221e2baf42b535213c492282d 280w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/0e2f30d-image.png?w=560&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=475c556a13a18691d600261b16f36c3f 560w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/0e2f30d-image.png?w=840&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=6c707c3bd727ef27a62a122c612f70af 840w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/0e2f30d-image.png?w=1100&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=e575c119ac20eddb902be7eba947e8e3 1100w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/0e2f30d-image.png?w=1650&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=6543d53ea75c2f201ea1bd9e03bec784 1650w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/0e2f30d-image.png?w=2500&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=ef098f326f88369b848b496374bb90b6 2500w" />
</Frame>
## 2. Making API Request
* **Root URLs:**
* Pro API: `https://pro-api.coingecko.com/api/v3/`, refer to [Pro API Authentication](/reference/authentication).
* Demo API: `https://api.coingecko.com/api/v3/`, refer to [Demo API Authentication](/v3.0.1/reference/authentication).
* **Example using the `/ping` endpoint:**
* Pro API: `https://pro-api.coingecko.com/api/v3/ping?x_cg_pro_api_key=YOUR_API_KEY`
* Demo API: `https://api.coingecko.com/api/v3/ping?x_cg_demo_api_key=YOUR_API_KEY`
<Frame>
<img src="https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/27ff800-image.png?fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=e3d99147f58fba36640e1bfe509349b1" data-og-width="1784" width="1784" data-og-height="604" height="604" data-path="images/reference/27ff800-image.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/27ff800-image.png?w=280&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=591078670f4f8bd13429f7fb18afaa90 280w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/27ff800-image.png?w=560&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=f5a27f6ae38522bb400bef3b620920ce 560w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/27ff800-image.png?w=840&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=a1aec54f1196f3f1b34f6f6124750fa7 840w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/27ff800-image.png?w=1100&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=c69aba5a0e5cd26d4789a231d168eb05 1100w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/27ff800-image.png?w=1650&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=ce2ee82a0be4d2b2595b5a356995c8d2 1650w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/27ff800-image.png?w=2500&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=cf0d9441cf738541947802398d367d65 2500w" />
</Frame>
## 3. Edit or Delete API Key
* Go to Developer's Dashboard and click “Edit” button on a specific API Key.
* In case the API Key is compromised, you may delete the API Key by clicking the "Delete" button.
* You may also update the label and save the changes by clicking "Save" button.
<Frame>
<img src="https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/cf29b58-image.png?fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=106da6dd2c0954fdac0b343222bd47d0" data-og-width="2372" width="2372" data-og-height="1054" height="1054" data-path="images/reference/cf29b58-image.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/cf29b58-image.png?w=280&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=34459564277bfa0cad6f5a700ecf8eb3 280w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/cf29b58-image.png?w=560&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=54225845278952d0a07ccec89b21b045 560w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/cf29b58-image.png?w=840&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=4504c5e87fc757c04537e3684ee675af 840w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/cf29b58-image.png?w=1100&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=8b2e7beb62498611215c9380911729e2 1100w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/cf29b58-image.png?w=1650&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=785b9d021240f872e1c5e94253ec59c0 1650w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/cf29b58-image.png?w=2500&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=d595ad19992b79691106f91ff2ef035c 2500w" />
</Frame>
## 4. API Usage Report
* You can monitor your API usage in the Usage Report section, which provides details such as:
* Total Monthly API Calls.
* Remaining Monthly API Calls.
* Rate Limit (Request Per Minute) — maximum number of API requests allowed in one minute.
* Last Used — the timestamp of the last used instance.
<Frame>
<img src="https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/c436404-image.png?fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=731ada28dc58aa21345e3ad74f79638a" data-og-width="2373" width="2373" data-og-height="1047" height="1047" data-path="images/reference/c436404-image.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/c436404-image.png?w=280&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=2f15435343b765ff33590235b98bb9ab 280w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/c436404-image.png?w=560&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=844e00763035fb01d9b6daed2db54c1d 560w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/c436404-image.png?w=840&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=8e2d5ed4c8da42f24554c97051e92d86 840w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/c436404-image.png?w=1100&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=ba78440ee678f4accc817e389c1b8928 1100w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/c436404-image.png?w=1650&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=403f14e82c4670b20f1440aa482d18c9 1650w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/c436404-image.png?w=2500&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=994b3e54b5d7d9327c4a23e6a28f6088 2500w" />
</Frame>
* You can also check your full historical usage by specifying "API Keys", "timeframe" or "date range". You may export as CSV for more comprehensive view.
<Frame>
<img src="https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/ed3143e-image.png?fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=fdebb203ab2f8c54dd4d2b57188131e6" data-og-width="2108" width="2108" data-og-height="1328" height="1328" data-path="images/reference/ed3143e-image.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/ed3143e-image.png?w=280&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=c396c9240b947a2380f40b4abf463208 280w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/ed3143e-image.png?w=560&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=8fc0778d14dad543359ee1f5e484ab2b 560w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/ed3143e-image.png?w=840&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=930dac6d510ce69c0261298b752c21c3 840w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/ed3143e-image.png?w=1100&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=9d617276ba1552ba5053377231c0205c 1100w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/ed3143e-image.png?w=1650&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=b14b89d98e4426e80e8d85b73702f954 1650w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/ed3143e-image.png?w=2500&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=752bf481dc327a547568d4701cd5e531 2500w" />
</Frame>
### Call Consumption Alerts
You may enable or disable call consumption alerts in the tab below to receive emails when specific credit usage thresholds are reached.
<Frame>
<img src="https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/752e839-image.png?fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=0152d66e48fe99fe40f6738f1b9a196c" data-og-width="2112" width="2112" data-og-height="1044" height="1044" data-path="images/reference/752e839-image.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/752e839-image.png?w=280&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=7c1eb5850e0ed72d674e76be142a2e05 280w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/752e839-image.png?w=560&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=64e6884c71f6e9514b1a76fffccbc3ee 560w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/752e839-image.png?w=840&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=bec801fac3b85f6cfa6b662ae626eab3 840w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/752e839-image.png?w=1100&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=d7b15b7e7df828c7872fa2a523138473 1100w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/752e839-image.png?w=1650&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=4787aae81682669a51ce54dd9d830941 1650w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/752e839-image.png?w=2500&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=09437ce25f2f9d9c42018967537b0d13 2500w" />
</Frame>
### Overage Option (Beta)
* The overage option enables you to make API calls when your usage exceeds the monthly credits.
* You can activate the overage option by clicking the "Turn On Overage" button, ensuring uninterrupted service and allowing you to continue making API calls or vice versa.
<Frame>
<img src="https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/b4711e6-image.png?fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=6d293516eea9798436bd1a28fcf55cd8" data-og-width="2218" width="2218" data-og-height="1074" height="1074" data-path="images/reference/b4711e6-image.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/b4711e6-image.png?w=280&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=3fc7358d6a4b47e0ac5b9ab1170731ea 280w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/b4711e6-image.png?w=560&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=50aac137f52b5c6d3ff3c0dfbcf440ed 560w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/b4711e6-image.png?w=840&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=5c0a29a1fb4d1a16e588c2ab1d7725df 840w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/b4711e6-image.png?w=1100&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=96aab6a665b736e7eff55b04f2202346 1100w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/b4711e6-image.png?w=1650&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=56b3971e1aaa69dc6ed99ee745fe6f7a 1650w, https://mintcdn.com/coingecko/a7cplMjqO5fc2v5e/images/reference/b4711e6-image.png?w=2500&fit=max&auto=format&n=a7cplMjqO5fc2v5e&q=85&s=a090e24c154fffcc39f4fc8c069840bb 2500w" />
</Frame>
---

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,23 @@
# Coingecko - Contract
**Pages:** 1
---
## NFTs Collection Data by Contract Address
**URL:** llms-txt#nfts-collection-data-by-contract-address
Source: https://docs.coingecko.com/v3.0.1/reference/nfts-contract-address
v3.0.1/reference/api-reference/coingecko-demo.json get /nfts/{asset_platform_id}/contract/{contract_address}
This endpoint allows you to **query all the NFT data (name, floor price, 24hr volume ...) based on the NFT collection contract address and respective asset platform**
* You may also obtain the asset platform id and contract address through [/nfts/list](/v3.0.1/reference/nfts-list) endpoint.
</Tip>
* Solana NFT & Art Blocks are not supported for this endpoint, please use [/nfts/\{id}](/v3.0.1/reference/nfts-id) endpoint instead.
* Cache / Update Frequency: every 60 seconds for all the API plans.
</Note>
---

View File

@ -0,0 +1,259 @@
# Coingecko - Exchanges
**Pages:** 14
---
## Exchange Volume Chart by ID
**URL:** llms-txt#exchange-volume-chart-by-id
Source: https://docs.coingecko.com/v3.0.1/reference/exchanges-id-volume-chart
v3.0.1/reference/api-reference/coingecko-demo.json get /exchanges/{id}/volume_chart
This endpoint allows you to **query the historical volume chart data with time in UNIX and trading volume data in BTC based on exchange's ID**
* You can use this endpoint to query the historical volume chart data of **derivatives exchanges** as well.
* The exchange volume in the response is provided in BTC. To convert it to other currencies, please use [/exchange\_rates](/v3.0.1/reference/exchange-rates) endpoint.
* Data granularity is automatic (cannot be adjusted):
* 1 day = 10-minutely
* 7, 14 days = hourly
* 30 days & above = daily
* Cache / Update Frequency: every 60 seconds for all the API plans.
</Note>
---
## Derivatives Tickers List
**URL:** llms-txt#derivatives-tickers-list
Source: https://docs.coingecko.com/v3.0.1/reference/derivatives-tickers
v3.0.1/reference/api-reference/coingecko-demo.json get /derivatives
This endpoint allows you to **query all the tickers from derivatives exchanges on CoinGecko**
* Data for `open_interest` and `volume_24h` in the endpoint responses are in USD.
* Cache / Update Frequency: every 30 seconds for all the API plans.
</Note>
---
## 💼 Exchange Volume Chart within Time Range by ID
**URL:** llms-txt#💼-exchange-volume-chart-within-time-range-by-id
Source: https://docs.coingecko.com/reference/exchanges-id-volume-chart-range
reference/api-reference/coingecko-pro.json get /exchanges/{id}/volume_chart/range
This endpoint allows you to **query the historical volume chart data in BTC by specifying date range in UNIX based on exchange's ID**
* You can query the historical volume chart data of **derivatives exchanges** with this endpoint as well.
* The data interval for this endpoint is fixed at daily.
* The date range between `from` and `to` must be within 31 days.
* Cache/Update Frequency: 5 minutes
* Exclusive for Paid Plan Subscribers (Analyst, Lite, Pro and Enterprise)
</Note>
---
## Derivatives Exchange Data by ID
**URL:** llms-txt#derivatives-exchange-data-by-id
Source: https://docs.coingecko.com/v3.0.1/reference/derivatives-exchanges-id
v3.0.1/reference/api-reference/coingecko-demo.json get /derivatives/exchanges/{id}
This endpoint allows you to **query the derivatives exchange's related data (ID, name, open interest, ...) based on the exchanges' ID**
* For `include_tickers` param, you may change the value to either `all` to include all the tickers or `unexpired` to include unexpired tickers in the responses. You may leave it blank to omit the tickers data.
</Tip>
* Cache / Update Frequency: every 30 seconds for all the API plans.
</Note>
---
## Supported Dexes List by Network (ID Map)
**URL:** llms-txt#supported-dexes-list-by-network-(id-map)
Source: https://docs.coingecko.com/v3.0.1/reference/dexes-list
v3.0.1/reference/api-reference/onchain-demo.json get /networks/{network}/dexes
This endpoint allows you to **query all the supported decentralized exchanges (DEXs) based on the provided network on GeckoTerminal**
* You may use this endpoint to query the list of DEXs with DEX ID for other endpoints that contain params like `dex`.
* You may include values such as `page` to specify which page of responses you would like to show.
</Tip>
---
## Exchanges List with data
**URL:** llms-txt#exchanges-list-with-data
Source: https://docs.coingecko.com/v3.0.1/reference/exchanges
v3.0.1/reference/api-reference/coingecko-demo.json get /exchanges
This endpoint allows you to **query all the supported exchanges with exchanges' data (ID, name, country, ...) that have active trading volumes on CoinGecko**
* You may include values such as `per_page` and `page` to specify how many results you would like to show in the responses per page and which page of responses you would like to show.
</Tip>
* All the exchanges in the responses are the exchanges with active trading volume on CoinGecko, any inactive or deactivated exchanges will be removed from the list.
* Cache / Update Frequency: every 60 seconds for all the API plans.
</Note>
---
## Derivatives Exchanges List with Data
**URL:** llms-txt#derivatives-exchanges-list-with-data
Source: https://docs.coingecko.com/v3.0.1/reference/derivatives-exchanges
v3.0.1/reference/api-reference/coingecko-demo.json get /derivatives/exchanges
This endpoint allows you to **query all the derivatives exchanges with related data (ID, name, open interest, ...) on CoinGecko**
* You may include values such as `per_page` and `page` to specify how many results you would like to show in the responses per page and which page of responses you would like to show.
</Tip>
* Cache / Update Frequency: every 60 seconds for all the API plans.
</Note>
---
## Exchanges List (ID Map)
**URL:** llms-txt#exchanges-list-(id-map)
Source: https://docs.coingecko.com/v3.0.1/reference/exchanges-list
v3.0.1/reference/api-reference/coingecko-demo.json get /exchanges/list
This endpoint allows you to **query all the exchanges with ID and name**
* You may use this endpoint to query the list of exchanges including **derivatives exchanges** for other endpoints that contain params like `id`(exchange ID).
</Tip>
* There is no pagination required for this endpoint.
* Cache / Update Frequency: every 5 minutes for all the API plans.
</Note>
---
## 💼 Global Market Cap Chart Data
**URL:** llms-txt#💼-global-market-cap-chart-data
Source: https://docs.coingecko.com/reference/global-market-cap-chart
reference/api-reference/coingecko-pro.json get /global/market_cap_chart
This endpoint allows you to **query historical global market cap and volume data by number of days away from now**
* CoinGecko equivalent page: [https://www.coingecko.com/en/global-charts](https://www.coingecko.com/en/global-charts).
* Data Granularity (auto):
* 1 day from now = **hourly** data
* 2 days & above from now = **daily** data
* Exclusive for all Paid Plan Subscribers (Analyst, Lite, Pro and Enterprise).
* The last completed UTC day (00:00) is available 5 minutes after midnight on the next UTC day (00:05). The cache will **always expire at 00:05 UTC**. If you wish to get the latest daily data (00:00 UTC), you can make request at 00:05 UTC or later.
* Cache / Update Frequency: every 1 minute.
</Note>
---
## 💼 NFTs List with Market Data
**URL:** llms-txt#💼-nfts-list-with-market-data
Source: https://docs.coingecko.com/reference/nfts-markets
reference/api-reference/coingecko-pro.json get /nfts/markets
This endpoint allows you to **query all the supported NFT collections with floor price, market cap, volume and market related data on CoinGecko**
* You may include values such as `per_page` and `page` to specify how many results you would like to show in the responses per page and which page of responses you would like to show.
</Tip>
* Cache / Update Frequency: every 5 minutes.
* Exclusive for Paid Plan Subscribers (Analyst, Lite, Pro and Enterprise).
* CoinGecko equivalent page: [https://www.coingecko.com/en/nft](https://www.coingecko.com/en/nft).
* Some collection with low liquidity may not be ranked by Market Cap value, learn more [here](https://support.coingecko.com/hc/en-us/articles/37226121227545-What-is-NFT-Market-Cap). Sorting by Mcap ranking will first prioritise Market Cap value of liquid NFT collections, then followed by trading volume of illiquid NFT collections.
</Note>
---
## Exchange Tickers by ID
**URL:** llms-txt#exchange-tickers-by-id
Source: https://docs.coingecko.com/v3.0.1/reference/exchanges-id-tickers
v3.0.1/reference/api-reference/coingecko-demo.json get /exchanges/{id}/tickers
This endpoint allows you to **query exchange's tickers based on exchange's ID**
* Responses are paginated and limited to 100 tickers per page. You may specify the page number using the `page` params to retrieve the tickers accordingly.
* `order=base_target` sorts tickers by `base` symbol, then `target` symbol, in lexicographical order (`0 -> 9`, followed by `a -> z`).\
This sorting method ensures stable pagination results, minimizing cases where cached responses might otherwise cause duplicate or missing tickers across paginated pages.
* When `dex_pair_format=symbol`, the DEX pair `base` and `target` are displayed in symbol format (e.g. `WETH`, `USDC`) instead of as contract addresses.
* Cache / Update Frequency: every 60 seconds for all the API plans.
</Note>
---
## BTC-to-Currency Exchange Rates
**URL:** llms-txt#btc-to-currency-exchange-rates
Source: https://docs.coingecko.com/v3.0.1/reference/exchange-rates
v3.0.1/reference/api-reference/coingecko-demo.json get /exchange_rates
This endpoint allows you to **query BTC exchange rates with other currencies**
* You may use this endpoint to convert the response data, which is originally in BTC, to other currencies.
</Tip>
* Cache / Update Frequency: every 5 minutes for all the API plans.
</Note>
---
## Exchange Data by ID
**URL:** llms-txt#exchange-data-by-id
Source: https://docs.coingecko.com/v3.0.1/reference/exchanges-id
v3.0.1/reference/api-reference/coingecko-demo.json get /exchanges/{id}
This endpoint allows you to **query exchange's data (name, year established, country, ...), exchange volume in BTC and top 100 tickers based on exchange's ID**
<Warning>
### Notice
* Please note that the `trade_volume_24h_btc_normalized` data field will no longer be supported by our API starting on June 15, 2025. Please refer to [changelog](/changelog#may-2025) for more details.
</Warning>
* The exchange volume in the response is provided in BTC. To convert it to other currencies, please use [/exchange\_rates](/v3.0.1/reference/exchange-rates) endpoint.
* For derivatives (e.g. bitmex, binance\_futures), to get derivatives exchanges data, please go to [/derivatives/exchange/\{id}](/v3.0.1/reference/derivatives-exchanges-id) endpoint.
* Tickers are limited to 100 items, to get more tickers, please go to [/exchanges/\{id}/tickers](/v3.0.1/reference/exchanges-id-tickers) endpoint.
* When `dex_pair_format=symbol`, the DEX pair `base` and `target` are displayed in symbol format (e.g. `WETH`, `USDC`) instead of as contract addresses.
* Cache / Update Frequency: every 60 seconds for all the API plans.
</Note>
---
## Derivatives Exchanges List (ID Map)
**URL:** llms-txt#derivatives-exchanges-list-(id-map)
Source: https://docs.coingecko.com/v3.0.1/reference/derivatives-exchanges-list
v3.0.1/reference/api-reference/coingecko-demo.json get /derivatives/exchanges/list
This endpoint allows you to **query all the derivatives exchanges with ID and name on CoinGecko**
* You may use this endpoint to query the list of exchanges for other endpoints that contain params like `id` (derivatives exchange's ID)
</Tip>
* Cache / Update Frequency: every 5 minutes for all the API plans.
</Note>
---

View File

@ -0,0 +1,47 @@
# Coingecko Documentation Index
## Categories
### Authentication
**File:** `authentication.md`
**Pages:** 3
### Coins
**File:** `coins.md`
**Pages:** 65
### Contract
**File:** `contract.md`
**Pages:** 1
### Exchanges
**File:** `exchanges.md`
**Pages:** 14
### Introduction
**File:** `introduction.md`
**Pages:** 4
### Market Data
**File:** `market_data.md`
**Pages:** 3
### Nfts
**File:** `nfts.md`
**Pages:** 2
### Other
**File:** `other.md`
**Pages:** 16
### Pricing
**File:** `pricing.md`
**Pages:** 1
### Reference
**File:** `reference.md`
**Pages:** 9
### Trending
**File:** `trending.md`
**Pages:** 2

View File

@ -0,0 +1,392 @@
# Coingecko - Introduction
**Pages:** 4
---
## 🔥 Getting Started
**URL:** llms-txt#🔥-getting-started
**Contents:**
- Which MCP Server Should You Use?
- 🔗 Endpoint Options
- Primary Endpoint (HTTP Streaming)
- Alternative Endpoint (SSE — Server-Sent Events)
- Remote Server (Public, Keyless)
- Remote Server (Authenticated)
- Step 1: Add the configuration
- Step 2: Authorize your MCP access
- Local Server (API Key Required)
Connecting your AI to CoinGecko is simple. We offer several MCP server options to fit your needs, from keyless access for testing to authenticated connections for production applications.
Most MCP-compatible clients, like Claude Desktop, Gemini CLI, and Cursor, can be configured using a simple JSON file (e.g., `claude_desktop_config.json`)
<Note>
### Prerequisites
* Make sure your device has `node` installed. You can download it from [nodejs.org/download](https://nodejs.org/en/download)
</Note>
## Which MCP Server Should You Use?
Here's a breakdown of the available options to help you choose the right one:
| MCP Server Type | Best For | Endpoints | Status | Setup Details |
| ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------- | ----------- | ----------------------------------------------------------------------------- |
| Remote Server (Public, Keyless) | - First-time users, quick tests, and basic queries<br />- Connect instantly without any registration<br />- Subject to shared rate limits, not for heavy use | Primary: `/mcp`<br />Alternative: `/sse` | Public Beta | [mcp.api.coingecko.com](https://mcp.api.coingecko.com/) |
| Remote Server (Authenticated) | - Scalable apps, AI agent integrations<br />- Unlocks 76+ tools available under your Demo/Pro plan<br />- Higher, reliable rate limits with 24/7 uptime. Get your API key [here](https://www.coingecko.com/en/api/pricing) | Primary: `/mcp`<br />Alternative: `/sse` | Public Beta | [mcp.pro-api.coingecko.com](https://mcp.pro-api.coingecko.com/) |
| Local Server | - Ideal for local development, desktop AI apps<br />- Build/test your AI app even without an active internet connection<br />- Demo/Pro API key to access more tools. Get your API key [here](https://www.coingecko.com/en/api/pricing) | Local server instance | Beta | [npmjs/coingecko-mcp](https://www.npmjs.com/package/@coingecko/coingecko-mcp) |
## 🔗 Endpoint Options
Each remote server offers two connection methods to ensure compatibility with various MCP clients:
### Primary Endpoint (HTTP Streaming)
* **Public Server**: `https://mcp.api.coingecko.com/mcp`
* **Pro Server**: `https://mcp.pro-api.coingecko.com/mcp`
* Uses HTTP streaming protocol for real-time data transfer.
* Recommended for most modern MCP clients.
### Alternative Endpoint (SSE — Server-Sent Events)
* **Public Server**: `https://mcp.api.coingecko.com/sse`
* **Pro Server**: `https://mcp.pro-api.coingecko.com/sse`
* Uses Server-Sent Events for compatibility.
* Use this if you encounter connection issues with the primary endpoint.
<Note>
Most clients work with either endpoint. The configuration examples below use the SSE endpoint by default for maximum compatibility.
</Note>
## Remote Server (Public, Keyless)
The easiest way to get started. Just add the following to your client's `mcp_config.json` file.
<Note>
### Client-Specific Config
The file name and location depend on your client. Find your config file here: [modelcontextprotocol.io/quickstart](https://modelcontextprotocol.io/quickstart/user#2-add-the-filesystem-mcp-server)
</Note>
Add the following configuration to your `mcp_config.json`:
<CodeGroup>
</CodeGroup>
Here's a quick 2-minute tutorial for setting up the public server with Claude Desktop:
<iframe className="w-full aspect-video rounded-xl" src="https://www.youtube.com/embed/PDYJvtKok0E" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowFullScreen />
## Remote Server (Authenticated)
To access more tools and higher rate limits, use your CoinGecko API key with our hosted "Bring Your Own Key" (BYOK) server. Get your API key [here](https://www.coingecko.com/en/api/pricing)
### Step 1: Add the configuration
Add the following configuration to your `mcp_config.json`:
<CodeGroup>
</CodeGroup>
### Step 2: Authorize your MCP access
After adding the config, the first time your client tries to use the CoinGecko MCP, a new browser tab will open, redirecting you to our authentication page:
<img src="https://mintcdn.com/coingecko/b3Fla9Sm0TsVrJN4/images/reference/0fd54e7-image.png?fit=max&auto=format&n=b3Fla9Sm0TsVrJN4&q=85&s=c40d3876ad3b12c0c3177231e8642bf7" alt="" data-og-width="1627" width="1627" data-og-height="1611" height="1611" data-path="images/reference/0fd54e7-image.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/coingecko/b3Fla9Sm0TsVrJN4/images/reference/0fd54e7-image.png?w=280&fit=max&auto=format&n=b3Fla9Sm0TsVrJN4&q=85&s=b44038862f84320e55096acf29d704ab 280w, https://mintcdn.com/coingecko/b3Fla9Sm0TsVrJN4/images/reference/0fd54e7-image.png?w=560&fit=max&auto=format&n=b3Fla9Sm0TsVrJN4&q=85&s=d7518c452993e3c2191de720716fc28a 560w, https://mintcdn.com/coingecko/b3Fla9Sm0TsVrJN4/images/reference/0fd54e7-image.png?w=840&fit=max&auto=format&n=b3Fla9Sm0TsVrJN4&q=85&s=f4e361fa7c96759e52cf23b245e44bfc 840w, https://mintcdn.com/coingecko/b3Fla9Sm0TsVrJN4/images/reference/0fd54e7-image.png?w=1100&fit=max&auto=format&n=b3Fla9Sm0TsVrJN4&q=85&s=41d3e848470a50259a8aabd2f11f879d 1100w, https://mintcdn.com/coingecko/b3Fla9Sm0TsVrJN4/images/reference/0fd54e7-image.png?w=1650&fit=max&auto=format&n=b3Fla9Sm0TsVrJN4&q=85&s=4767ab92447bc5ba7a7f1ed2994945ea 1650w, https://mintcdn.com/coingecko/b3Fla9Sm0TsVrJN4/images/reference/0fd54e7-image.png?w=2500&fit=max&auto=format&n=b3Fla9Sm0TsVrJN4&q=85&s=686d5177b5697a4561eae0f10f157694 2500w" />
* Simply paste in your CoinGecko API key, and authorize to link your key to the MCP session.
✨ Don't have an API key yet? Upgrade to Pro today! Read more [here](https://www.coingecko.com/en/api/pricing).
* You can also toggle between dynamic/static tools here. Learn more about [Dynamic Tools](#dynamic-vs-static-tools).
## Local Server (API Key Required)
For local development and maximum control, run the MCP server directly on your machine. This method offers the rate limits based on your API plan.
<CodeGroup>
</CodeGroup>
✨ Don't have an API key yet? Get your free Demo key or upgrade to Pro! Read more [here](https://www.coingecko.com/en/api/pricing).
* Configure the `env` based on your API key tier:
* Pro API access:
<CodeGroup>
</CodeGroup>
* Demo API access:
<CodeGroup>
</CodeGroup>
**Examples:**
Example 1 (unknown):
```unknown
</CodeGroup>
Here's a quick 2-minute tutorial for setting up the public server with Claude Desktop:
<iframe className="w-full aspect-video rounded-xl" src="https://www.youtube.com/embed/PDYJvtKok0E" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowFullScreen />
## Remote Server (Authenticated)
To access more tools and higher rate limits, use your CoinGecko API key with our hosted "Bring Your Own Key" (BYOK) server. Get your API key [here](https://www.coingecko.com/en/api/pricing)
### Step 1: Add the configuration
Add the following configuration to your `mcp_config.json`:
<CodeGroup>
```
Example 2 (unknown):
```unknown
</CodeGroup>
### Step 2: Authorize your MCP access
After adding the config, the first time your client tries to use the CoinGecko MCP, a new browser tab will open, redirecting you to our authentication page:
<img src="https://mintcdn.com/coingecko/b3Fla9Sm0TsVrJN4/images/reference/0fd54e7-image.png?fit=max&auto=format&n=b3Fla9Sm0TsVrJN4&q=85&s=c40d3876ad3b12c0c3177231e8642bf7" alt="" data-og-width="1627" width="1627" data-og-height="1611" height="1611" data-path="images/reference/0fd54e7-image.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/coingecko/b3Fla9Sm0TsVrJN4/images/reference/0fd54e7-image.png?w=280&fit=max&auto=format&n=b3Fla9Sm0TsVrJN4&q=85&s=b44038862f84320e55096acf29d704ab 280w, https://mintcdn.com/coingecko/b3Fla9Sm0TsVrJN4/images/reference/0fd54e7-image.png?w=560&fit=max&auto=format&n=b3Fla9Sm0TsVrJN4&q=85&s=d7518c452993e3c2191de720716fc28a 560w, https://mintcdn.com/coingecko/b3Fla9Sm0TsVrJN4/images/reference/0fd54e7-image.png?w=840&fit=max&auto=format&n=b3Fla9Sm0TsVrJN4&q=85&s=f4e361fa7c96759e52cf23b245e44bfc 840w, https://mintcdn.com/coingecko/b3Fla9Sm0TsVrJN4/images/reference/0fd54e7-image.png?w=1100&fit=max&auto=format&n=b3Fla9Sm0TsVrJN4&q=85&s=41d3e848470a50259a8aabd2f11f879d 1100w, https://mintcdn.com/coingecko/b3Fla9Sm0TsVrJN4/images/reference/0fd54e7-image.png?w=1650&fit=max&auto=format&n=b3Fla9Sm0TsVrJN4&q=85&s=4767ab92447bc5ba7a7f1ed2994945ea 1650w, https://mintcdn.com/coingecko/b3Fla9Sm0TsVrJN4/images/reference/0fd54e7-image.png?w=2500&fit=max&auto=format&n=b3Fla9Sm0TsVrJN4&q=85&s=686d5177b5697a4561eae0f10f157694 2500w" />
* Simply paste in your CoinGecko API key, and authorize to link your key to the MCP session.
✨ Don't have an API key yet? Upgrade to Pro today! Read more [here](https://www.coingecko.com/en/api/pricing).
* You can also toggle between dynamic/static tools here. Learn more about [Dynamic Tools](#dynamic-vs-static-tools).
## Local Server (API Key Required)
For local development and maximum control, run the MCP server directly on your machine. This method offers the rate limits based on your API plan.
<CodeGroup>
```
Example 3 (unknown):
```unknown
</CodeGroup>
✨ Don't have an API key yet? Get your free Demo key or upgrade to Pro! Read more [here](https://www.coingecko.com/en/api/pricing).
* Configure the `env` based on your API key tier:
* Pro API access:
<CodeGroup>
```
Example 4 (unknown):
```unknown
</CodeGroup>
* Demo API access:
<CodeGroup>
```
---
## Endpoint Overview
**URL:** llms-txt#endpoint-overview
**Contents:**
- CoinGecko Endpoints: Coins
- CoinGecko Endpoints: NFT
- CoinGecko Endpoints: Exchanges & Derivatives
- CoinGecko Endpoints: Public Treasuries
- CoinGecko Endpoints: General
- Onchain DEX Endpoints (GeckoTerminal)
Source: https://docs.coingecko.com/v3.0.1/reference/endpoint-overview
Any exclusive endpoints for Pro-API users (any paid plan subscribers) will not be included here.
For a full list of endpoints, please visit [Pro API Documentation](/reference/endpoint-overview) instead.
</Note>
## CoinGecko Endpoints: Coins
| Endpoint | Description |
| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [/ping](/v3.0.1/reference/ping-server) | Check the API server status |
| [/simple/price](/v3.0.1/reference/simple-price) | Query the prices of one or more coins by using their unique Coin API IDs |
| [/simple/token\_price/\{id}](/v3.0.1/reference/simple-token-price) | Query the prices of one or more coins by using their unique Coin API IDs |
| [/simple/supported\_vs\_currencies](/v3.0.1/reference/simple-supported-currencies) | Query all the supported currencies on CoinGecko |
| [/coins/list](/v3.0.1/reference/coins-list) | Query all the supported coins on CoinGecko with coins ID, name and symbol |
| [/coins/markets](/v3.0.1/reference/coins-markets) | Query all the supported coins with price, market cap, volume and market related data |
| [/coins/\{id}](/v3.0.1/reference/coins-id) | Query all the metadata (image, websites, socials, description, contract address, etc.) from the CoinGecko coin page based on a particular coin ID |
| [/coins/\{id}/tickers](/v3.0.1/reference/coins-id-tickers) | Query the coin tickers on both centralized exchange (CEX) and decentralized exchange (DEX) based on a particular coin ID |
| [/coins/\{id}/history](/v3.0.1/reference/coins-id-history) | Query the historical data (price, market cap, 24hr volume, ...) at a given date for a coin based on a particular coin ID |
| [/coins/\{id}/market\_chart](/v3.0.1/reference/coins-id-market-chart) | Get the historical chart data of a coin including time in UNIX, price, market cap and 24hr volume based on particular coin ID |
| [/coins/\{id}/market\_chart/range](/v3.0.1/reference/coins-id-market-chart-range) | Get the historical chart data of a coin within certain time range in UNIX along with price, market cap and 24hr volume based on particular coin ID |
| [/coins-id-ohlc](/v3.0.1/reference/coins-id-ohlc) | Get the OHLC chart (Open, High, Low, Close) of a coin based on particular coin ID |
| [/coins/../contract/..](/v3.0.1/reference/coins-contract-address) | Query all the metadata (image, websites, socials, description, contract address, etc.) from the CoinGecko coin page based on an asset platform and a particular token contract address |
| [/coins/../contract/../market\_chart](/v3.0.1/reference/contract-address-market-chart) | Get the historical chart data including time in UNIX, price, market cap and 24hr volume based on asset platform and particular token contract address |
| [/coins/../contract/../market\_chart/range](/v3.0.1/reference/contract-address-market-chart-range) | Get the historical chart data within certain time range in UNIX along with price, market cap and 24hr volume based on asset platform and particular token contract address |
| [/coins/categories/list](/v3.0.1/reference/coins-categories-list) | Query all the coins categories on CoinGecko |
| [/coins/categories](/v3.0.1/reference/coins-categories) | Query all the coins categories with market data (market cap, volume, ...) on CoinGecko |
## CoinGecko Endpoints: NFT
| Endpoint | Description |
| --------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| [/nfts/list](/v3.0.1/reference/nfts-list) | Query all supported NFTs with ID, contract address, name, asset platform ID and symbol on CoinGecko |
| [/nfts/..](/v3.0.1/reference/nfts-id) | Query all the NFT data (name, floor price, 24hr volume, ...) based on the NFT collection ID |
| [/nfts/../contract/..](/v3.0.1/reference/nfts-contract-address) | Query all the NFT data (name, floor price, 24hr volume, ...) based on the NFT collection contract address and respective asset platform |
## CoinGecko Endpoints: Exchanges & Derivatives
| Endpoint | Description |
| ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| [/exchanges](/v3.0.1/reference/exchanges) | Query all the supported exchanges with exchanges' data (ID, name, country, ...) that have active trading volumes on CoinGecko |
| [/exchanges/list](/v3.0.1/reference/exchanges-list) | Query all the exchanges with ID and name |
| [/exchanges/\{id}](/v3.0.1/reference/exchanges-id) | Query exchange's data (name, year established, country, ...), exchange volume in BTC and tickers based on exchange's ID |
| [/exchanges/\{id}/tickers](/v3.0.1/reference/exchanges-id-tickers) | Query exchange's tickers based on exchange's ID |
| [/exchanges/\{id}/volume\_chart](/v3.0.1/reference/exchanges-id-volume-chart) | Query the historical volume chart data with time in UNIX and trading volume data in BTC based on exchange's ID |
| [/derivatives](/v3.0.1/reference/derivatives-tickers) | Query all the tickers from derivatives exchanges on CoinGecko |
| [/derivatives/exchanges](/v3.0.1/reference/derivatives-exchanges) | Query all the derivatives exchanges with related data (ID, name, open interest, ...) on CoinGecko |
| [/derivatives/exchanges/\{id}](/v3.0.1/reference/derivatives-exchanges-id) | Query the derivatives exchange's related data (ID, name, open interest, ...) based on the exchanges' ID |
| [/derivatives/exchanges/list](/v3.0.1/reference/derivatives-exchanges-list) | Query all the derivatives exchanges with ID and name on CoinGecko |
## CoinGecko Endpoints: Public Treasuries
| Endpoint | Description |
| ------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
| [/\{entity}/public\_treasury/\{coin\_id}](/reference/companies-public-treasury) | Query public companies & governments' cryptocurrency holdings by coin ID |
| [/public\_treasury/\{entity\_id}](/reference/public-treasury-entity) | Query public companies & governments' cryptocurrency holdings by entity ID |
| [/entities/list](/reference/entities-list) | Query all the supported entities on CoinGecko with entities ID, name, symbol, and country |
## CoinGecko Endpoints: General
| Endpoint | Description |
| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ |
| [/exchange\_rates](/v3.0.1/reference/exchange-rates) | Query BTC exchange rates with other currencies |
| [/asset\_platforms](/v3.0.1/reference/asset-platforms-list) | Query all the asset platforms (blockchain networks) on CoinGecko |
| [/token\_lists/\{asset\_platform\_id}/all.json](/v3.0.1/reference/token-lists) | Get full list of tokens of a blockchain network (asset platform) that is supported by Ethereum token list standard |
| [/search](/v3.0.1/reference/search-data) | Search for coins, categories and markets listed on CoinGecko |
| [/search/trending](/v3.0.1/reference/trending-search) | Query trending search coins, NFTs and categories on CoinGecko in the last 24 hours |
| [/global](/v3.0.1/reference/crypto-global) | Query cryptocurrency global data including active cryptocurrencies, markets, total crypto market cap and etc. |
| [/global/decentralized\_finance\_defi](/v3.0.1/reference/global-defi) | Query cryptocurrency global decentralized finance (DeFi) data including DeFi market cap, trading volume |
## Onchain DEX Endpoints (GeckoTerminal)
| Endpoint | Description |
| ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [/onchain/simple/networks/../token\_price/..](/v3.0.1/reference/onchain-simple-price) | Get token price based on the provided token contract address on a network |
| [/onchain/networks](/v3.0.1/reference/networks-list) | Query all the supported networks on GeckoTerminal |
| [/onchain/networks/../dexes](/v3.0.1/reference/dexes-list) | Query all the supported decentralized exchanges (DEXs) based on the provided network on GeckoTerminal |
| [/onchain/networks/trending\_pools](/v3.0.1/reference/trending-pools-list) | Query all the trending pools across all networks on GeckoTerminal |
| [/onchain/networks/../trending\_pools](/v3.0.1/reference/trending-pools-network) | Query the trending pools based on the provided network |
| [/onchain/networks/../pools/..](/v3.0.1/reference/pool-address) | Query the specific pool based on the provided network and pool address |
| [/onchain/networks/../pools/multi/..](/v3.0.1/reference/pools-addresses) | Query multiple pools based on the provided network and pool address |
| [/onchain/networks/../pools](/v3.0.1/reference/top-pools-network) | Query all the top pools based on the provided network |
| [/onchain/networks/../dexes/../pools](/v3.0.1/reference/top-pools-dex) | Query all the top pools based on the provided network and decentralized exchange (DEX) |
| [/onchain/networks/../new\_pools](/v3.0.1/reference/latest-pools-network) | Query all the latest pools based on provided network |
| [/onchain/networks/new\_pools](/v3.0.1/reference/latest-pools-list) | Query all the latest pools across all networks on GeckoTerminal |
| [/onchain/search/pools](/v3.0.1/reference/search-pools) | Search for pools on a network |
| [/onchain/networks/../tokens/../pools](/v3.0.1/reference/top-pools-contract-address) | Query top pools based on the provided token contract address on a network |
| [/onchain/networks/../tokens/..](/v3.0.1/reference/token-data-contract-address) | Query specific token data based on the provided token contract address on a network |
| [/onchain/networks/../tokens/multi/..](/v3.0.1/reference/tokens-data-contract-addresses) | Query multiple tokens data based on the provided token contract addresses on a network |
| [/onchain/networks/../tokens/../info](/v3.0.1/reference/token-info-contract-address) | Query token metadata (name, symbol, CoinGecko ID, image, socials, websites, description, etc.) based on a provided token contract address on a network |
| [/onchain/networks/../pools/../info](/v3.0.1/reference/pool-token-info-contract-address) | Query pool metadata (base and quote token details, image, socials, websites, description, contract address, etc.) based on a provided pool contract address on a network |
| [/onchain/tokens/info\_recently\_updated](/v3.0.1/reference/tokens-info-recent-updated) | Query 100 most recently updated tokens info across all networks on GeckoTerminal |
| [/onchain/networks/../pools/../ohlcv/..](/v3.0.1/reference/pool-ohlcv-contract-address) | Get the OHLCV chart (Open, High, Low, Close, Volume) of a pool based on the provided pool address on a network |
| [/onchain/networks/../pools/../trades](/v3.0.1/reference/pool-trades-contract-address) | Query the last 300 trades in the past 24 hours based on the provided pool address |
⚡️ Need Real-time Data Streams? Try [WebSocket API](https://docs.coingecko.com/websocket)
<a href="/websocket">
<Frame>
<img src="https://mintcdn.com/coingecko/VlaOc2UnIs8mj72v/images/wss-banner-2.png?fit=max&auto=format&n=VlaOc2UnIs8mj72v&q=85&s=2c88f667113256b6285720c468fb53a1" noZoom data-og-width="2400" width="2400" data-og-height="470" height="470" data-path="images/wss-banner-2.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/coingecko/VlaOc2UnIs8mj72v/images/wss-banner-2.png?w=280&fit=max&auto=format&n=VlaOc2UnIs8mj72v&q=85&s=d2eafb93fcd670d5df221d617fd6f6a7 280w, https://mintcdn.com/coingecko/VlaOc2UnIs8mj72v/images/wss-banner-2.png?w=560&fit=max&auto=format&n=VlaOc2UnIs8mj72v&q=85&s=24f635622a42c0ae03695cc940112699 560w, https://mintcdn.com/coingecko/VlaOc2UnIs8mj72v/images/wss-banner-2.png?w=840&fit=max&auto=format&n=VlaOc2UnIs8mj72v&q=85&s=82ef1c05b6f45d6d8ec0bcef0f19d49a 840w, https://mintcdn.com/coingecko/VlaOc2UnIs8mj72v/images/wss-banner-2.png?w=1100&fit=max&auto=format&n=VlaOc2UnIs8mj72v&q=85&s=b119e8746bb1a78b759e6d94d96b7c8b 1100w, https://mintcdn.com/coingecko/VlaOc2UnIs8mj72v/images/wss-banner-2.png?w=1650&fit=max&auto=format&n=VlaOc2UnIs8mj72v&q=85&s=95797e7366c7f280e3e4b570b6db2b49 1650w, https://mintcdn.com/coingecko/VlaOc2UnIs8mj72v/images/wss-banner-2.png?w=2500&fit=max&auto=format&n=VlaOc2UnIs8mj72v&q=85&s=2f120e8a31b5793213494d4ae2d46fb3 2500w" />
</Frame>
</a>
With WebSocket, you can now stream ultra-low latency, real-time prices, trades, and OHLCV chart data. <br />
Subscribe to our [paid API plan](https://www.coingecko.com/en/api/pricing) (Analyst plan & above) to access WebSocket and REST API data delivery methods.
---
## Introduction
**URL:** llms-txt#introduction
Source: https://docs.coingecko.com/index
Started in 2014, CoinGecko is the world's largest independent crypto data aggregator that is integrated with more than 1,000 crypto exchanges and lists more than 18,000 coins across 600+ categories. CoinGecko API offers the most comprehensive and reliable crypto market data through RESTful JSON endpoints.
CoinGecko API now serves **onchain DEX data** across 250+ blockchain networks, 1,700+ decentralized exchanges (DEXes), and 15M+ tokens, powered by GeckoTerminal.
Thousands of forward-thinking projects, Web3 developers, researchers, institutions, and enterprises use our API to obtain **price feeds, market data, metadata, and historical data of crypto assets, NFTs, and exchanges**.
Here are some of the **common use cases** for clients who use CoinGecko API:
* Crypto Exchanges (CEX, DEX), Trading Apps
* Wallets (Hot, Cold)
* Data Aggregator, Crypto Screener, Analytics Dashboard
* AI Agents, DeFAI Apps
* Block Explorer, Portfolio Tracker
* DeFi Protocols, NFT Marketplaces, Digital Bank
* Backtesting Trading Strategy
* Accounting, Tax, Audit, HR Payroll
* Research & Analysis: Media, Institution, Academic, VC, Financial
* Oracles, Bots, Payments, E-commerce
🔥 New: [WebSocket API](https://docs.coingecko.com/websocket)
<a href="/websocket">
<Frame>
<img src="https://mintcdn.com/coingecko/VlaOc2UnIs8mj72v/images/wss-banner-1.png?fit=max&auto=format&n=VlaOc2UnIs8mj72v&q=85&s=bd74fb20a26084018272eb6b63010804" noZoom data-og-width="2400" width="2400" data-og-height="470" height="470" data-path="images/wss-banner-1.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/coingecko/VlaOc2UnIs8mj72v/images/wss-banner-1.png?w=280&fit=max&auto=format&n=VlaOc2UnIs8mj72v&q=85&s=bc17e03ee25137fbcc1eaac0733e6781 280w, https://mintcdn.com/coingecko/VlaOc2UnIs8mj72v/images/wss-banner-1.png?w=560&fit=max&auto=format&n=VlaOc2UnIs8mj72v&q=85&s=d8439f50c69e11ba595b6c07d97eb65c 560w, https://mintcdn.com/coingecko/VlaOc2UnIs8mj72v/images/wss-banner-1.png?w=840&fit=max&auto=format&n=VlaOc2UnIs8mj72v&q=85&s=8c232633716268ced5b171e3e38acbf5 840w, https://mintcdn.com/coingecko/VlaOc2UnIs8mj72v/images/wss-banner-1.png?w=1100&fit=max&auto=format&n=VlaOc2UnIs8mj72v&q=85&s=3ac0be8afcc3e9fba5b4c4a961c5cda7 1100w, https://mintcdn.com/coingecko/VlaOc2UnIs8mj72v/images/wss-banner-1.png?w=1650&fit=max&auto=format&n=VlaOc2UnIs8mj72v&q=85&s=b8e71e426137d6f26642360aa8f1c347 1650w, https://mintcdn.com/coingecko/VlaOc2UnIs8mj72v/images/wss-banner-1.png?w=2500&fit=max&auto=format&n=VlaOc2UnIs8mj72v&q=85&s=eb7699818b518264b9c3c65c5ec5a633 2500w" />
</Frame>
</a>
With WebSocket, you can now stream ultra-low latency, real-time prices, trades, and OHLCV chart data. <br />
Subscribe to our [paid API plan](https://www.coingecko.com/en/api/pricing) (Analyst plan & above) to access WebSocket and REST API data delivery methods.
<Columns cols={2}>
<Card title="Setting Up Your API Key" icon="key" href="/docs/setting-up-your-api-key">
Start by creating your CoinGecko API key
</Card>
<Card title="Building with AI" icon="robot" href="/docs/building-with-ai">
Bring CoinGecko data to your AI apps
</Card>
</Columns>
export const FooterFix = () => {
React.useEffect(() => {
const paginationElement = document.getElementById('pagination');
if (paginationElement) paginationElement.remove();
const footerElement = document.getElementById('footer');
if (footerElement) footerElement.style.marginTop = '-40px';
const feedbackToolbarClass = document.querySelector('.feedback-toolbar');
if (feedbackToolbarClass) feedbackToolbarClass.style.paddingBottom = '0px';
}, []);
---
## 📕 Overview
**URL:** llms-txt#📕-overview
The official CoinGecko MCP Server is now live, making CoinGecko data readily available to your AI models and applications. With the CoinGecko MCP, you can empower your agents to:
* **Access real-time market data**: Get aggregated prices, market cap, and trading volume for over 15k+ coins on CoinGecko, integrated across 1,000+ exchanges.
* **Dive into onchain analytics**: Query onchain DEX price and liquidity data for more than 8M tokens across 200+ networks via GeckoTerminal.
* **Discover market trends**: Instantly find trending coins, new token listings, top gainers/losers, and popular NFT collections.
* **Retrieve rich metadata**: Pull essential details like project descriptions, logos, social links, contract addresses, security info, and more.
* **Analyze historical performance**: Access historical price, market data, and OHLCV for any cryptocurrency.
* **Explore crypto categories**: Effortlessly list coins within specific sectors like Meme, DeFi, Layer 1, AI agent, and more.
<Frame caption="MCP Demo with Claude Desktop">
<img src="https://mintcdn.com/coingecko/b3Fla9Sm0TsVrJN4/images/reference/8c45171-image.png?fit=max&auto=format&n=b3Fla9Sm0TsVrJN4&q=85&s=a17e15d1b672940226da961086b986ed" data-og-width="2930" width="2930" data-og-height="1882" height="1882" data-path="images/reference/8c45171-image.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/coingecko/b3Fla9Sm0TsVrJN4/images/reference/8c45171-image.png?w=280&fit=max&auto=format&n=b3Fla9Sm0TsVrJN4&q=85&s=c026d75329f72ee001fafea1c6d35659 280w, https://mintcdn.com/coingecko/b3Fla9Sm0TsVrJN4/images/reference/8c45171-image.png?w=560&fit=max&auto=format&n=b3Fla9Sm0TsVrJN4&q=85&s=e90eb94aa0cd98f9409042706e598703 560w, https://mintcdn.com/coingecko/b3Fla9Sm0TsVrJN4/images/reference/8c45171-image.png?w=840&fit=max&auto=format&n=b3Fla9Sm0TsVrJN4&q=85&s=fd02d8b78f1e6b325e29b59795d1f84f 840w, https://mintcdn.com/coingecko/b3Fla9Sm0TsVrJN4/images/reference/8c45171-image.png?w=1100&fit=max&auto=format&n=b3Fla9Sm0TsVrJN4&q=85&s=2ef4c5580ce4de3f5caae91b4c9be11d 1100w, https://mintcdn.com/coingecko/b3Fla9Sm0TsVrJN4/images/reference/8c45171-image.png?w=1650&fit=max&auto=format&n=b3Fla9Sm0TsVrJN4&q=85&s=c9efb0e238afbfe0a3d7bf54ede0c3c1 1650w, https://mintcdn.com/coingecko/b3Fla9Sm0TsVrJN4/images/reference/8c45171-image.png?w=2500&fit=max&auto=format&n=b3Fla9Sm0TsVrJN4&q=85&s=2b8f2e6b387cd3c9f9c229a31c1efe12 2500w" />
</Frame>
---

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,183 @@
# CoinGecko API
## Docs
- [Changelog](https://docs.coingecko.com/changelog.md): Product updates and announcements
- [1. Get data by ID or Address](https://docs.coingecko.com/docs/1-get-data-by-id-or-address.md)
- [10-mins Tutorial Guide](https://docs.coingecko.com/docs/10-mins-tutorial-guide.md): New to CoinGecko API? Fret not. Whether you're a programmer or someone with zero coding experience, we've got you covered!
- [2. Get Historical Data](https://docs.coingecko.com/docs/2-get-historical-data.md)
- [3. Get Exchanges & NFT Data](https://docs.coingecko.com/docs/3-get-exchanges-nft-data.md)
- [4. Get On-chain Data](https://docs.coingecko.com/docs/4-get-on-chain-data.md)
- [AI Prompts](https://docs.coingecko.com/docs/ai-prompts.md): CoinGecko API AI prompt library
- [API Status](https://docs.coingecko.com/docs/api-status.md): CoinGecko's API status page provides information on the current status and incident history of CoinGecko API (Public & Pro)
- [Best Practices](https://docs.coingecko.com/docs/best-practices.md): Wonder how to use different endpoints together? This is the perfect place for you
- [Building with AI](https://docs.coingecko.com/docs/building-with-ai.md): Quick tips to empower your AI applications with CoinGecko API, and leverage our AI capabilities to help you build better and easier.
- [Clients](https://docs.coingecko.com/docs/clients.md): Explore client resources, including official Swagger JSON and unofficial Python wrapper
- [Common Errors & Rate Limit](https://docs.coingecko.com/docs/common-errors-rate-limit.md)
- [Common Use Cases](https://docs.coingecko.com/docs/common-use-cases.md): Discover the common use cases of CoinGecko API by our users
- [Endpoint Showcase](https://docs.coingecko.com/docs/endpoint-showcase.md): Discover how CoinGecko API is used at CoinGecko.com and GeckoTerminal.com
- [CoinGecko MCP Server (Beta)](https://docs.coingecko.com/docs/mcp-server.md): MCP Server for Crypto Price & Market Data. MCP (Model Context Protocol) is an open standard that allows Large Language Model (LLM) and other AI agents to securely and intelligently interact with external data sources and tools.
- [Python AI Prompts](https://docs.coingecko.com/docs/python-ai-prompts.md): A comprehensive AI prompt to guide coding assistants in correctly implementing the official CoinGecko Python SDK for reliable API integration.
- [CoinGecko SDK (Beta)](https://docs.coingecko.com/docs/sdk.md): Official CoinGecko Typescript and Python SDKs — Crypto Price & Market Data API
- [Setting Up Your API Key](https://docs.coingecko.com/docs/setting-up-your-api-key.md)
- [Tutorials (Beginner-friendly)](https://docs.coingecko.com/docs/tutorials-beginner-friendly.md): Using CoinGecko API is super easy, even if you have no programming experience!
- [TypeScript AI Prompts](https://docs.coingecko.com/docs/typescript-ai-prompts.md): A comprehensive AI prompt to guide coding assistants in correctly implementing the official CoinGecko TypeScript SDK.
- [Useful Links](https://docs.coingecko.com/docs/useful-links.md): Some of the useful links to help you navigate while using the CoinGecko API
- [Introduction](https://docs.coingecko.com/index.md)
- [💼 API Usage](https://docs.coingecko.com/reference/api-usage.md): This endpoint allows you to **monitor your account's API usage, including rate limits, monthly total credits, remaining credits, and more**
- [Asset Platforms List (ID Map)](https://docs.coingecko.com/reference/asset-platforms-list.md): This endpoint allows you to **query all the asset platforms on CoinGecko**
- [Authentication (Pro API)](https://docs.coingecko.com/reference/authentication.md): Authentication method for CoinGecko Pro API (Paid plan subscribers with Pro-API keys)
- [💼 Categories List](https://docs.coingecko.com/reference/categories-list.md): This endpoint allows you to **query all the supported categories on GeckoTerminal**
- [Coins Categories List with Market Data](https://docs.coingecko.com/reference/coins-categories.md): This endpoint allows you to **query all the coins categories with market data (market cap, volume, ...) on CoinGecko**
- [Coins Categories List (ID Map)](https://docs.coingecko.com/reference/coins-categories-list.md): This endpoint allows you to **query all the coins categories on CoinGecko**
- [Coin Data by Token Address](https://docs.coingecko.com/reference/coins-contract-address.md): This endpoint allows you to **query all the metadata (image, websites, socials, description, contract address, etc.) and market data (price, ATH, exchange tickers, etc.) of a coin from the CoinGecko coin page based on an asset platform and a particular token contract address**
- [Coin Data by ID](https://docs.coingecko.com/reference/coins-id.md): This endpoint allows you to **query all the metadata (image, websites, socials, description, contract address, etc.) and market data (price, ATH, exchange tickers, etc.) of a coin from the CoinGecko coin page based on a particular coin ID**
- [👑 Circulating Supply Chart by ID](https://docs.coingecko.com/reference/coins-id-circulating-supply-chart.md): This endpoint allows you to **query historical circulating supply of a coin by number of days away from now based on provided coin ID**
- [👑 Circulating Supply Chart within Time Range by ID](https://docs.coingecko.com/reference/coins-id-circulating-supply-chart-range.md): This endpoint allows you to **query historical circulating supply of a coin, within a range of timestamp based on the provided coin ID**
- [Coin Historical Data by ID](https://docs.coingecko.com/reference/coins-id-history.md): This endpoint allows you to **query the historical data (price, market cap, 24hrs volume, ...) at a given date for a coin based on a particular coin ID**
- [Coin Historical Chart Data by ID](https://docs.coingecko.com/reference/coins-id-market-chart.md): This endpoint allows you to **get the historical chart data of a coin including time in UNIX, price, market cap and 24hr volume based on particular coin ID**
- [Coin Historical Chart Data within Time Range by ID](https://docs.coingecko.com/reference/coins-id-market-chart-range.md): This endpoint allows you to **get the historical chart data of a coin within certain time range in UNIX along with price, market cap and 24hr volume based on particular coin ID**
- [Coin OHLC Chart by ID](https://docs.coingecko.com/reference/coins-id-ohlc.md): This endpoint allows you to **get the OHLC chart (Open, High, Low, Close) of a coin based on particular coin ID**
- [💼 Coin OHLC Chart within Time Range by ID](https://docs.coingecko.com/reference/coins-id-ohlc-range.md): This endpoint allows you to **get the OHLC chart (Open, High, Low, Close) of a coin within a range of timestamp based on particular coin ID**
- [Coin Tickers by ID](https://docs.coingecko.com/reference/coins-id-tickers.md): This endpoint allows you to **query the coin tickers on both centralized exchange (CEX) and decentralized exchange (DEX) based on a particular coin ID**
- [👑 Total Supply Chart by ID](https://docs.coingecko.com/reference/coins-id-total-supply-chart.md): This endpoint allows you to **query historical total supply of a coin by number of days away from now based on provided coin ID**
- [👑 Total Supply Chart within time range by ID](https://docs.coingecko.com/reference/coins-id-total-supply-chart-range.md): This endpoint allows you to **query historical total supply of a coin, within a range of timestamp based on the provided coin ID**
- [Coins List (ID Map)](https://docs.coingecko.com/reference/coins-list.md): This endpoint allows you to **query all the supported coins on CoinGecko with coins ID, name and symbol**
- [💼 Recently Added Coins](https://docs.coingecko.com/reference/coins-list-new.md): This endpoint allows you to **query the latest 200 coins that recently listed on CoinGecko**
- [Coins List with Market Data](https://docs.coingecko.com/reference/coins-markets.md): This endpoint allows you to **query all the supported coins with price, market cap, volume and market related data**
- [💼 Top Gainers & Losers](https://docs.coingecko.com/reference/coins-top-gainers-losers.md): This endpoint allows you to **query the top 30 coins with largest price gain and loss by a specific time duration**
- [Crypto Treasury Holdings by Coin ID](https://docs.coingecko.com/reference/companies-public-treasury.md): This endpoint allows you **query public companies & governments' cryptocurrency holdings** by Coin ID
- [Coin Historical Chart Data by Token Address](https://docs.coingecko.com/reference/contract-address-market-chart.md): This endpoint allows you to **get the historical chart data including time in UNIX, price, market cap and 24hr volume based on asset platform and particular token contract address**
- [Coin Historical Chart Data within Time Range by Token Address](https://docs.coingecko.com/reference/contract-address-market-chart-range.md): This endpoint allows you to **get the historical chart data within certain time range in UNIX along with price, market cap and 24hr volume based on asset platform and particular token contract address**
- [Crypto Global Market Data](https://docs.coingecko.com/reference/crypto-global.md): This endpoint allows you **query cryptocurrency global data including active cryptocurrencies, markets, total crypto market cap and etc**
- [Derivatives Exchanges List with Data](https://docs.coingecko.com/reference/derivatives-exchanges.md): This endpoint allows you to **query all the derivatives exchanges with related data (ID, name, open interest, ...) on CoinGecko**
- [Derivatives Exchange Data by ID](https://docs.coingecko.com/reference/derivatives-exchanges-id.md): This endpoint allows you to **query the derivatives exchange's related data (ID, name, open interest, ...) based on the exchanges' ID**
- [Derivatives Exchanges List (ID Map)](https://docs.coingecko.com/reference/derivatives-exchanges-list.md): This endpoint allows you to **query all the derivatives exchanges with ID and name on CoinGecko**
- [Derivatives Tickers List](https://docs.coingecko.com/reference/derivatives-tickers.md): This endpoint allows you to **query all the tickers from derivatives exchanges on CoinGecko**
- [Supported Dexes List by Network (ID Map)](https://docs.coingecko.com/reference/dexes-list.md): This endpoint allows you to **query all the supported decentralized exchanges (DEXs) based on the provided network on GeckoTerminal**
- [Endpoint Overview](https://docs.coingecko.com/reference/endpoint-overview.md)
- [Entities List (ID Map)](https://docs.coingecko.com/reference/entities-list.md): This endpoint allows you to **query all the supported entities on CoinGecko with entities ID, name, symbol, and country**
- [BTC-to-Currency Exchange Rates](https://docs.coingecko.com/reference/exchange-rates.md): This endpoint allows you to **query BTC exchange rates with other currencies**
- [Exchanges List with data](https://docs.coingecko.com/reference/exchanges.md): This endpoint allows you to **query all the supported exchanges with exchanges' data (ID, name, country, ...) that have active trading volumes on CoinGecko**
- [Exchange Data by ID](https://docs.coingecko.com/reference/exchanges-id.md): This endpoint allows you to **query exchange's data (name, year established, country, ...), exchange volume in BTC and top 100 tickers based on exchange's ID**
- [Exchange Tickers by ID](https://docs.coingecko.com/reference/exchanges-id-tickers.md): This endpoint allows you to **query exchange's tickers based on exchange's ID**
- [Exchange Volume Chart by ID](https://docs.coingecko.com/reference/exchanges-id-volume-chart.md): This endpoint allows you to **query the historical volume chart data with time in UNIX and trading volume data in BTC based on exchange's ID**
- [💼 Exchange Volume Chart within Time Range by ID](https://docs.coingecko.com/reference/exchanges-id-volume-chart-range.md): This endpoint allows you to **query the historical volume chart data in BTC by specifying date range in UNIX based on exchange's ID**
- [Exchanges List (ID Map)](https://docs.coingecko.com/reference/exchanges-list.md): This endpoint allows you to **query all the exchanges with ID and name**
- [Global DeFi Market Data](https://docs.coingecko.com/reference/global-defi.md): This endpoint allows you **query top 100 cryptocurrency global decentralized finance (DeFi) data including DeFi market cap, trading volume**
- [💼 Global Market Cap Chart Data](https://docs.coingecko.com/reference/global-market-cap-chart.md): This endpoint allows you to **query historical global market cap and volume data by number of days away from now**
- [New Pools List](https://docs.coingecko.com/reference/latest-pools-list.md): This endpoint allows you to **query all the latest pools across all networks on GeckoTerminal**
- [New Pools by Network](https://docs.coingecko.com/reference/latest-pools-network.md): This endpoint allows you to **query all the latest pools based on provided network**
- [Supported Networks List (ID Map)](https://docs.coingecko.com/reference/networks-list.md): This endpoint allows you to **query all the supported networks on GeckoTerminal**
- [NFTs Collection Data by Contract Address](https://docs.coingecko.com/reference/nfts-contract-address.md): This endpoint allows you to **query all the NFT data (name, floor price, 24hr volume ...) based on the NFT collection contract address and respective asset platform**
- [💼 NFTs Collection Historical Chart Data by Contract Address](https://docs.coingecko.com/reference/nfts-contract-address-market-chart.md): This endpoint allows you **query historical market data of a NFT collection, including floor price, market cap, and 24hr volume, by number of days away from now based on the provided contract address**
- [NFTs Collection Data by ID](https://docs.coingecko.com/reference/nfts-id.md): This endpoint allows you to **query all the NFT data (name, floor price, 24hr volume ...) based on the NFT collection ID**
- [💼 NFTs Collection Historical Chart Data by ID](https://docs.coingecko.com/reference/nfts-id-market-chart.md): This endpoint allows you **query historical market data of a NFT collection, including floor price, market cap, and 24hr volume, by number of days away from now**
- [💼 NFTs Collection Tickers by ID](https://docs.coingecko.com/reference/nfts-id-tickers.md): This endpoint allows you to **query the latest floor price and 24hr volume of a NFT collection, on each NFT marketplace, e.g. OpenSea and LooksRare**
- [NFTs List (ID Map)](https://docs.coingecko.com/reference/nfts-list.md): This endpoint allows you to **query all supported NFTs with ID, contract address, name, asset platform ID and symbol on CoinGecko**
- [💼 NFTs List with Market Data](https://docs.coingecko.com/reference/nfts-markets.md): This endpoint allows you to **query all the supported NFT collections with floor price, market cap, volume and market related data on CoinGecko**
- [Token Price by Token Addresses](https://docs.coingecko.com/reference/onchain-simple-price.md): This endpoint allows you to **get token price based on the provided token contract address on a network**
- [Check API server status](https://docs.coingecko.com/reference/ping-server.md): This endpoint allows you to **check the API server status**
- [Specific Pool Data by Pool Address](https://docs.coingecko.com/reference/pool-address.md): This endpoint allows you to **query the specific pool based on the provided network and pool address**
- [Pool OHLCV chart by Pool Address](https://docs.coingecko.com/reference/pool-ohlcv-contract-address.md): This endpoint allows you to **get the OHLCV chart (Open, High, Low, Close, Volume) of a pool based on the provided pool address on a network**
- [Pool Tokens Info by Pool Address](https://docs.coingecko.com/reference/pool-token-info-contract-address.md): This endpoint allows you to **query pool metadata (base and quote token details, image, socials, websites, description, contract address, etc.) based on a provided pool contract address on a network**
- [Past 24 Hour Trades by Pool Address](https://docs.coingecko.com/reference/pool-trades-contract-address.md): This endpoint allows you to **query the last 300 trades in the past 24 hours based on the provided pool address**
- [Multiple Pools Data by Pool Addresses](https://docs.coingecko.com/reference/pools-addresses.md): This endpoint allows you to **query multiple pools based on the provided network and pool address**
- [💼 Pools by Category ID](https://docs.coingecko.com/reference/pools-category.md): This endpoint allows you to **query all the pools based on the provided category ID**
- [🔥 Megafilter for Pools](https://docs.coingecko.com/reference/pools-megafilter.md): This endpoint allows you to **query pools based on various filters across all networks on GeckoTerminal**
- [Crypto Treasury Holdings by Entity ID](https://docs.coingecko.com/reference/public-treasury-entity.md): This endpoint allows you **query public companies & governments' cryptocurrency holdings** by Entity ID
- [Search Queries](https://docs.coingecko.com/reference/search-data.md): This endpoint allows you to **search for coins, categories and markets listed on CoinGecko**
- [Search Pools](https://docs.coingecko.com/reference/search-pools.md): This endpoint allows you to **search for pools on a network**
- [Coin Price by IDs](https://docs.coingecko.com/reference/simple-price.md): This endpoint allows you to **query the prices of one or more coins by using their unique Coin API IDs**
- [Supported Currencies List](https://docs.coingecko.com/reference/simple-supported-currencies.md): This endpoint allows you to **query all the supported currencies on CoinGecko**
- [Coin Price by Token Addresses](https://docs.coingecko.com/reference/simple-token-price.md): This endpoint allows you to **query one or more token prices using their token contract addresses**
- [Token Data by Token Address](https://docs.coingecko.com/reference/token-data-contract-address.md): This endpoint allows you to **query specific token data based on the provided token contract address on a network**
- [💼 Historical Token Holders Chart by Token Address](https://docs.coingecko.com/reference/token-holders-chart-token-address.md): This endpoint allows you to **get the historical token holders chart based on the provided token contract address on a network**
- [Token Info by Token Address](https://docs.coingecko.com/reference/token-info-contract-address.md): This endpoint allows you to **query token metadata (name, symbol, CoinGecko ID, image, socials, websites, description, etc.) based on a provided token contract address on a network**
- [Token Lists by Asset Platform ID](https://docs.coingecko.com/reference/token-lists.md): This endpoint allows you to **get full list of tokens of a blockchain network (asset platform) that is supported by [Ethereum token list standard](https://tokenlists.org/)**
- [💼 Token OHLCV chart by Token Address](https://docs.coingecko.com/reference/token-ohlcv-token-address.md): This endpoint allows you to **get the OHLCV chart (Open, High, Low, Close, Volume) of a token based on the provided token address on a network**
- [💼 Past 24 Hour Trades by Token Address](https://docs.coingecko.com/reference/token-trades-contract-address.md): This endpoint allows you to **query the last 300 trades in the past 24 hours, across all pools, based on the provided token contract address on a network**
- [Tokens Data by Token Addresses](https://docs.coingecko.com/reference/tokens-data-contract-addresses.md): This endpoint allows you to **query multiple tokens data based on the provided token contract addresses on a network**
- [Most Recently Updated Tokens List](https://docs.coingecko.com/reference/tokens-info-recent-updated.md): This endpoint allows you to **query 100 most recently updated tokens info of a specific network or across all networks on GeckoTerminal**
- [Top Pools by Token Address](https://docs.coingecko.com/reference/top-pools-contract-address.md): This endpoint allows you to **query top pools based on the provided token contract address on a network**
- [Top Pools by Dex](https://docs.coingecko.com/reference/top-pools-dex.md): This endpoint allows you to **query all the top pools based on the provided network and decentralized exchange (DEX)**
- [Top Pools by Network](https://docs.coingecko.com/reference/top-pools-network.md): This endpoint allows you to **query all the top pools based on the provided network**
- [💼 Top Token Holders by Token Address](https://docs.coingecko.com/reference/top-token-holders-token-address.md): This endpoint allows you to **query top token holders based on the provided token contract address on a network**
- [Trending Pools List](https://docs.coingecko.com/reference/trending-pools-list.md): This endpoint allows you to **query all the trending pools across all networks on GeckoTerminal**
- [Trending Pools by Network](https://docs.coingecko.com/reference/trending-pools-network.md): This endpoint allows you to **query the trending pools based on the provided network**
- [Trending Search List](https://docs.coingecko.com/reference/trending-search.md): This endpoint allows you **query trending search coins, NFTs and categories on CoinGecko in the last 24 hours**
- [💼 Trending Search Pools](https://docs.coingecko.com/reference/trending-search-pools.md): This endpoint allows you to **query all the trending search pools across all networks on GeckoTerminal**
- [Asset Platforms List (ID Map)](https://docs.coingecko.com/v3.0.1/reference/asset-platforms-list.md): This endpoint allows you to **query all the asset platforms on CoinGecko**
- [Authentication (Public/Demo)](https://docs.coingecko.com/v3.0.1/reference/authentication.md): Authentication method for CoinGecko Public API (Demo plan users)
- [Coins Categories List with Market Data](https://docs.coingecko.com/v3.0.1/reference/coins-categories.md): This endpoint allows you to **query all the coins categories with market data (market cap, volume, ...) on CoinGecko**
- [Coins Categories List (ID Map)](https://docs.coingecko.com/v3.0.1/reference/coins-categories-list.md): This endpoint allows you to **query all the coins categories on CoinGecko**
- [Coin Data by Token Address](https://docs.coingecko.com/v3.0.1/reference/coins-contract-address.md): This endpoint allows you to **query all the metadata (image, websites, socials, description, contract address, etc.) and market data (price, ATH, exchange tickers, etc.) of a coin from the CoinGecko coin page based on an asset platform and a particular token contract address**
- [Coin Data by ID](https://docs.coingecko.com/v3.0.1/reference/coins-id.md): This endpoint allows you to **query all the metadata (image, websites, socials, description, contract address, etc.) and market data (price, ATH, exchange tickers, etc.) of a coin from the CoinGecko coin page based on a particular coin ID**
- [Coin Historical Data by ID](https://docs.coingecko.com/v3.0.1/reference/coins-id-history.md): This endpoint allows you to **query the historical data (price, market cap, 24hrs volume, ...) at a given date for a coin based on a particular coin ID**
- [Coin Historical Chart Data by ID](https://docs.coingecko.com/v3.0.1/reference/coins-id-market-chart.md): This endpoint allows you to **get the historical chart data of a coin including time in UNIX, price, market cap and 24hr volume based on particular coin ID**
- [Coin Historical Chart Data within Time Range by ID](https://docs.coingecko.com/v3.0.1/reference/coins-id-market-chart-range.md): This endpoint allows you to **get the historical chart data of a coin within certain time range in UNIX along with price, market cap and 24hr volume based on particular coin ID**
- [Coin OHLC Chart by ID](https://docs.coingecko.com/v3.0.1/reference/coins-id-ohlc.md): This endpoint allows you to **get the OHLC chart (Open, High, Low, Close) of a coin based on particular coin ID**
- [Coin Tickers by ID](https://docs.coingecko.com/v3.0.1/reference/coins-id-tickers.md): This endpoint allows you to **query the coin tickers on both centralized exchange (CEX) and decentralized exchange (DEX) based on a particular coin ID**
- [Coins List (ID Map)](https://docs.coingecko.com/v3.0.1/reference/coins-list.md): This endpoint allows you to **query all the supported coins on CoinGecko with coins ID, name and symbol**
- [Coins List with Market Data](https://docs.coingecko.com/v3.0.1/reference/coins-markets.md): This endpoint allows you to **query all the supported coins with price, market cap, volume and market related data**
- [Crypto Treasury Holdings by Coin ID](https://docs.coingecko.com/v3.0.1/reference/companies-public-treasury.md): This endpoint allows you **query public companies & governments' cryptocurrency holdings** by Coin ID
- [Coin Historical Chart Data by Token Address](https://docs.coingecko.com/v3.0.1/reference/contract-address-market-chart.md): This endpoint allows you to **get the historical chart data including time in UNIX, price, market cap and 24hr volume based on asset platform and particular token contract address**
- [Coin Historical Chart Data within Time Range by Token Address](https://docs.coingecko.com/v3.0.1/reference/contract-address-market-chart-range.md): This endpoint allows you to **get the historical chart data within certain time range in UNIX along with price, market cap and 24hr volume based on asset platform and particular token contract address**
- [Crypto Global Market Data](https://docs.coingecko.com/v3.0.1/reference/crypto-global.md): This endpoint allows you **query cryptocurrency global data including active cryptocurrencies, markets, total crypto market cap and etc**
- [Derivatives Exchanges List with Data](https://docs.coingecko.com/v3.0.1/reference/derivatives-exchanges.md): This endpoint allows you to **query all the derivatives exchanges with related data (ID, name, open interest, ...) on CoinGecko**
- [Derivatives Exchange Data by ID](https://docs.coingecko.com/v3.0.1/reference/derivatives-exchanges-id.md): This endpoint allows you to **query the derivatives exchange's related data (ID, name, open interest, ...) based on the exchanges' ID**
- [Derivatives Exchanges List (ID Map)](https://docs.coingecko.com/v3.0.1/reference/derivatives-exchanges-list.md): This endpoint allows you to **query all the derivatives exchanges with ID and name on CoinGecko**
- [Derivatives Tickers List](https://docs.coingecko.com/v3.0.1/reference/derivatives-tickers.md): This endpoint allows you to **query all the tickers from derivatives exchanges on CoinGecko**
- [Supported Dexes List by Network (ID Map)](https://docs.coingecko.com/v3.0.1/reference/dexes-list.md): This endpoint allows you to **query all the supported decentralized exchanges (DEXs) based on the provided network on GeckoTerminal**
- [Endpoint Overview](https://docs.coingecko.com/v3.0.1/reference/endpoint-overview.md)
- [Entities List (ID Map)](https://docs.coingecko.com/v3.0.1/reference/entities-list.md): This endpoint allows you to **query all the supported entities on CoinGecko with entities ID, name, symbol, and country**
- [BTC-to-Currency Exchange Rates](https://docs.coingecko.com/v3.0.1/reference/exchange-rates.md): This endpoint allows you to **query BTC exchange rates with other currencies**
- [Exchanges List with data](https://docs.coingecko.com/v3.0.1/reference/exchanges.md): This endpoint allows you to **query all the supported exchanges with exchanges' data (ID, name, country, ...) that have active trading volumes on CoinGecko**
- [Exchange Data by ID](https://docs.coingecko.com/v3.0.1/reference/exchanges-id.md): This endpoint allows you to **query exchange's data (name, year established, country, ...), exchange volume in BTC and top 100 tickers based on exchange's ID**
- [Exchange Tickers by ID](https://docs.coingecko.com/v3.0.1/reference/exchanges-id-tickers.md): This endpoint allows you to **query exchange's tickers based on exchange's ID**
- [Exchange Volume Chart by ID](https://docs.coingecko.com/v3.0.1/reference/exchanges-id-volume-chart.md): This endpoint allows you to **query the historical volume chart data with time in UNIX and trading volume data in BTC based on exchange's ID**
- [Exchanges List (ID Map)](https://docs.coingecko.com/v3.0.1/reference/exchanges-list.md): This endpoint allows you to **query all the exchanges with ID and name**
- [Global DeFi Market Data](https://docs.coingecko.com/v3.0.1/reference/global-defi.md): This endpoint allows you **query top 100 cryptocurrency global decentralized finance (DeFi) data including DeFi market cap, trading volume**
- [New Pools List](https://docs.coingecko.com/v3.0.1/reference/latest-pools-list.md): This endpoint allows you to **query all the latest pools across all networks on GeckoTerminal**
- [New Pools by Network](https://docs.coingecko.com/v3.0.1/reference/latest-pools-network.md): This endpoint allows you to **query all the latest pools based on provided network**
- [Supported Networks List (ID Map)](https://docs.coingecko.com/v3.0.1/reference/networks-list.md): This endpoint allows you to **query all the supported networks on GeckoTerminal**
- [NFTs Collection Data by Contract Address](https://docs.coingecko.com/v3.0.1/reference/nfts-contract-address.md): This endpoint allows you to **query all the NFT data (name, floor price, 24hr volume ...) based on the NFT collection contract address and respective asset platform**
- [NFTs Collection Data by ID](https://docs.coingecko.com/v3.0.1/reference/nfts-id.md): This endpoint allows you to **query all the NFT data (name, floor price, 24hr volume ...) based on the NFT collection ID**
- [NFTs List (ID Map)](https://docs.coingecko.com/v3.0.1/reference/nfts-list.md): This endpoint allows you to **query all supported NFTs with ID, contract address, name, asset platform ID and symbol on CoinGecko**
- [Token Price by Token Addresses](https://docs.coingecko.com/v3.0.1/reference/onchain-simple-price.md): This endpoint allows you to **get token price based on the provided token contract address on a network**
- [Check API server status](https://docs.coingecko.com/v3.0.1/reference/ping-server.md): This endpoint allows you to **check the API server status**
- [Specific Pool Data by Pool Address](https://docs.coingecko.com/v3.0.1/reference/pool-address.md): This endpoint allows you to **query the specific pool based on the provided network and pool address**
- [Pool OHLCV chart by Pool Address](https://docs.coingecko.com/v3.0.1/reference/pool-ohlcv-contract-address.md): This endpoint allows you to **get the OHLCV chart (Open, High, Low, Close, Volume) of a pool based on the provided pool address on a network**
- [Pool Tokens Info by Pool Address](https://docs.coingecko.com/v3.0.1/reference/pool-token-info-contract-address.md): This endpoint allows you to **query pool metadata (base and quote token details, image, socials, websites, description, contract address, etc.) based on a provided pool contract address on a network**
- [Past 24 Hour Trades by Pool Address](https://docs.coingecko.com/v3.0.1/reference/pool-trades-contract-address.md): This endpoint allows you to **query the last 300 trades in the past 24 hours based on the provided pool address**
- [Multiple Pools Data by Pool Addresses](https://docs.coingecko.com/v3.0.1/reference/pools-addresses.md): This endpoint allows you to **query multiple pools based on the provided network and pool address**
- [Crypto Treasury Holdings by Entity ID](https://docs.coingecko.com/v3.0.1/reference/public-treasury-entity.md): This endpoint allows you **query public companies & governments' cryptocurrency holdings** by Entity ID
- [Search Queries](https://docs.coingecko.com/v3.0.1/reference/search-data.md): This endpoint allows you to **search for coins, categories and markets listed on CoinGecko**
- [Search Pools](https://docs.coingecko.com/v3.0.1/reference/search-pools.md): This endpoint allows you to **search for pools on a network**
- [Coin Price by IDs](https://docs.coingecko.com/v3.0.1/reference/simple-price.md): This endpoint allows you to **query the prices of one or more coins by using their unique Coin API IDs**
- [Supported Currencies List](https://docs.coingecko.com/v3.0.1/reference/simple-supported-currencies.md): This endpoint allows you to **query all the supported currencies on CoinGecko**
- [Coin Price by Token Addresses](https://docs.coingecko.com/v3.0.1/reference/simple-token-price.md): This endpoint allows you to **query one or more token prices using their token contract addresses**
- [Token Data by Token Address](https://docs.coingecko.com/v3.0.1/reference/token-data-contract-address.md): This endpoint allows you to **query specific token data based on the provided token contract address on a network**
- [Token Info by Token Address](https://docs.coingecko.com/v3.0.1/reference/token-info-contract-address.md): This endpoint allows you to **query token metadata (name, symbol, CoinGecko ID, image, socials, websites, description, etc.) based on a provided token contract address on a network**
- [Token Lists by Asset Platform ID](https://docs.coingecko.com/v3.0.1/reference/token-lists.md): This endpoint allows you to **get full list of tokens of a blockchain network (asset platform) that is supported by [Ethereum token list standard](https://tokenlists.org/)**
- [Tokens Data by Token Addresses](https://docs.coingecko.com/v3.0.1/reference/tokens-data-contract-addresses.md): This endpoint allows you to **query multiple tokens data based on the provided token contract addresses on a network**
- [Most Recently Updated Tokens List](https://docs.coingecko.com/v3.0.1/reference/tokens-info-recent-updated.md): This endpoint allows you to **query 100 most recently updated tokens info of a specific network or across all networks on GeckoTerminal**
- [Top Pools by Token Address](https://docs.coingecko.com/v3.0.1/reference/top-pools-contract-address.md): This endpoint allows you to **query top pools based on the provided token contract address on a network**
- [Top Pools by Dex](https://docs.coingecko.com/v3.0.1/reference/top-pools-dex.md): This endpoint allows you to **query all the top pools based on the provided network and decentralized exchange (DEX)**
- [Top Pools by Network](https://docs.coingecko.com/v3.0.1/reference/top-pools-network.md): This endpoint allows you to **query all the top pools based on the provided network**
- [Trending Pools List](https://docs.coingecko.com/v3.0.1/reference/trending-pools-list.md): This endpoint allows you to **query all the trending pools across all networks on GeckoTerminal**
- [Trending Pools by Network](https://docs.coingecko.com/v3.0.1/reference/trending-pools-network.md): This endpoint allows you to **query the trending pools based on the provided network**
- [Trending Search List](https://docs.coingecko.com/v3.0.1/reference/trending-search.md): This endpoint allows you **query trending search coins, NFTs and categories on CoinGecko in the last 24 hours**
- [CGSimplePrice](https://docs.coingecko.com/websocket/cgsimpleprice.md): Subscribe to receive real-time price updates for tokens, as seen on CoinGecko.com
- [WebSocket (Beta)](https://docs.coingecko.com/websocket/index.md): CoinGecko API: Stream Real-Time Crypto Data with WebSockets
- [OnchainSimpleTokenPrice](https://docs.coingecko.com/websocket/onchainsimpletokenprice.md): Subscribe to receive real-time price updates for tokens, as seen on GeckoTerminal.com
- [OnchainTrade](https://docs.coingecko.com/websocket/wss-onchain-trade.md): Subscribe to receive real-time transaction (trade/swap) updates for pools, as seen on GeckoTerminal.com
- [OnchainOHLCV](https://docs.coingecko.com/websocket/wssonchainohlcv.md): Subscribe to receive real-time OHLCV updates for pools, as seen on GeckoTerminal.com
## Optional
- [CoinGecko API](https://www.coingecko.com/en/api)
- [Case Studies](https://www.coingecko.com/en/api/case-studies)
- [Newsletter](https://newsletter.coingecko.com/landing/api_updates_subscribe)
- [Feedback](https://docs.google.com/forms/d/e/1FAIpQLSeb7pnl_YaT17IWR5qnZrlmqmZ0xdYaT0JEyVz717Ergd5ptw/viewform)

View File

@ -0,0 +1,59 @@
# Coingecko - Market Data
**Pages:** 3
---
## 💼 NFTs Collection Historical Chart Data by ID
**URL:** llms-txt#💼-nfts-collection-historical-chart-data-by-id
Source: https://docs.coingecko.com/reference/nfts-id-market-chart
reference/api-reference/coingecko-pro.json get /nfts/{id}/market_chart
This endpoint allows you **query historical market data of a NFT collection, including floor price, market cap, and 24hr volume, by number of days away from now**
* Data Granularity (auto):
* 1-14 days from now = **5-minutely** data
* 15 days & above from now = **daily** data (00:00 UTC)
* Cache/Update Frequency: every 5 minutes
* The last completed UTC day (00:00) is available 5 minutes after midnight on the next UTC day (00:05).
* Exclusive for Paid Plan Subscribers (Analyst, Lite, Pro and Enterprise).
</Note>
---
## 💼 NFTs Collection Historical Chart Data by Contract Address
**URL:** llms-txt#💼-nfts-collection-historical-chart-data-by-contract-address
Source: https://docs.coingecko.com/reference/nfts-contract-address-market-chart
reference/api-reference/coingecko-pro.json get /nfts/{asset_platform_id}/contract/{contract_address}/market_chart
This endpoint allows you **query historical market data of a NFT collection, including floor price, market cap, and 24hr volume, by number of days away from now based on the provided contract address**
* This endpoint doesn't support Solana NFT and Art Blocks, please use [/nfts/\{id}/market\_chart](/reference/nfts-id-market-chart) endpoint instead.
* Data Granularity (auto):
* 1-14 days from now = **5-minutely** data
* 15 days & above from now = **daily** data (00:00 UTC)
* Cache/Update Frequency: every 5 minutes
* The last completed UTC day (00:00) is available 5 minutes after midnight on the next UTC day (00:05).
* Exclusive for Paid Plan Subscribers (Analyst, Lite, Pro and Enterprise).
</Note>
---
## 💼 NFTs Collection Tickers by ID
**URL:** llms-txt#💼-nfts-collection-tickers-by-id
Source: https://docs.coingecko.com/reference/nfts-id-tickers
reference/api-reference/coingecko-pro.json get /nfts/{id}/tickers
This endpoint allows you to **query the latest floor price and 24hr volume of a NFT collection, on each NFT marketplace, e.g. OpenSea and LooksRare**
* Cache/Update Frequency: every 30 seconds.
* Exclusive for Paid Plan Subscribers (Analyst, Lite, Pro and Enterprise).
</Note>
---

View File

@ -0,0 +1,38 @@
# Coingecko - Nfts
**Pages:** 2
---
## NFTs Collection Data by ID
**URL:** llms-txt#nfts-collection-data-by-id
Source: https://docs.coingecko.com/v3.0.1/reference/nfts-id
v3.0.1/reference/api-reference/coingecko-demo.json get /nfts/{id}
This endpoint allows you to **query all the NFT data (name, floor price, 24hr volume ...) based on the NFT collection ID**
* Cache / Update Frequency: every 60 seconds for all the API plans.
</Note>
---
## NFTs List (ID Map)
**URL:** llms-txt#nfts-list-(id-map)
Source: https://docs.coingecko.com/v3.0.1/reference/nfts-list
v3.0.1/reference/api-reference/coingecko-demo.json get /nfts/list
This endpoint allows you to **query all supported NFTs with ID, contract address, name, asset platform ID and symbol on CoinGecko**
* You may use this endpoint to query the list of NFTs for other endpoints that contain params like `id` (NFT collection's id) as well as `asset_platform_id` and `contract_address`.
* You may include values such as `per_page` and `page` to specify how many results you would like to show in the responses per page and which page of responses you would like to show.
</Tip>
* The responses are paginated to 100 items.
* Cache / Update Frequency: every 5 minutes for all the API plans.
</Note>
---

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,52 @@
# Coingecko - Pricing
**Pages:** 1
---
## Tutorials (Beginner-friendly)
**URL:** llms-txt#tutorials-(beginner-friendly)
**Contents:**
- 🔤 No Code
- 💻 Low Code
- 👨‍💻 Code
Source: https://docs.coingecko.com/docs/tutorials-beginner-friendly
Using CoinGecko API is super easy, even if you have no programming experience!
* [Import Crypto Prices in Google Sheets](https://www.coingecko.com/learn/import-crypto-prices-google-sheets)
<a href="https://www.coingecko.com/learn/import-crypto-prices-google-sheets" target="_blank" rel="noopener noreferrer">
<Frame>
<img src="https://mintcdn.com/coingecko/M02rMX2XJMwBGpCe/images/docs/906cac9-image.png?fit=max&auto=format&n=M02rMX2XJMwBGpCe&q=85&s=c96bbea598140dba0164bbe3e4f61760" noZoom data-og-width="950" width="950" data-og-height="475" height="475" data-path="images/docs/906cac9-image.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/coingecko/M02rMX2XJMwBGpCe/images/docs/906cac9-image.png?w=280&fit=max&auto=format&n=M02rMX2XJMwBGpCe&q=85&s=d13a6c4da6429b209dae28775142ebe5 280w, https://mintcdn.com/coingecko/M02rMX2XJMwBGpCe/images/docs/906cac9-image.png?w=560&fit=max&auto=format&n=M02rMX2XJMwBGpCe&q=85&s=b748519107cdd0675124d4d05f2da490 560w, https://mintcdn.com/coingecko/M02rMX2XJMwBGpCe/images/docs/906cac9-image.png?w=840&fit=max&auto=format&n=M02rMX2XJMwBGpCe&q=85&s=0da19082bce7186cb4df2b8c67757994 840w, https://mintcdn.com/coingecko/M02rMX2XJMwBGpCe/images/docs/906cac9-image.png?w=1100&fit=max&auto=format&n=M02rMX2XJMwBGpCe&q=85&s=33f43f5a4672be22b501a9c2c157e9ab 1100w, https://mintcdn.com/coingecko/M02rMX2XJMwBGpCe/images/docs/906cac9-image.png?w=1650&fit=max&auto=format&n=M02rMX2XJMwBGpCe&q=85&s=fda02e234c3e0dcccef137eb1d0156cc 1650w, https://mintcdn.com/coingecko/M02rMX2XJMwBGpCe/images/docs/906cac9-image.png?w=2500&fit=max&auto=format&n=M02rMX2XJMwBGpCe&q=85&s=dd24d20dd9bb7ae493d77aff4ec9b116 2500w" />
</Frame>
</a>
* [Import Crypto Prices in Microsoft Excel](https://www.coingecko.com/learn/import-crypto-prices-excel)
<a href="https://www.coingecko.com/learn/import-crypto-prices-excel" target="_blank" rel="noopener noreferrer">
<Frame>
<img src="https://mintcdn.com/coingecko/M02rMX2XJMwBGpCe/images/docs/3ee7dca-image.png?fit=max&auto=format&n=M02rMX2XJMwBGpCe&q=85&s=461979ff4f88f526da4d96325c619a55" noZoom data-og-width="1472" width="1472" data-og-height="704" height="704" data-path="images/docs/3ee7dca-image.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/coingecko/M02rMX2XJMwBGpCe/images/docs/3ee7dca-image.png?w=280&fit=max&auto=format&n=M02rMX2XJMwBGpCe&q=85&s=8a81f02bb6c2f787523cf1975ab6b56b 280w, https://mintcdn.com/coingecko/M02rMX2XJMwBGpCe/images/docs/3ee7dca-image.png?w=560&fit=max&auto=format&n=M02rMX2XJMwBGpCe&q=85&s=0fedcd8efc2090812749d817ae172ffb 560w, https://mintcdn.com/coingecko/M02rMX2XJMwBGpCe/images/docs/3ee7dca-image.png?w=840&fit=max&auto=format&n=M02rMX2XJMwBGpCe&q=85&s=0a6e2faa6f8aea908c5dbc92cd9f60fe 840w, https://mintcdn.com/coingecko/M02rMX2XJMwBGpCe/images/docs/3ee7dca-image.png?w=1100&fit=max&auto=format&n=M02rMX2XJMwBGpCe&q=85&s=30b96b3f0d6a76a46758d91a20366ff0 1100w, https://mintcdn.com/coingecko/M02rMX2XJMwBGpCe/images/docs/3ee7dca-image.png?w=1650&fit=max&auto=format&n=M02rMX2XJMwBGpCe&q=85&s=75654d488e16b4309623cc91391ed614 1650w, https://mintcdn.com/coingecko/M02rMX2XJMwBGpCe/images/docs/3ee7dca-image.png?w=2500&fit=max&auto=format&n=M02rMX2XJMwBGpCe&q=85&s=f8d8aa22a51b94adc04decc40ba41f78 2500w" />
</Frame>
</a>
* [Create Portfolio Tracker in Microsoft Excel](https://www.coingecko.com/learn/crypto-portfolio-tracker-google-sheets)
<a href="https://www.coingecko.com/learn/crypto-portfolio-tracker-google-sheets" target="_blank" rel="noopener noreferrer">
<Frame>
<img src="https://mintcdn.com/coingecko/M02rMX2XJMwBGpCe/images/docs/f4d47e2-image.png?fit=max&auto=format&n=M02rMX2XJMwBGpCe&q=85&s=0820b04fd5f2d945e8618d88733a35a9" noZoom data-og-width="1200" width="1200" data-og-height="600" height="600" data-path="images/docs/f4d47e2-image.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/coingecko/M02rMX2XJMwBGpCe/images/docs/f4d47e2-image.png?w=280&fit=max&auto=format&n=M02rMX2XJMwBGpCe&q=85&s=ec9dc9ecacf4dea880bb9283043d54a5 280w, https://mintcdn.com/coingecko/M02rMX2XJMwBGpCe/images/docs/f4d47e2-image.png?w=560&fit=max&auto=format&n=M02rMX2XJMwBGpCe&q=85&s=d8061f7df985a8e013b4f20b506ffcd1 560w, https://mintcdn.com/coingecko/M02rMX2XJMwBGpCe/images/docs/f4d47e2-image.png?w=840&fit=max&auto=format&n=M02rMX2XJMwBGpCe&q=85&s=71545611aa35f6686853ff932713ec81 840w, https://mintcdn.com/coingecko/M02rMX2XJMwBGpCe/images/docs/f4d47e2-image.png?w=1100&fit=max&auto=format&n=M02rMX2XJMwBGpCe&q=85&s=c563a701e58781f49d7db9020de3fa5c 1100w, https://mintcdn.com/coingecko/M02rMX2XJMwBGpCe/images/docs/f4d47e2-image.png?w=1650&fit=max&auto=format&n=M02rMX2XJMwBGpCe&q=85&s=8ef6ecb51f3e8ecf5c0fe1d991bfc2e5 1650w, https://mintcdn.com/coingecko/M02rMX2XJMwBGpCe/images/docs/f4d47e2-image.png?w=2500&fit=max&auto=format&n=M02rMX2XJMwBGpCe&q=85&s=74ab69e420239526560da774b35d35a4 2500w" />
</Frame>
</a>
* [Fetch Crypto Data Using Python](https://www.coingecko.com/learn/python-query-coingecko-api)
<a href="https://www.coingecko.com/learn/python-query-coingecko-api" target="_blank" rel="noopener noreferrer">
<Frame>
<img src="https://mintcdn.com/coingecko/M02rMX2XJMwBGpCe/images/docs/bf15f91-image.png?fit=max&auto=format&n=M02rMX2XJMwBGpCe&q=85&s=595e24814ec97ede65a775347cee4bca" noZoom data-og-width="950" width="950" data-og-height="473" height="473" data-path="images/docs/bf15f91-image.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/coingecko/M02rMX2XJMwBGpCe/images/docs/bf15f91-image.png?w=280&fit=max&auto=format&n=M02rMX2XJMwBGpCe&q=85&s=4bf00666cc1d6121a705b48ae386a7a9 280w, https://mintcdn.com/coingecko/M02rMX2XJMwBGpCe/images/docs/bf15f91-image.png?w=560&fit=max&auto=format&n=M02rMX2XJMwBGpCe&q=85&s=4a27c38c5a4a49b15c1081922fa526f0 560w, https://mintcdn.com/coingecko/M02rMX2XJMwBGpCe/images/docs/bf15f91-image.png?w=840&fit=max&auto=format&n=M02rMX2XJMwBGpCe&q=85&s=da86d2d15d228dfa49e4c4ac7214df31 840w, https://mintcdn.com/coingecko/M02rMX2XJMwBGpCe/images/docs/bf15f91-image.png?w=1100&fit=max&auto=format&n=M02rMX2XJMwBGpCe&q=85&s=d8547008839925194e0ac89bf1436127 1100w, https://mintcdn.com/coingecko/M02rMX2XJMwBGpCe/images/docs/bf15f91-image.png?w=1650&fit=max&auto=format&n=M02rMX2XJMwBGpCe&q=85&s=ee7fc9d6444ca624f93fd0f78afc893c 1650w, https://mintcdn.com/coingecko/M02rMX2XJMwBGpCe/images/docs/bf15f91-image.png?w=2500&fit=max&auto=format&n=M02rMX2XJMwBGpCe&q=85&s=98f982d6ba198a370c7ac0a089ef673b 2500w" />
</Frame>
</a>
---

View File

@ -0,0 +1,154 @@
# Coingecko - Reference
**Pages:** 9
---
## 💼 API Usage
**URL:** llms-txt#💼-api-usage
Source: https://docs.coingecko.com/reference/api-usage
reference/api-reference/coingecko-pro.json get /key
This endpoint allows you to **monitor your account's API usage, including rate limits, monthly total credits, remaining credits, and more**
For a more comprehensive overview of your API usage, please log in to [https://www.coingecko.com/en/developers/dashboard](https://www.coingecko.com/en/developers/dashboard).
</Note>
---
## Supported Networks List (ID Map)
**URL:** llms-txt#supported-networks-list-(id-map)
Source: https://docs.coingecko.com/v3.0.1/reference/networks-list
v3.0.1/reference/api-reference/onchain-demo.json get /networks
This endpoint allows you to **query all the supported networks on GeckoTerminal**
* You may use this endpoint to query the list of networks with network ID for other endpoints that contain params like `network`.
* You may include values such as `page` to specify which page of responses you would like to show.
</Tip>
---
## Check API server status
**URL:** llms-txt#check-api-server-status
Source: https://docs.coingecko.com/v3.0.1/reference/ping-server
v3.0.1/reference/api-reference/coingecko-demo.json get /ping
This endpoint allows you to **check the API server status**
* You can also go to [status.coingecko.com](https://status.coingecko.com/) to check the API server status and further maintenance notices.
</Note>
---
## Supported Currencies List
**URL:** llms-txt#supported-currencies-list
Source: https://docs.coingecko.com/v3.0.1/reference/simple-supported-currencies
v3.0.1/reference/api-reference/coingecko-demo.json get /simple/supported_vs_currencies
This endpoint allows you to **query all the supported currencies on CoinGecko**
* You may use this endpoint to query the list of currencies for other endpoints that contain params like `vs_currencies`.
</Tip>
* Cache/Update Frequency: every 60 seconds for Public API.
</Note>
---
## Asset Platforms List (ID Map)
**URL:** llms-txt#asset-platforms-list-(id-map)
Source: https://docs.coingecko.com/v3.0.1/reference/asset-platforms-list
v3.0.1/reference/api-reference/coingecko-demo.json get /asset_platforms
This endpoint allows you to **query all the asset platforms on CoinGecko**
* You may use this endpoint to query the list of asset platforms for other endpoints that contain params like `id` or`ids`(asset platforms).
* You may include NFT at the `filter` params to get the list of NFT-support asset platforms on CoinGecko.
</Tip>
---
## Past 24 Hour Trades by Pool Address
**URL:** llms-txt#past-24-hour-trades-by-pool-address
Source: https://docs.coingecko.com/v3.0.1/reference/pool-trades-contract-address
v3.0.1/reference/api-reference/onchain-demo.json get /networks/{network}/pools/{pool_address}/trades
This endpoint allows you to **query the last 300 trades in the past 24 hours based on the provided pool address**
* Cache/Update Frequency: every 60 seconds.
</Note>
---
## Entities List (ID Map)
**URL:** llms-txt#entities-list-(id-map)
Source: https://docs.coingecko.com/v3.0.1/reference/entities-list
v3.0.1/reference/api-reference/coingecko-demo.json get /entities/list
This endpoint allows you to **query all the supported entities on CoinGecko with entities ID, name, symbol, and country**
* Cache / Update Frequency: every 5 minutes for all the API plans.
</Note>
---
## Top Pools by Network
**URL:** llms-txt#top-pools-by-network
Source: https://docs.coingecko.com/v3.0.1/reference/top-pools-network
v3.0.1/reference/api-reference/onchain-demo.json get /networks/{network}/pools
This endpoint allows you to **query all the top pools based on the provided network**
* You may include values such as `page` to specify which page of responses you would like to show.
* For more flexibility in retrieving an exact list of pools that match your specific needs, consider using the [/pools/megafilter](https://docs.coingecko.com/reference/pools-megafilter) endpoint (available for [Paid Plan](https://www.coingecko.com/en/api/pricing) subscribers \[Analyst plan or above].)
</Tip>
* If the token's market cap is not verified by the team, the API response will return `null` for its market cap value, even though it has a displayed value on GeckoTerminal, which might not be accurate as it often matches the Fully Diluted Valuation (FDV).
* Attributes specified in the `include` param will be returned under the top-level "included" key.
* This endpoint returns up to 20 pools per page. Use the `page` param to navigate more results.
* `page`: Pagination beyond 10 pages is available for [Paid Plan](https://www.coingecko.com/en/api/pricing) subscribers (Analyst plan or above).
* Cache/Update frequency: every 60 seconds.
* GeckoTerminal equivalent page (example): [https://www.geckoterminal.com/solana/pools?sort=-24h\_transactions](https://www.geckoterminal.com/solana/pools?sort=-24h_transactions)
</Note>
---
## Top Pools by Dex
**URL:** llms-txt#top-pools-by-dex
Source: https://docs.coingecko.com/v3.0.1/reference/top-pools-dex
v3.0.1/reference/api-reference/onchain-demo.json get /networks/{network}/dexes/{dex}/pools
This endpoint allows you to **query all the top pools based on the provided network and decentralized exchange (DEX)**
* You may include values such as `page` to specify which page of responses you would like to show.
* For more flexibility in retrieving an exact list of pools that match your specific needs, consider using the [/pools/megafilter](https://docs.coingecko.com/reference/pools-megafilter) endpoint (available for [Paid Plan](https://www.coingecko.com/en/api/pricing) subscribers \[Analyst plan or above].)
</Tip>
* If the token's market cap is not verified by the team, the API response will return `null` for its market cap value, even though it has a displayed value on GeckoTerminal, which might not be accurate as it often matches the Fully Diluted Valuation (FDV).
* Attributes specified in the `include` param will be returned under the top-level "included" key.
* This endpoint returns up to 20 pools per page. Use the `page` param to navigate more results.
* `page`: Pagination beyond 10 pages is available for [Paid Plan](https://www.coingecko.com/en/api/pricing) subscribers (Analyst plan or above).
* Cache/Update frequency: every 60 seconds.
* GeckoTerminal equivalent page (example): [https://www.geckoterminal.com/base/uniswap-v3-base/pools?sort=-24h\_transactions](https://www.geckoterminal.com/base/uniswap-v3-base/pools?sort=-24h_transactions)
</Note>
---

View File

@ -0,0 +1,51 @@
# Coingecko - Trending
**Pages:** 2
---
## Trending Pools by Network
**URL:** llms-txt#trending-pools-by-network
Source: https://docs.coingecko.com/v3.0.1/reference/trending-pools-network
v3.0.1/reference/api-reference/onchain-demo.json get /networks/{network}/trending_pools
This endpoint allows you to **query the trending pools based on the provided network**
* You may include values such as `page` to specify which page of responses you would like to show.
* For more flexibility in retrieving an exact list of pools that match your specific needs, consider using the [/pools/megafilter](https://docs.coingecko.com/reference/pools-megafilter) endpoint (available for [Paid Plan](https://www.coingecko.com/en/api/pricing) subscribers \[Analyst plan or above].)
</Tip>
* If the token's market cap is not verified by the team, the API response will return `null` for its market cap value, even though it has a displayed value on GeckoTerminal, which might not be accurate as it often matches the Fully Diluted Valuation (FDV).
* Attributes specified in the `include` param will be returned under the top-level "included" key.
* This endpoint returns up to 20 pools per page. Use the `page` param to navigate more results.
* `page`: Pagination beyond 10 pages is available for [Paid Plan](https://www.coingecko.com/en/api/pricing) subscribers (Analyst plan or above).
* Cache/Update frequency: every 60 seconds.
* GeckoTerminal equivalent page (example): [https://www.geckoterminal.com/base/pools](https://www.geckoterminal.com/base/pools)
</Note>
---
## Trending Pools List
**URL:** llms-txt#trending-pools-list
Source: https://docs.coingecko.com/v3.0.1/reference/trending-pools-list
v3.0.1/reference/api-reference/onchain-demo.json get /networks/trending_pools
This endpoint allows you to **query all the trending pools across all networks on GeckoTerminal**
* You may include values such as `page` to specify which page of responses you would like to show.
* For more flexibility in retrieving an exact list of pools that match your specific needs, consider using the [/pools/megafilter](https://docs.coingecko.com/reference/pools-megafilter) endpoint (available for [Paid Plan](https://www.coingecko.com/en/api/pricing) subscribers \[Analyst plan or above].)
</Tip>
* If the token's market cap is not verified by the team, the API response will return `null` for its market cap value, even though it has a displayed value on GeckoTerminal, which might not be accurate as it often matches the Fully Diluted Valuation (FDV).
* Attributes specified in the `include` param will be returned under the top-level "included" key.
* This endpoint returns up to 20 pools per page. Use the `page` param to navigate more results.
* `page`: Pagination beyond 10 pages is available for [Paid Plan](https://www.coingecko.com/en/api/pricing) subscribers (Analyst plan or above).
* Cache/Update frequency: every 60 seconds.
* GeckoTerminal equivalent page (example): [https://www.geckoterminal.com](https://www.geckoterminal.com)
</Note>
---

221
skills/cryptofeed/SKILL.md Normal file
View File

@ -0,0 +1,221 @@
---
name: cryptofeed
description: Cryptofeed - Real-time cryptocurrency market data feeds from 40+ exchanges. WebSocket streaming, normalized data, order books, trades, tickers. Python library for algorithmic trading and market data analysis.
---
# Cryptofeed Skill
Comprehensive assistance with Cryptofeed development - a Python library for handling cryptocurrency exchange data feeds with normalized and standardized results.
## When to Use This Skill
This skill should be triggered when:
- Working with real-time cryptocurrency market data
- Implementing WebSocket streaming from crypto exchanges
- Building algorithmic trading systems
- Processing order book updates, trades, or ticker data
- Connecting to 40+ cryptocurrency exchanges
- Using normalized exchange APIs
- Implementing market data backends (Redis, MongoDB, Kafka, etc.)
## Quick Reference
### Installation
```python
# Basic installation
pip install cryptofeed
# With all optional backends
pip install cryptofeed[all]
```
### Basic Usage Pattern
```python
from cryptofeed import FeedHandler
from cryptofeed.exchanges import Coinbase, Bitfinex
from cryptofeed.defines import TICKER, TRADES, L2_BOOK
# Define callbacks
def ticker_callback(data):
print(f"Ticker: {data}")
def trade_callback(data):
print(f"Trade: {data}")
# Create feed handler
fh = FeedHandler()
# Add exchange feeds
fh.add_feed(Coinbase(
symbols=['BTC-USD'],
channels=[TICKER],
callbacks={TICKER: ticker_callback}
))
fh.add_feed(Bitfinex(
symbols=['BTC-USD'],
channels=[TRADES],
callbacks={TRADES: trade_callback}
))
# Start receiving data
fh.run()
```
### National Best Bid/Offer (NBBO)
```python
from cryptofeed import FeedHandler
from cryptofeed.exchanges import Coinbase, Gemini, Kraken
def nbbo_update(symbol, bid, bid_size, ask, ask_size, bid_feed, ask_feed):
print(f'Pair: {symbol} Bid: {bid:.2f} ({bid_size:.6f}) from {bid_feed}')
print(f'Ask: {ask:.2f} ({ask_size:.6f}) from {ask_feed}')
f = FeedHandler()
f.add_nbbo([Coinbase, Kraken, Gemini], ['BTC-USD'], nbbo_update)
f.run()
```
## Supported Exchanges (40+)
### Major Exchanges
- **Binance** (Spot, Futures, Delivery, US)
- **Coinbase**, **Kraken** (Spot, Futures), **Bitfinex**
- **Gemini**, **OKX**, **Bybit**
- **Huobi** (Spot, DM, Swap), **Gate.io** (Spot, Futures)
- **KuCoin**, **Deribit**, **BitMEX**, **dYdX**
### Additional Exchanges
AscendEX, Bequant, bitFlyer, Bithumb, Bitstamp, Blockchain.com, Bit.com, Bitget, Crypto.com, Delta, EXX, FMFW.io, HitBTC, Independent Reserve, OKCoin, Phemex, Poloniex, ProBit, Upbit
## Supported Data Channels
### Market Data (Public)
- **L1_BOOK** - Top of order book
- **L2_BOOK** - Price aggregated sizes
- **L3_BOOK** - Price aggregated orders
- **TRADES** - Executed trades (taker side)
- **TICKER** - Price ticker updates
- **FUNDING** - Funding rate data
- **OPEN_INTEREST** - Open interest statistics
- **LIQUIDATIONS** - Liquidation events
- **INDEX** - Index price data
- **CANDLES** - Candlestick/K-line data
### Authenticated Channels (Private)
- **ORDER_INFO** - Order status updates
- **TRANSACTIONS** - Deposits and withdrawals
- **BALANCES** - Wallet balance updates
- **FILLS** - User's executed trades
## Supported Backends
Write data directly to storage:
- **Redis** (Streams and Sorted Sets)
- **Arctic** - Time-series database
- **ZeroMQ**, **InfluxDB v2**, **MongoDB**
- **Kafka**, **RabbitMQ**, **PostgreSQL**
- **QuasarDB**, **GCP Pub/Sub**, **QuestDB**
- **UDP/TCP/Unix Sockets**
## Key Features
### Real-time Data Normalization
Cryptofeed normalizes data across all exchanges, providing consistent:
- Symbol formatting
- Timestamp handling
- Data structures
- Channel names
### WebSocket + REST Fallback
- Primarily uses WebSockets for real-time data
- Falls back to REST polling when WebSocket unavailable
- Automatic reconnection handling
### NBBO Aggregation
Create synthetic National Best Bid/Offer feeds by aggregating data across multiple exchanges to find arbitrage opportunities.
### Backend Integration
Direct data writing to various storage systems without custom integration code.
## Requirements
- **Python**: 3.8 or higher
- **Installation**: Via pip or from source
- **Optional Dependencies**: Install backends as needed
## Common Use Cases
### Multi-Exchange Price Monitoring
```python
fh = FeedHandler()
fh.add_feed(Binance(symbols=['BTC-USDT'], channels=[TICKER], callbacks=ticker_cb))
fh.add_feed(Coinbase(symbols=['BTC-USD'], channels=[TICKER], callbacks=ticker_cb))
fh.add_feed(Kraken(symbols=['BTC-USD'], channels=[TICKER], callbacks=ticker_cb))
fh.run()
```
### Order Book Depth Analysis
```python
def book_callback(book, receipt_timestamp):
print(f"Bids: {len(book.book.bids)} | Asks: {len(book.book.asks)}")
fh.add_feed(Coinbase(
symbols=['BTC-USD'],
channels=[L2_BOOK],
callbacks={L2_BOOK: book_callback}
))
```
### Trade Flow Analysis
```python
def trade_callback(trade, receipt_timestamp):
print(f"{trade.exchange} - {trade.symbol}: {trade.side} {trade.amount} @ {trade.price}")
fh.add_feed(Binance(
symbols=['BTC-USDT', 'ETH-USDT'],
channels=[TRADES],
callbacks={TRADES: trade_callback}
))
```
## Reference Files
This skill includes documentation in `references/`:
- **getting_started.md** - Installation and basic usage
- **README.md** - Complete overview and examples
Use `view` to read specific reference files when detailed information is needed.
## Working with This Skill
### For Beginners
Start with basic FeedHandler setup and single exchange connections before adding multiple feeds.
### For Advanced Users
Explore NBBO feeds, authenticated channels, and backend integrations for production systems.
### For Code Examples
See the quick reference section above and the reference files for complete working examples.
## Resources
- **Repository**: https://github.com/bmoscon/cryptofeed
- **PyPI**: https://pypi.python.org/pypi/cryptofeed
- **Examples**: https://github.com/bmoscon/cryptofeed/tree/master/examples
- **Documentation**: https://github.com/bmoscon/cryptofeed/blob/master/docs/README.md
- **Discord**: https://discord.gg/zaBYaGAYfR
- **Related**: Cryptostore (containerized data storage)
## Notes
- Requires Python 3.8+
- WebSocket-first approach with REST fallback
- Normalized data across all exchanges
- Active development and community support
- 40+ supported exchanges and growing

View File

@ -0,0 +1,192 @@
# Cryptocurrency Exchange Feed Handler
[![License](https://img.shields.io/badge/license-XFree86-blue.svg)](LICENSE)
![Python](https://img.shields.io/badge/Python-3.8+-green.svg)
[![PyPi](https://img.shields.io/badge/PyPi-cryptofeed-brightgreen.svg)](https://pypi.python.org/pypi/cryptofeed)
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/efa4e0d6e10b41d0b51454d08f7b33b1)](https://www.codacy.com/app/bmoscon/cryptofeed?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=bmoscon/cryptofeed&amp;utm_campaign=Badge_Grade)
Handles multiple cryptocurrency exchange data feeds and returns normalized and standardized results to client registered callbacks for events like trades, book updates, ticker updates, etc. Utilizes websockets when possible, but can also poll data via REST endpoints if a websocket is not provided.
## Supported exchanges
* [AscendEX](https://ascendex.com/)
* [Bequant](https://bequant.io/)
* [Bitfinex](https://bitfinex.com)
* [bitFlyer](https://bitflyer.com/)
* [Bithumb](https://en.bithumb.com/)
* [Bitstamp](https://www.bitstamp.net/)
* [Blockchain.com](https://www.blockchain.com/)
* [Bybit](https://www.bybit.com/)
* [Binance](https://www.binance.com/en)
* [Binance Delivery](https://binance-docs.github.io/apidocs/delivery/en/)
* [Binance Futures](https://www.binance.com/en/futures)
* [Binance US](https://www.binance.us/en)
* [Bit.com](https://www.bit.com)
* [Bitget](https://www.bitget.com/)
* [BitMEX](https://www.bitmex.com/)
* [Coinbase](https://www.coinbase.com/)
* [Crypto.com](https://www.crypto.com)
* [Delta](https://www.delta.exchange/)
* [Deribit](https://www.deribit.com/)
* [dYdX](https://dydx.exchange/)
* [FMFW.io](https://www.fmfw.io/)
* [EXX](https://www.exx.com/)
* [Gate.io](https://www.gate.io/)
* [Gate.io Futures](https://www.gate.io/futures_center)
* [Gemini](https://gemini.com/)
* [HitBTC](https://hitbtc.com/)
* [Huobi](https://www.hbg.com/)
* [Huobi DM](https://www.huobi.com/en-us/markets/hb_dm/)
* Huobi Swap (Coin-M and USDT-M)
* [Independent Reserve](https://www.independentreserve.com/)
* [Kraken](https://www.kraken.com/)
* [Kraken Futures](https://futures.kraken.com/)
* [KuCoin](https://www.kucoin.com/)
* [OKCoin](http://okcoin.com/)
* [OKX](https://www.okx.com/)
* [Phemex](https://phemex.com/)
* [Poloniex](https://www.poloniex.com/)
* [ProBit](https://www.probit.com/)
* [Upbit](https://sg.upbit.com/home)
## Basic Usage
Create a FeedHandler object and add subscriptions. For the various data channels that an exchange supports, you can supply callbacks for data events, or use provided backends (described below) to handle the data for you. Start the feed handler and you're done!
```python
from cryptofeed import FeedHandler
# not all imports shown for clarity
fh = FeedHandler()
# ticker, trade, and book are user defined functions that
# will be called when ticker, trade and book updates are received
ticker_cb = {TICKER: ticker}
trade_cb = {TRADES: trade}
gemini_cb = {TRADES: trade, L2_BOOK: book}
fh.add_feed(Coinbase(symbols=['BTC-USD'], channels=[TICKER], callbacks=ticker_cb))
fh.add_feed(Bitfinex(symbols=['BTC-USD'], channels=[TICKER], callbacks=ticker_cb))
fh.add_feed(Poloniex(symbols=['BTC-USDT'], channels=[TRADES], callbacks=trade_cb))
fh.add_feed(Gemini(symbols=['BTC-USD', 'ETH-USD'], channels=[TRADES, L2_BOOK], callbacks=gemini_cb))
fh.run()
```
Please see the [examples](https://github.com/bmoscon/cryptofeed/tree/master/examples) for more code samples and the [documentation](https://github.com/bmoscon/cryptofeed/blob/master/docs/README.md) for more information about the library usage.
For an example of a containerized application using cryptofeed to store data to a backend, please see [Cryptostore](https://github.com/bmoscon/cryptostore).
## National Best Bid/Offer (NBBO)
Cryptofeed also provides a synthetic [NBBO](examples/demo_nbbo.py) (National Best Bid/Offer) feed that aggregates the best bids and asks from the user specified feeds.
```python
from cryptofeed import FeedHandler
from cryptofeed.exchanges import Coinbase, Gemini, Kraken
def nbbo_update(symbol, bid, bid_size, ask, ask_size, bid_feed, ask_feed):
print(f'Pair: {symbol} Bid Price: {bid:.2f} Bid Size: {bid_size:.6f} Bid Feed: {bid_feed} Ask Price: {ask:.2f} Ask Size: {ask_size:.6f} Ask Feed: {ask_feed}')
def main():
f = FeedHandler()
f.add_nbbo([Coinbase, Kraken, Gemini], ['BTC-USD'], nbbo_update)
f.run()
```
## Supported Channels
Cryptofeed supports the following channels from exchanges:
### Market Data Channels (Public)
* L1_BOOK - Top of book
* L2_BOOK - Price aggregated sizes. Some exchanges provide the entire depth, some provide a subset.
* L3_BOOK - Price aggregated orders. Like the L2 book, some exchanges may only provide partial depth.
* TRADES - Note this reports the taker's side, even for exchanges that report the maker side.
* TICKER
* FUNDING
* OPEN_INTEREST - Open interest data.
* LIQUIDATIONS
* INDEX
* CANDLES - Candlestick / K-Line data.
### Authenticated Data Channels
* ORDER_INFO - Order status updates
* TRANSACTIONS - Real-time updates on account deposits and withdrawals
* BALANCES - Updates on wallet funds
* FILLS - User's executed trades
## Backends
Cryptofeed supports `backend` callbacks that will write directly to storage or other interfaces.
Supported Backends:
* Redis (Streams and Sorted Sets)
* [Arctic](https://github.com/manahl/arctic)
* ZeroMQ
* UDP Sockets
* TCP Sockets
* Unix Domain Sockets
* [InfluxDB v2](https://github.com/influxdata/influxdb)
* MongoDB
* Kafka
* RabbitMQ
* PostgreSQL
* [QuasarDB](https://quasar.ai/)
* GCP Pub/Sub
* [QuestDB](https://questdb.io/)
## Installation
**Note:** cryptofeed requires Python 3.8+
Cryptofeed can be installed from PyPi. (It's recommended that you install in a virtual environment of your choosing).
pip install cryptofeed
Cryptofeed has optional dependencies, depending on the backends used. You can install them individually, or all at once. To install Cryptofeed along with all its optional dependencies in one bundle:
pip install cryptofeed[all]
If you wish to clone the repository and install from source, run this command from the root of the cloned repository.
python setup.py install
Alternatively, you can install in 'edit' mode (also called development mode):
python setup.py develop
See more discussion of package installation in [INSTALL.md](https://github.com/bmoscon/cryptofeed/blob/master/INSTALL.md).
## Rest API
Cryptofeed supports some REST interfaces for retrieving real-time and historical data, as well as order placement and account management. These are integrated into the exchange classes directly. You can view the supported methods by calling the `info()` method on any exchange. The methods for interacting with the exchange RET endpoints exist in two flavors, the synchronous methods (suffixed with `_sync`) as well as the asynchronous which can be utilized with asyncio. For more information see the [documentation](docs/rest.md).
## Future Work
There are a lot of planned features, new exchanges, etc planned! If you'd like to discuss ongoing development, please join the [discord](https://discord.gg/zaBYaGAYfR) or open a thread in the [discussions](https://github.com/bmoscon/cryptofeed/discussions) in GitHub.
## Contributing
Issues and PRs are welcomed!
Cryptofeed wouldn't be possible without the help of many [contributors](AUTHORS.md)! I owe them and all other contributors my thanks!
## Donations / Support
Support and donations are appreciated but not required. You can donate via [GitHub Sponsors](https://github.com/sponsors/bmoscon), or via the addresses below:
* Bitcoin: bc1qm0kxz8hqacaglku5fjhfe9a5hjnuyfwk02lsyr
* Ethereum: 0x690709FEe13eEce9E7852089BB2D53Ae5D073154

View File

@ -0,0 +1,24 @@
# Cryptofeed Documentation Index
## Categories
### README
**File:** `README.md`
**Pages:** 1 (192 lines)
Complete overview of Cryptofeed including:
- Installation instructions
- Supported exchanges (40+)
- Basic usage examples
- NBBO (National Best Bid/Offer) implementation
- Supported channels and backends
- REST API information
## Quick Links
- Installation and setup → `README.md`
- Basic usage examples → `README.md` (line 52-76)
- NBBO example → `README.md` (line 83-100)
- Supported exchanges → `README.md` (line 9-50)
- Data channels → `README.md` (line 102-125)
- Backend integrations → `README.md` (line 127-146)

View File

@ -0,0 +1,11 @@
# Cryptofeed - Other
**Pages:** 1
---
## GitHub - bmoscon/cryptofeed: Cryptocurrency Exchange Websocket Data Feed Handler
**URL:** https://github.com/bmoscon/cryptofeed
---

133
skills/hummingbot/SKILL.md Normal file
View File

@ -0,0 +1,133 @@
---
name: hummingbot
description: Hummingbot trading bot framework - automated trading strategies, market making, arbitrage, connectors for crypto exchanges. Use when working with algorithmic trading, crypto trading bots, or exchange integrations.
---
# Hummingbot Skill
Comprehensive assistance with hummingbot development, generated from official documentation.
## When to Use This Skill
This skill should be triggered when:
- Working with hummingbot
- Asking about hummingbot features or APIs
- Implementing hummingbot solutions
- Debugging hummingbot code
- Learning hummingbot best practices
## Quick Reference
### Common Patterns
**Pattern 1:** For example: candles = [CandlesFactory.get_candle(connector=kucoin, trading_pair="ETH-USDT", interval="1m", max_records=100)]
```
candles = [CandlesFactory.get_candle(connector=kucoin,
trading_pair="ETH-USDT", interval="1m", max_records=100)]
```
**Pattern 2:** Example:
```
bin/hummingbot_quickstart.py -p a -f simple_pmm_example_config.py -c conf_simple_pmm_example_config_1.yml
```
**Pattern 3:** >>> gateway swap --help usage: gateway swap [-h] [connector] [args ...] positional arguments: connector Connector name/type (e.g., jupiter/router) args Arguments: [base-quote] [side] [amount] options: -h, --help show this help message and exit
```
>>> gateway swap --help
usage: gateway swap [-h] [connector] [args ...]
positional arguments:
connector Connector name/type (e.g., jupiter/router)
args Arguments: [base-quote] [side] [amount]
options:
-h, --help show this help message and exit
```
**Pattern 4:** usage: gateway list [-h]
```
usage: gateway list [-h]
```
**Pattern 5:** Example:
```
price = self.market_data_provider.get_price_by_type('binance', 'BTC-USDT', PriceType.MidPrice)
```
**Pattern 6:** Example:
```
price = self.market_data_provider.get_price_by_volume('binance', 'BTC-USDT', volume: 10000, True)
```
**Pattern 7:** Example:
```
price = self.market_data_provider.get_volume_for_price('binance', 'BTC-USDT', 70000, True)
```
**Pattern 8:** Example:
```
price = self.market_data_provider.get_order_book_snapshot('binance', 'BTC-USDT')
```
## Reference Files
This skill includes comprehensive documentation in `references/`:
- **advanced.md** - Advanced documentation
- **configuration.md** - Configuration documentation
- **connectors.md** - Connectors documentation
- **development.md** - Development documentation
- **getting_started.md** - Getting Started documentation
- **other.md** - Other documentation
- **strategies.md** - Strategies documentation
- **trading.md** - Trading documentation
- **troubleshooting.md** - Troubleshooting documentation
Use `view` to read specific reference files when detailed information is needed.
## Working with This Skill
### For Beginners
Start with the getting_started or tutorials reference files for foundational concepts.
### For Specific Features
Use the appropriate category reference file (api, guides, etc.) for detailed information.
### For Code Examples
The quick reference section above contains common patterns extracted from the official docs.
## Resources
### references/
Organized documentation extracted from official sources. These files contain:
- Detailed explanations
- Code examples with language annotations
- Links to original documentation
- Table of contents for quick navigation
### scripts/
Add helper scripts here for common automation tasks.
### assets/
Add templates, boilerplate, or example projects here.
## Notes
- This skill was automatically generated from official documentation
- Reference files preserve the structure and examples from source docs
- Code examples include language detection for better syntax highlighting
- Quick reference patterns are extracted from common usage examples in the docs
## Updating
To refresh this skill with updated documentation:
1. Re-run the scraper with the same configuration
2. The skill will be rebuilt with the latest information

View File

@ -0,0 +1,255 @@
# Hummingbot - Advanced
**Pages:** 7
---
##
**URL:** https://hummingbot.org/dashboard/backtest.png
---
##
**URL:** https://hummingbot.org/dashboard/backtest-2.png
---
##
**URL:** https://hummingbot.org/assets/img/backtesting.png
---
##
**URL:** https://hummingbot.org/dashboard/backtest-1.png
---
## Check Performance - Hummingbot
**URL:** https://hummingbot.org/client/history
**Contents:**
- Performance History¶
- History command¶
- How It Works¶
- Sample Output¶
- Average Price¶
- Hold Portfolio Value¶
- Current Portfolio Value¶
- Trade P&
- Total P&
- Return Percentage¶
The history command displays the current duration of total past trades, asset inventory and value, and market trading pair performance. Run history --verbose to see all recent trades.
Trades are saved locally in a .csv file located in the data folder which you can view by running history --verbose --days command even after you restart Hummingbot.
Optional argument --precision specifies the number of decimal values.
This block below shows the calculation for some of the values displayed in the history output.
The Return % in the navbar at the bottom of Hummingbot client may be different from the history command output. This is because the Return % in history takes the price changes into calculation while the navbar in the bottom UI does not.
Run the history command in Hummingbot to display the current duration of total past trades, asset inventory and value, market trading pair performance.
The following displays the formula for key calculations:
For more details on the calculations, please see this Google Sheet.
Avg Price = Total trade volume of quote/Total trade volume of base asset.
In the sample output, the total avg price is 6.91/47423 = 0.0001457
This value means the average price of total MFT/BNB trades is 0.0001457
The asset value from the start to the end with no trades.
Hold portfolio value = (base start asset*current market price)+ quote start asset
From the above example, for the Hold portfolio value is (155248*0.0000809)+23.33=35.89
Current portfolio value = (base current asset*current market price)+ quote current asset
From the above example, for the Current portfolio value is (202671*0.0000809)+16.419=32.815
Trade P&L = Current portfolio value - Hold Portfolio value
From the above example, for the Trade P&L value is 32.815-35.89=-3.075
Total P&L = Trade P&L + Fees paid
From the above example, for the Total P&L is -3.075 + -0.428 = -3.504
Return% = Total P&L/Hold portfolio value
From the above example, for the Return% is -3.075/-35.89 = -9.76%
The Return % (bottom navbar) matches the calculated return on History after the last trade, see following screenshot:
**Examples:**
Example 1 (unknown):
```unknown
Avg price = total trade volume of quote / total trade volume of base asset
Hold portfolio value = (base start asset * current market price) + quote start asset
Current portfolio value = (base current asset * current market price) + quote current asset
Trade P&L = current portfolio value - hold portfolio value
Total P&L = trade P&L + fees paid
Return % = total P&L / hold portfolio value
```
Example 2 (unknown):
```unknown
>>> history
Start Time: 2020-11-11 00:56:37
Current Time: 2020-11-11 12:57:22
Duration: 0 days 12:00:45
binance / MFT-BNB
Trades:
buy sell total
Number of trades 113 97 209
Total trade volume (BTC) 2181335 -2133912 47423
Total trade volume (USDT) -217,67 210.76 -6.91
Avg price 0.0000998 0.0000988 0.0001457
Assets:
Start Current Change
MFT 155248 202671 47423
BNB 23.331 16.419 -6.912
MFT/BNB price 0.0001076 0.0000809 -0.0000267
Base asset % 41.7% 50.0% 8.2%
Performance:
Hold portfolio value 35.890 BNB
Current portfolio value 32.815 BNB
Trade P&L -3.075 BNB
Fees paid -0.428 BNB
Total P&L -3.504 BNB
Return %: -9.76%
```
---
##
**URL:** https://hummingbot.org/dashboard/backtest-3.png
---
## Check Performance - Hummingbot
**URL:** https://hummingbot.org/client/history/
**Contents:**
- Performance History¶
- History command¶
- How It Works¶
- Sample Output¶
- Average Price¶
- Hold Portfolio Value¶
- Current Portfolio Value¶
- Trade P&
- Total P&
- Return Percentage¶
The history command displays the current duration of total past trades, asset inventory and value, and market trading pair performance. Run history --verbose to see all recent trades.
Trades are saved locally in a .csv file located in the data folder which you can view by running history --verbose --days command even after you restart Hummingbot.
Optional argument --precision specifies the number of decimal values.
This block below shows the calculation for some of the values displayed in the history output.
The Return % in the navbar at the bottom of Hummingbot client may be different from the history command output. This is because the Return % in history takes the price changes into calculation while the navbar in the bottom UI does not.
Run the history command in Hummingbot to display the current duration of total past trades, asset inventory and value, market trading pair performance.
The following displays the formula for key calculations:
For more details on the calculations, please see this Google Sheet.
Avg Price = Total trade volume of quote/Total trade volume of base asset.
In the sample output, the total avg price is 6.91/47423 = 0.0001457
This value means the average price of total MFT/BNB trades is 0.0001457
The asset value from the start to the end with no trades.
Hold portfolio value = (base start asset*current market price)+ quote start asset
From the above example, for the Hold portfolio value is (155248*0.0000809)+23.33=35.89
Current portfolio value = (base current asset*current market price)+ quote current asset
From the above example, for the Current portfolio value is (202671*0.0000809)+16.419=32.815
Trade P&L = Current portfolio value - Hold Portfolio value
From the above example, for the Trade P&L value is 32.815-35.89=-3.075
Total P&L = Trade P&L + Fees paid
From the above example, for the Total P&L is -3.075 + -0.428 = -3.504
Return% = Total P&L/Hold portfolio value
From the above example, for the Return% is -3.075/-35.89 = -9.76%
The Return % (bottom navbar) matches the calculated return on History after the last trade, see following screenshot:
**Examples:**
Example 1 (unknown):
```unknown
Avg price = total trade volume of quote / total trade volume of base asset
Hold portfolio value = (base start asset * current market price) + quote start asset
Current portfolio value = (base current asset * current market price) + quote current asset
Trade P&L = current portfolio value - hold portfolio value
Total P&L = trade P&L + fees paid
Return % = total P&L / hold portfolio value
```
Example 2 (unknown):
```unknown
>>> history
Start Time: 2020-11-11 00:56:37
Current Time: 2020-11-11 12:57:22
Duration: 0 days 12:00:45
binance / MFT-BNB
Trades:
buy sell total
Number of trades 113 97 209
Total trade volume (BTC) 2181335 -2133912 47423
Total trade volume (USDT) -217,67 210.76 -6.91
Avg price 0.0000998 0.0000988 0.0001457
Assets:
Start Current Change
MFT 155248 202671 47423
BNB 23.331 16.419 -6.912
MFT/BNB price 0.0001076 0.0000809 -0.0000267
Base asset % 41.7% 50.0% 8.2%
Performance:
Hold portfolio value 35.890 BNB
Current portfolio value 32.815 BNB
Trade P&L -3.075 BNB
Fees paid -0.428 BNB
Total P&L -3.504 BNB
Return %: -9.76%
```
---

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,39 @@
# Hummingbot Documentation Index
## Categories
### Advanced
**File:** `advanced.md`
**Pages:** 7
### Configuration
**File:** `configuration.md`
**Pages:** 24
### Connectors
**File:** `connectors.md`
**Pages:** 100
### Development
**File:** `development.md`
**Pages:** 13
### Getting Started
**File:** `getting_started.md`
**Pages:** 24
### Other
**File:** `other.md`
**Pages:** 75
### Strategies
**File:** `strategies.md`
**Pages:** 73
### Trading
**File:** `trading.md`
**Pages:** 3
### Troubleshooting
**File:** `troubleshooting.md`
**Pages:** 1

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,258 @@
# Hummingbot - Trading
**Pages:** 3
---
## Overview - Hummingbot
**URL:** https://hummingbot.org/gateway/
**Contents:**
- Overview
- What is Gateway?¶
- In This Section¶
- Key Features¶
- Connector Schemas¶
- Installation¶
- Architecture¶
- Governance and Maintenance¶
- Contributing¶
- History¶
Hummingbot Gateway is a Typescript-based API server that standardizes interactions with blockchain networks and decentralized exchanges (DEXs). It acts as a middleware layer, providing a unified interface for performing actions like checking balances, executing trades, and managing wallets across different protocols.
Gateway is a companion service to the Python-based Hummingbot client, exposing standardized REST API endpoints for trading and liquidity-related functionality on DEXs. This enables Hummingbot to run strategies that operate across both centralized (CEX) and decentralized exchanges seamlessly.
For detailed implementation guides and examples for each schema, see DEX Connectors.
Gateway can be installed alongside Hummingbot to enable trading on AMM DEXs, or as a standalone API server. For detailed installation instructions, see Installation & Setup.
When running Gateway in DEV mode, access the interactive Swagger API documentation at: http://localhost:15888/docs
Gateway follows a modular architecture with clear separation of concerns:
Like other connectors, Gateway DEX connectors require ongoing maintenance: fixing bugs, addressing user issues, and keeping up with updates to both the exchange/blockchain API as well as improvements to the Hummingbot connector standard.
Hummingbot Foundation maintains certain reference connectors as the standard and utilizes a community-based maintenance process. We assign Bounties to community developers to upgrade and fix bugs for each exchange's connectors in the codebase.
Each quarter, Exchange Connector Polls allocates HBOT bounties toward the top CEX connectors and determines which exchange connectors should be included in the codebase going forward. This process also determines which blockchains and networks that Gateway supports.
See the Connector Pots tab in HBOT Tracker for the current allocations for each exchange.
Gateway is part of the open source Hummingbot project. Ways to contribute:
For more information about Gateway's history and architecture decisions, see:
**Examples:**
Example 1 (javascript):
```javascript
/src
├── chains/ # Blockchain-specific implementations
│ └── {chain}/ # Each blockchain (ethereum, solana, etc.)
├── connectors/ # DEX-specific implementations
│ ├── {dex}/ # Each DEX connector directory
│ │ ├── router-routes/ # DEX aggregator operations
│ │ ├── amm-routes/ # AMM pool operations
│ │ └── clmm-routes/ # Concentrated liquidity operations
├── services/ # Core services (config, logging, tokens)
├── schemas/ # API request/response schemas
├── templates/ # Base classes and interfaces for connectors
├── tokens/ # Token lists and metadata
├── pools/ # Liquidity pool configurations
└── wallet/ # Wallet management
```
---
## Overview - Hummingbot
**URL:** https://hummingbot.org/gateway
**Contents:**
- Overview
- What is Gateway?¶
- In This Section¶
- Key Features¶
- Connector Schemas¶
- Installation¶
- Architecture¶
- Governance and Maintenance¶
- Contributing¶
- History¶
Hummingbot Gateway is a Typescript-based API server that standardizes interactions with blockchain networks and decentralized exchanges (DEXs). It acts as a middleware layer, providing a unified interface for performing actions like checking balances, executing trades, and managing wallets across different protocols.
Gateway is a companion service to the Python-based Hummingbot client, exposing standardized REST API endpoints for trading and liquidity-related functionality on DEXs. This enables Hummingbot to run strategies that operate across both centralized (CEX) and decentralized exchanges seamlessly.
For detailed implementation guides and examples for each schema, see DEX Connectors.
Gateway can be installed alongside Hummingbot to enable trading on AMM DEXs, or as a standalone API server. For detailed installation instructions, see Installation & Setup.
When running Gateway in DEV mode, access the interactive Swagger API documentation at: http://localhost:15888/docs
Gateway follows a modular architecture with clear separation of concerns:
Like other connectors, Gateway DEX connectors require ongoing maintenance: fixing bugs, addressing user issues, and keeping up with updates to both the exchange/blockchain API as well as improvements to the Hummingbot connector standard.
Hummingbot Foundation maintains certain reference connectors as the standard and utilizes a community-based maintenance process. We assign Bounties to community developers to upgrade and fix bugs for each exchange's connectors in the codebase.
Each quarter, Exchange Connector Polls allocates HBOT bounties toward the top CEX connectors and determines which exchange connectors should be included in the codebase going forward. This process also determines which blockchains and networks that Gateway supports.
See the Connector Pots tab in HBOT Tracker for the current allocations for each exchange.
Gateway is part of the open source Hummingbot project. Ways to contribute:
For more information about Gateway's history and architecture decisions, see:
**Examples:**
Example 1 (javascript):
```javascript
/src
├── chains/ # Blockchain-specific implementations
│ └── {chain}/ # Each blockchain (ethereum, solana, etc.)
├── connectors/ # DEX-specific implementations
│ ├── {dex}/ # Each DEX connector directory
│ │ ├── router-routes/ # DEX aggregator operations
│ │ ├── amm-routes/ # AMM pool operations
│ │ └── clmm-routes/ # Concentrated liquidity operations
├── services/ # Core services (config, logging, tokens)
├── schemas/ # API request/response schemas
├── templates/ # Base classes and interfaces for connectors
├── tokens/ # Token lists and metadata
├── pools/ # Liquidity pool configurations
└── wallet/ # Wallet management
```
---
## Overview - Hummingbot
**URL:** https://hummingbot.org/hummingbot-api/
**Contents:**
- Hummingbot API¶
- Overview¶
- Key Features¶
- Architecture¶
- Key Components¶
- Use Cases¶
- Getting Started¶
- API Routers¶
- 🐳 Docker Management¶
- 💼 Account Management¶
The backend-api has been renamed to hummingbot-api, marking a major revamp of the codebase with improvements in architecture, modularity, and developer experience.
Hummingbot API is a comprehensive RESTful API framework designed for managing trading operations across multiple exchanges. It allows individual traders and teams to deploy custom, private servers for trade execution, portfolio management, and data collection, bot deployment, and other use cases.
GitHub Repository: github.com/hummingbot/hummingbot-api
The Hummingbot API enables various trading applications:
The guides include Docker setup and Python API client examples to get you trading in minutes.
The Hummingbot API provides the following key routers:
Manage Docker containers and instances running Hummingbot
Handle exchange account credentials and configurations
Discover and manage available exchange connectors
Monitor and analyze portfolio performance across exchanges
Execute trades, manage orders, and monitor positions
Configure and deploy trading strategies with real-time updates
Access real-time and historical market data
Deploy, configure, and manage multiple bot instances
Run strategy backtests with historical data
The API uses HTTP Basic Authentication:
A modern, asynchronous Python client is available for interacting with the Hummingbot API. This client is used by the Hummingbot Dashboard as the interface layer for all API communications.
**Examples:**
Example 1 (unknown):
```unknown
graph TB
subgraph "Clients"
direction LR
CUSTOM[Custom Apps]
DASH[Hummingbot<br/>Dashboard]
AI[AI Agents]
end
subgraph "Hummingbot API"
direction LR
API["FastAPI<br/>Server<br/>"]
PG[(PostgreSQL<br/>Database)]
MQTT[EMQX<br/>Message Broker]
end
subgraph "Bots"
BOTS[Hummingbot<br/>Instances]
end
subgraph "Exchanges"
EX[Binance, OKX,<br/>Hyperliquid, etc.]
end
%% Client connections using API Client
DASH -->|Hummingbot API Client| API
%% Bot connections
BOTS <-->|Commands & Updates| MQTT
%% Exchange connections
BOTS <-->|Trade & Data| EX
API <-->|Trade & Data| EX
%% Apply theme colors
classDef clientStyle stroke:#5FFFD7,stroke-width:3px
classDef apiStyle stroke:#00B1BB,stroke-width:3px
classDef botsStyle stroke:#E549FF,stroke-width:3px
class DASH clientStyle
class API,PG,MQTT apiStyle
class BOTS botsStyle
```
Example 2 (unknown):
```unknown
pip install hummingbot-api-client
```
Example 3 (python):
```python
from hummingbot_api_client import HummingbotAPIClient
# Initialize client
client = HummingbotAPIClient(
base_url="http://localhost:8000",
username="your-username",
password="your-password"
)
# Get portfolio data
portfolio = await client.get_portfolio()
# Execute a trade
order = await client.create_order(
connector="binance",
trading_pair="BTC-USDT",
order_type="limit",
side="buy",
amount=0.001,
price=50000
)
```
---

View File

@ -0,0 +1,87 @@
# Hummingbot - Troubleshooting
**Pages:** 1
---
## Troubleshooting - Hummingbot
**URL:** https://hummingbot.org/troubleshooting/
**Contents:**
- Troubleshooting
- Installation¶
- Docker: Permission denied error¶
- Source: conda command not found¶
- Source: ./install: line 40 ... Killed¶
- Source: Could not find conda environment: hummingbot¶
- Source: unable to execute gcc: No such file or directory¶
- Dashboard¶
- Failed to connect MQTT Bridge:¶
- Docker is not running. Please start Docker and refresh the page.¶
The error message above indicates a permission issue while trying to access the Docker daemon socket. This is a common problem when trying to run Docker commands as a non-root user. To add your user to the docker group, use the following command:
Ensure Anaconda, Miniconda, or Miniforge (for arm64 systems) is installed. If you've just installed it, restart your terminal to refresh the command line environment.
Collecting package metadata (repodata.json): / ./install: line 40: 14981 Killed... This error shows up during installation, typically on systems with 2GB RAM or less. Increase your system's RAM to at least 4GB, or consider adding a swap file if upgrading hardware is not feasible.
This is related to the issue above. Check if there are any errors after running the ./install script. If there are, you'll need to solve those first otherwise creating the hummingbot conda environment will fail.
If getting this error you'll need to install the build-essential package. Run the command below to install -
If you get this error, this usually means the Hummingbot Broker is not running, start the Broker from the Instances page and then restart all Hummingbot client instances.
Make sure you have Docker installed. On Windows and MacOS machines make sure you have Docker Desktop running in the background.
Note: The name of the missing module could be something else like st_pages etc. If you get this message this means the environment wasn't installed properly. Run the following steps in a terminal to reinstall -
By default the authentication system is disabled.
Find the variable AUTH_SYSTEM_ENABLED in the CONFIG.py file and set it to True to enable the authentication page.
If you are getting this error on Kraken, or a similar error on a different exchange this is because the exchange connector doesn't currently support market orders which the PositionExecutor needs to close the position.
If you get this error make sure that when you created the API keys you also checked the Access Websockets API option.
You'll need to approve tokens that you are trading. See below for an example if you are trading WETH on Ethereum mainnet
When approving tokens, if you get a "Token not Supported" error, please make sure to add the token address in the tokenlist manually. The token list can be found in the ./conf/list folder
Use the following command to display token balances for different networks.
This error comes up because CTRL + V doesn't work in Hummingbot. Try any of the following shortcuts below to paste.
Press CTRL + X if you want to cancel out of the configuration
If one or more tokens is showing 0 Total in ($), use the command below to change your rate oracle source. By default, the rate_oracle_source is set to Binance and if the token is not available in Binance then the Total in ($) will show 0.
**Examples:**
Example 1 (unknown):
```unknown
docker: Got permission denied while trying to connect to the Docker daemon socket at
unix:///var/run/docker.sock...
```
Example 2 (unknown):
```unknown
sudo usermod -aG docker $USER
# Restart the terminal after running the command above, if it still doesn't work try the command below
sudo chmod 666 /var/run/docker.sock
```
Example 3 (unknown):
```unknown
$ conda
-bash: conda: command not found
```
Example 4 (unknown):
```unknown
Collecting package metadata (repodata.json): / ./install: line 40: 14981 Killed...
```
---

233
skills/polymarket/SKILL.md Normal file
View File

@ -0,0 +1,233 @@
---
name: polymarket
description: Comprehensive Polymarket skill covering prediction markets, API, trading, market data, and real-time WebSocket data streaming. Build applications with Polymarket services, monitor live trades, and integrate market predictions.
---
# Polymarket Comprehensive Skill
Complete assistance with Polymarket development - covering the full platform (API, trading, market data) and the real-time data streaming client (WebSocket subscriptions for live market activity).
## When to Use This Skill
This skill should be triggered when:
**Platform & API:**
- Working with Polymarket prediction markets
- Using Polymarket API for market data
- Implementing trading strategies
- Building applications with Polymarket services
- Learning Polymarket best practices
**Real-Time Data Streaming:**
- Connecting to Polymarket's WebSocket service
- Building prediction market monitoring tools
- Processing live trades, orders, and market updates
- Monitoring market comments and social reactions
- Tracking RFQ (Request for Quote) activity
- Integrating crypto price feeds
## Quick Reference
### Real-Time Data Client Setup
**Installation:**
```bash
npm install @polymarket/real-time-data-client
```
**Basic Usage:**
```typescript
import { RealTimeDataClient } from "@polymarket/real-time-data-client";
const onMessage = (message: Message): void => {
console.log(message.topic, message.type, message.payload);
};
const onConnect = (client: RealTimeDataClient): void => {
client.subscribe({
subscriptions: [{
topic: "activity",
type: "trades"
}]
});
};
new RealTimeDataClient({ onMessage, onConnect }).connect();
```
### Supported WebSocket Topics
**1. Activity (`activity`)**
- `trades` - Completed trades
- `orders_matched` - Order matching events
- Filters: `{"event_slug":"string"}` OR `{"market_slug":"string"}`
**2. Comments (`comments`)**
- `comment_created`, `comment_removed`
- `reaction_created`, `reaction_removed`
- Filters: `{"parentEntityID":number,"parentEntityType":"Event"}`
**3. RFQ (`rfq`)**
- Request/Quote lifecycle events
- No filters, no auth required
**4. Crypto Prices (`crypto_prices`, `crypto_prices_chainlink`)**
- `update` - Real-time price feeds
- Filters: `{"symbol":"BTC"}` (optional)
**5. CLOB User (`clob_user`)** ⚠️ Requires Auth
- `order` - User's order updates
- `trade` - User's trade executions
**6. CLOB Market (`clob_market`)**
- `price_change` - Price movements
- `agg_orderbook` - Aggregated order book
- `last_trade_price` - Latest prices
- `market_created`, `market_resolved`
### Authentication for User Data
```typescript
client.subscribe({
subscriptions: [{
topic: "clob_user",
type: "*",
clob_auth: {
key: "your-api-key",
secret: "your-api-secret",
passphrase: "your-passphrase"
}
}]
});
```
### Common Use Cases
**Monitor Specific Market:**
```typescript
client.subscribe({
subscriptions: [{
topic: "activity",
type: "trades",
filters: `{"market_slug":"btc-above-100k-2024"}`
}]
});
```
**Track Multiple Markets:**
```typescript
client.subscribe({
subscriptions: [{
topic: "clob_market",
type: "price_change",
filters: `["100","101","102"]`
}]
});
```
**Monitor Event Comments:**
```typescript
client.subscribe({
subscriptions: [{
topic: "comments",
type: "*",
filters: `{"parentEntityID":12345,"parentEntityType":"Event"}`
}]
});
```
## Reference Files
This skill includes comprehensive documentation in `references/`:
**Platform Documentation:**
- **api.md** - Polymarket API documentation
- **getting_started.md** - Getting started guide
- **guides.md** - Development guides
- **learn.md** - Learning resources
- **trading.md** - Trading documentation
- **other.md** - Additional resources
**Real-Time Client:**
- **README.md** - WebSocket client API and examples
- **llms.md** - LLM integration guide
- **llms-full.md** - Complete LLM documentation
Use `view` to read specific reference files for detailed information.
## Key Features
**Platform Capabilities:**
✅ Prediction market creation and resolution
✅ Trading API (REST & WebSocket)
✅ Market data queries
✅ User portfolio management
✅ Event and market discovery
**Real-Time Streaming:**
✅ WebSocket-based persistent connections
✅ Topic-based subscriptions
✅ Dynamic subscription management
✅ Filter support for targeted data
✅ User authentication for private data
✅ TypeScript with full type safety
✅ Initial data dumps on connection
## Best Practices
### WebSocket Connection Management
- Use `onConnect` callback for subscriptions
- Implement reconnection logic for production
- Clean up with `disconnect()` when done
- Handle authentication errors gracefully
### Subscription Strategy
- Use wildcards (`"*"`) sparingly
- Apply filters to reduce data volume
- Unsubscribe from unused streams
- Process messages asynchronously
### Performance
- Consider batching high-frequency data
- Use filters to minimize client processing
- Validate message payloads before use
## Requirements
- **Node.js**: 14+ recommended
- **TypeScript**: Optional but recommended
- **Package Manager**: npm or yarn
## Resources
### Official Links
- **Polymarket Platform**: https://polymarket.com
- **Real-Time Client Repo**: https://github.com/Polymarket/real-time-data-client
- **API Documentation**: See references/api.md
### Working with This Skill
**For Beginners:**
Start with `getting_started.md` for foundational concepts.
**For API Integration:**
Use `api.md` and `trading.md` for REST API details.
**For Real-Time Data:**
Use `README.md` for WebSocket client implementation.
**For LLM Integration:**
Use `llms.md` and `llms-full.md` for AI/ML use cases.
## Notes
- Real-Time Client is TypeScript/JavaScript (not Python)
- Some WebSocket topics require authentication
- Use filters to manage message volume effectively
- All timestamps are Unix timestamps
- Market IDs are strings (e.g., "100", "101")
- Platform documentation covers both REST API and WebSocket usage
---
**This comprehensive skill combines Polymarket platform expertise with real-time data streaming capabilities!**

View File

@ -0,0 +1,396 @@
# Real time data client
This client provides a wrapper to connect to the `real-time-data-streaming` `WebSocket` service.
## How to use it
Here is a quick example about how to connect to the service and start receiving messages (you can find more in the folder `examples/`):
```typescript
import { RealTimeDataClient } from "../src/client";
import { Message } from "../src/model";
const onMessage = (message: Message): void => {
console.log(message.topic, message.type, message.payload);
};
const onConnect = (client: RealTimeDataClient): void => {
// Subscribe to a topic
client.subscribe({
subscriptions: [
{
topic: "comments",
type: "*", // "*"" can be used to connect to all the types of the topic
filters: `{"parentEntityID":100,"parentEntityType":"Event"}`, // empty means no filter
},
],
});
};
new RealTimeDataClient({ onMessage, onConnect }).connect();
```
## How to subscribe and unsubscribe from messages
Once the connection is stablished and you have a `client: RealTimeDataClient` object, you can `subscribe` and `unsubscribe` to many messages streamings using the same connection.
### Subscribe
Subscribe to 'trades' messages from the topic 'activity' and to the all comments messages.
```typescript
client.subscribe({
subscriptions: [
{
topic: "activity",
type: "trades",
},
],
});
client.subscribe({
subscriptions: [
{
topic: "comments",
type: "*", // "*"" can be used to connect to all the types of the topic
},
],
});
```
### Unsubscribe
Unsubscribe from the new trades messages of the topic 'activity'. If 'activity' has more messages types and I used '\*' to connect to all of them, this will only unsubscribe from the type 'trades'.
```typescript
client.subscribe({
subscriptions: [
{
topic: "activity",
type: "trades",
},
],
});
```
### Disconnect
The `client` object provides a method to disconnect from the `WebSocket` server:
```typescript
client.disconnect();
```
## Messages hierarchy
| Topic | Type | Auth | Filters (if it is empty the messages won't be filtered) | Schema | Subscription Handler |
| ------------------------- | ------------------ | -------- | --------------------------------------------------------------- | ----------------------------------- | ----------------------------------------------------------- |
| `activity` | `trades` | - | `{"event_slug":"string"}' OR '{"market_slug":"string"}` | [`Trade`](#trade) | |
| `activity` | `orders_matched` | - | `{"event_slug":"string"}' OR '{"market_slug":"string"}` | [`Trade`](#trade) | |
| `comments` | `comment_created` | - | `{"parentEntityID":number,"parentEntityType":"Event / Series"}` | [`Comment`](#comment) | |
| `comments` | `comment_removed` | - | `{"parentEntityID":number,"parentEntityType":"Event / Series"}` | [`Comment`](#comment) | |
| `comments` | `reaction_created` | - | `{"parentEntityID":number,"parentEntityType":"Event / Series"}` | [`Reaction`](#reaction) | |
| `comments` | `reaction_removed` | - | `{"parentEntityID":number,"parentEntityType":"Event / Series"}` | [`Reaction`](#reaction) | |
| `rfq` | `request_created` | - | - | [`Request`](#request) | |
| `rfq` | `request_edited` | - | - | [`Request`](#request) | |
| `rfq` | `request_canceled` | - | - | [`Request`](#request) | |
| `rfq` | `request_expired` | - | - | [`Request`](#request) | |
| `rfq` | `quote_created` | - | - | [`Quote`](#quote) | |
| `rfq` | `quote_edited` | - | - | [`Quote`](#quote) | |
| `rfq` | `quote_canceled` | - | - | [`Quote`](#quote) | |
| `rfq` | `quote_expired` | - | - | [`Quote`](#quote) | |
| `crypto_prices` | `update` | - | `{"symbol":string}` | [`CryptoPrice`](#cryptoprice) | [`CryptoPriceHistorical`](#initial-data-dump-on-connection) |
| `crypto_prices_chainlink` | `update` | - | `{"symbol":string}` | [`CryptoPrice`](#cryptoprice) | [`CryptoPriceHistorical`](#initial-data-dump-on-connection) |
| `clob_user` | `order` | ClobAuth | - | [`Order`](#order) | |
| `clob_user` | `trade` | ClobAuth | - | [`Trade`](#trade-1) | |
| `clob_market` | `price_change` | - | `["100","200",...]` (filters are mandatory on this one) | [`PriceChanges`](#pricechanges) | |
| `clob_market` | `agg_orderbook` | - | `["100","200",...]` | [`AggOrderbook`](#aggorderbook) | [`AggOrderbook`](#aggorderbook) |
| `clob_market` | `last_trade_price` | - | `["100","200",...]` | [`LastTradePrice`](#lasttradeprice) | |
| `clob_market` | `tick_size_change` | - | `["100","200",...]` | [`TickSizeChange`](#ticksizechange) | |
| `clob_market` | `market_created` | - | - | [`ClobMarket`](#clobmarket) | |
| `clob_market` | `market_resolved` | - | - | [`ClobMarket`](#clobmarket) | |
## Auth
### ClobAuth
```typescript
/**
* API key credentials for CLOB authentication.
*/
export interface ClobApiKeyCreds {
/** API key used for authentication */
key: string;
/** API secret associated with the key */
secret: string;
/** Passphrase required for authentication */
passphrase: string;
}
```
```typescript
client.subscribe({
subscriptions: [
{
topic: "clob_user",
type: "*",
clob_auth: {
key: "xxxxxx-xxxx-xxxxx-xxxx-xxxxxx",
secret: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
passphrase: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
},
},
],
});
```
## Message types
### Activity
#### Trade
| Name | Type | Description |
| ----------------- | ------- | -------------------------------------------------- |
| `asset` | string | ERC1155 token ID of conditional token being traded |
| `bio` | string | Bio of the user of the trade |
| `conditionId` | string | Id of market which is also the CTF condition ID |
| `eventSlug` | string | Slug of the event |
| `icon` | string | URL to the market icon image |
| `name` | string | Name of the user of the trade |
| `outcome` | string | Human readable outcome of the market |
| `outcomeIndex` | integer | Index of the outcome |
| `price` | float | Price of the trade |
| `profileImage` | string | URL to the user profile image |
| `proxyWallet` | string | Address of the user proxy wallet |
| `pseudonym` | string | Pseudonym of the user |
| `side` | string | Side of the trade (`BUY`/`SELL`) |
| `size` | integer | Size of the trade |
| `slug` | string | Slug of the market |
| `timestamp` | integer | Timestamp of the trade |
| `title` | string | Title of the event |
| `transactionHash` | string | Hash of the transaction |
### Comments
#### Comment
| Name | Type | Description |
| ------------------ | ------ | ------------------------------------------- |
| `id` | string | Unique identifier of comment |
| `body` | string | Content of the comment |
| `parentEntityType` | string | Type of the parent entity (Event or Series) |
| `parentEntityID` | number | ID of the parent entity |
| `parentCommentID` | string | ID of the parent comment |
| `userAddress` | string | Address of the user |
| `replyAddress` | string | Address of the reply user |
| `createdAt` | string | Creation timestamp |
| `updatedAt` | string | Last update timestamp |
#### Reaction
| Name | Type | Description |
| -------------- | ------ | ------------------------------ |
| `id` | string | Unique identifier of reaction |
| `commentID` | number | ID of the comment |
| `reactionType` | string | Type of the reaction |
| `icon` | string | Icon representing the reaction |
| `userAddress` | string | Address of the user |
| `createdAt` | string | Creation timestamp |
### RFQ
#### Request
| Name | Type | Description |
| -------------- | ------ | --------------------------------------------------------------- |
| `requestId` | string | Unique identifier for the request |
| `proxyAddress` | string | User proxy address |
| `market` | string | Id of market which is also the CTF condition ID |
| `token` | string | `ERC1155` token ID of conditional token being traded |
| `complement` | string | Complement `ERC1155` token ID of conditional token being traded |
| `state` | string | Current state of the request |
| `side` | string | Indicates buy or sell side |
| `sizeIn` | number | Input size of the request |
| `sizeOut` | number | Output size of the request |
| `price` | number | Price from in/out sizes |
| `expiry` | number | Expiry timestamp (UNIX format) |
#### Quote
| Name | Type | Description |
| -------------- | ------ | --------------------------------------------------------------- |
| `quoteId` | string | Unique identifier for the quote |
| `requestId` | string | Associated request identifier |
| `proxyAddress` | string | User proxy address |
| `token` | string | `ERC1155` token ID of conditional token being traded |
| `state` | string | Current state of the quote |
| `side` | string | Indicates buy or sell side |
| `sizeIn` | number | Input size of the quote |
| `sizeOut` | number | Output size of the quote |
| `sizeOut` | number | Output size of the request |
| `condition` | string | Id of market which is also the CTF condition ID |
| `complement` | string | Complement `ERC1155` token ID of conditional token being traded |
| `expiry` | number | Expiry timestamp (UNIX format) |
### CryptoPrice
| Name | Type | Description |
| ----------- | ------ | ---------------------------------------- |
| `symbol` | string | Symbol of the asset |
| `timestamp` | number | Timestamp in milliseconds for the update |
| `value` | number | Value at the time of update |
#### Filters
- `{"symbol":"btcusdt"}`
- `{"symbol":"ethusdt"}`
- `{"symbol":"xrpusdt"}`
- `{"symbol":"solusdt"}`
#### Initial data dump on connection
When the connection is stablished, if a `filter` is used, the server will dump an initial snapshoot of recent data
| Name | Type | Description |
| ------ | ------ | ---------------------------------------------------------------- |
| symbol | string | Symbol of the asset |
| data | array | Array of price data objects, each containing timestamp and value |
### CLOB User
#### Order
| Name | Type | Description |
| --------------- | ------------------ | --------------------------------------------------------- |
| `asset_id` | string | Order's `ERC1155` token ID of conditional token |
| `created_at` | string (timestamp) | Order's creation UNIX timestamp |
| `expiration` | string (timestamp) | Order's expiration UNIX timestamp |
| `id` | string | Unique order hash identifier |
| `maker_address` | string | Makers address (funder) |
| `market` | string | Condition ID or market identifier |
| `order_type` | string | Type of order: `GTC`, `GTD`, `FOK`, `FAK` |
| `original_size` | string | Original size of the order at placement |
| `outcome` | string | Order outcome: `YES` / `NO` |
| `owner` | string | UUID of the order owner |
| `price` | string | Order price (e.g., in decimals like `0.5`) |
| `side` | string | Side of the trade: `BUY` or `SELL` |
| `size_matched` | string | Amount of order that has been matched |
| `status` | string | Status of the order (e.g., `MATCHED`) |
| `type` | string | Type of update: `PLACEMENT`, `CANCELLATION`, `FILL`, etc. |
#### Trade
| Name | Type | Description |
| ------------------ | ------------------ | ----------------------------------------------------------------- |
| `asset_id` | string | `ERC1155` token ID of the conditional token involved in the trade |
| `fee_rate_bps` | string | Fee rate in basis points (bps) |
| `id` | string | Unique identifier for the match record |
| `last_update` | string (timestamp) | Last update timestamp (UNIX) |
| `maker_address` | string | Makers address |
| `maker_orders` | array | List of maker orders (see nested schema below) |
| `market` | string | Condition ID or market identifier |
| `match_time` | string (timestamp) | Match execution timestamp (UNIX) |
| `outcome` | string | Outcome of the market: `YES` / `NO` |
| `owner` | string | UUID of the taker (owner of the matched order) |
| `price` | string | Matched price (in decimal format, e.g., `0.5`) |
| `side` | string | Taker side of the trade: `BUY` or `SELL` |
| `size` | string | Total matched size |
| `status` | string | Status of the match: e.g., `MINED` |
| `taker_order_id` | string | ID of the taker's order |
| `transaction_hash` | string | Transaction hash where the match was settled |
##### `maker_orders`
| Name | Type | Description |
| ---------------- | ------ | ---------------------------------------------------------------- |
| `asset_id` | string | `ERC1155` token ID of the conditional token of the maker's order |
| `fee_rate_bps` | string | Maker's fee rate in basis points |
| `maker_address` | string | Makers address |
| `matched_amount` | string | Amount matched from the maker's order |
| `order_id` | string | ID of the maker's order |
| `outcome` | string | Outcome targeted by the maker's order (`YES` / `NO`) |
| `owner` | string | UUID of the maker |
| `price` | string | Order price |
| `side` | string | Side of the maker: `BUY` or `SELL` |
### CLOB market
#### PriceChanges
| Name | Type | Description |
| ------------------- | ------------------ | --------------------------------------------------------- |
| `m` (market) | string | Condition ID |
| `pc` (price change) | array | Price changes by book |
| `t` (timestamp) | string (timestamp) | Timestamp in milliseconds since epoch (UNIX time \* 1000) |
##### PriceChange
NOTE: Filters are mandatory for this topic/type. Example: `["100","200",...]` (collection of token ids)
| Name | Type | Description |
| --------------- | ------ | --------------------------------------------------------------- |
| `a` (asset_id) | string | Asset identifier |
| `h` (hash) | string | Unique hash ID of the book snapshot |
| `p` (price) | string | Price quoted (e.g., `0.5`) |
| `s` (side) | string | Side of the quote: `BUY` or `SELL` |
| `si` (size) | string | Size or volume available at the quoted price (e.g., `0`, `100`) |
| `ba` (best_ask) | string | Best ask price |
| `bb` (best_bid) | string | Best bid price |
#### AggOrderbook
| Name | Type | Description |
| ---------------- | ------------------ | ----------------------------------------------------------------------- |
| `asks` | array | List of ask aggregated orders (sell side), each with `price` and `size` |
| `asset_id` | string | Asset Id identifier |
| `bids` | array | List of aggregated bid orders (buy side), each with `price` and `size` |
| `hash` | string | Unique hash ID for this orderbook snapshot |
| `market` | string | Market or condition ID |
| `min_order_size` | string | Minimum allowed order size |
| `neg_risk` | boolean | NegRisk or not |
| `tick_size` | string | Minimum tick size |
| `timestamp` | string (timestamp) | Timestamp in milliseconds since epoch (UNIX time \* 1000) |
##### `asks`/`bids` scheema
| Name | Type | Description |
| ------- | ------ | ------------------ |
| `price` | string | Price level |
| `size` | string | Size at that price |
##### Initial data dump on connection
When the connection is stablished, if a `filter` is used, the server will dump an initial snapshoot of recent data
#### LastTradePrice
| Name | Type | Description |
| -------------- | ------ | ---------------------------------- |
| `asset_id` | string | Asset Id identifier |
| `fee_rate_bps` | string | Fee rate in basis points (bps) |
| `market` | string | Market or condition ID |
| `price` | string | Trade price (e.g., `0.5`) |
| `side` | string | Side of the order: `BUY` or `SELL` |
| `size` | string | Size of the trade |
#### TickSizeChange
| Name | Type | Description |
| --------------- | ------ | ------------------------------------ |
| `market` | string | Market or condition ID |
| `asset_id` | string | Array of two `ERC1155` asset ID |
| `old_tick_size` | string | Previous tick size before the change |
| `new_tick_size` | string | Updated tick size after the change |
#### ClobMarket
| Name | Type | Description |
| ---------------- | --------- | ------------------------------------------------------------------ |
| `market` | string | Market or condition ID |
| `asset_ids` | [2]string | Array of two `ERC1155` asset ID identifiers associated with market |
| `min_order_size` | string | Minimum size allowed for an order |
| `tick_size` | string | Minimum allowable price increment |
| `neg_risk` | boolean | Indicates if the market is negative risk |

View File

@ -0,0 +1,655 @@
# Polymarket - Api
**Pages:** 46
---
## Get sports metadata information
**URL:** llms-txt#get-sports-metadata-information
Source: https://docs.polymarket.com/api-reference/sports/get-sports-metadata-information
api-reference/gamma-openapi.json get /sports
Retrieves metadata for various sports including images, resolution sources, ordering preferences, tags, and series information. This endpoint provides comprehensive sport configuration data used throughout the platform.
---
## Get user activity
**URL:** llms-txt#get-user-activity
Source: https://docs.polymarket.com/api-reference/core/get-user-activity
api-reference/data-api-openapi.yaml get /activity
Returns on-chain activity for a user.
---
## Get comments by comment id
**URL:** llms-txt#get-comments-by-comment-id
Source: https://docs.polymarket.com/api-reference/comments/get-comments-by-comment-id
api-reference/gamma-openapi.json get /comments/{id}
---
## Get open interest
**URL:** llms-txt#get-open-interest
Source: https://docs.polymarket.com/api-reference/misc/get-open-interest
api-reference/data-api-openapi.yaml get /oi
---
## Get total value of a user's positions
**URL:** llms-txt#get-total-value-of-a-user's-positions
Source: https://docs.polymarket.com/api-reference/core/get-total-value-of-a-users-positions
api-reference/data-api-openapi.yaml get /value
---
## Get related tags (relationships) by tag id
**URL:** llms-txt#get-related-tags-(relationships)-by-tag-id
Source: https://docs.polymarket.com/api-reference/tags/get-related-tags-relationships-by-tag-id
api-reference/gamma-openapi.json get /tags/{id}/related-tags
---
## List events
**URL:** llms-txt#list-events
Source: https://docs.polymarket.com/api-reference/events/list-events
api-reference/gamma-openapi.json get /events
---
## Get tag by id
**URL:** llms-txt#get-tag-by-id
Source: https://docs.polymarket.com/api-reference/tags/get-tag-by-id
api-reference/gamma-openapi.json get /tags/{id}
---
## Get market by id
**URL:** llms-txt#get-market-by-id
Source: https://docs.polymarket.com/api-reference/markets/get-market-by-id
api-reference/gamma-openapi.json get /markets/{id}
---
## WSS Authentication
**URL:** llms-txt#wss-authentication
Source: https://docs.polymarket.com/developers/CLOB/websocket/wss-auth
<Tip> Only connections to `user` channel require authentication. </Tip>
| Field | Optional | Description |
| ---------- | -------- | ------------------------------------- |
| apikey | yes | Polygon account's CLOB api key |
| secret | yes | Polygon account's CLOB api secret |
| passphrase | yes | Polygon account's CLOB api passphrase |
---
## Get tags related to a tag slug
**URL:** llms-txt#get-tags-related-to-a-tag-slug
Source: https://docs.polymarket.com/api-reference/tags/get-tags-related-to-a-tag-slug
api-reference/gamma-openapi.json get /tags/slug/{slug}/related-tags/tags
---
## Get related tags (relationships) by tag slug
**URL:** llms-txt#get-related-tags-(relationships)-by-tag-slug
Source: https://docs.polymarket.com/api-reference/tags/get-related-tags-relationships-by-tag-slug
api-reference/gamma-openapi.json get /tags/slug/{slug}/related-tags
---
## Get total markets a user has traded
**URL:** llms-txt#get-total-markets-a-user-has-traded
Source: https://docs.polymarket.com/api-reference/misc/get-total-markets-a-user-has-traded
api-reference/data-api-openapi.yaml get /traded
---
## Get market by slug
**URL:** llms-txt#get-market-by-slug
Source: https://docs.polymarket.com/api-reference/markets/get-market-by-slug
api-reference/gamma-openapi.json get /markets/slug/{slug}
---
## List tags
**URL:** llms-txt#list-tags
Source: https://docs.polymarket.com/api-reference/tags/list-tags
api-reference/gamma-openapi.json get /tags
---
## Get market price
**URL:** llms-txt#get-market-price
Source: https://docs.polymarket.com/api-reference/pricing/get-market-price
api-reference/clob-subset-openapi.yaml get /price
Retrieves the market price for a specific token and side
---
## Next page of markets with tag filtering
**URL:** llms-txt#next-page-of-markets-with-tag-filtering
**Contents:**
- Best Practices
- Related Endpoints
curl "https://gamma-api.polymarket.com/markets?tag_id=100381&closed=false&limit=25&offset=25"
```
1. **For Individual Markets:** Always use the slug method for best performance
2. **For Category Browsing:** Use tag filtering to reduce API calls
3. **For Complete Market Discovery:** Use the events endpoint with pagination
4. **Always Include `closed=false`:** Unless you specifically need historical data
5. **Implement Rate Limiting:** Respect API limits for production applications
* [Get Markets](/developers/gamma-markets-api/get-markets) - Full markets endpoint documentation
* [Get Events](/developers/gamma-markets-api/get-events) - Full events endpoint documentation
* [Search Markets](/developers/gamma-markets-api/get-public-search) - Search functionality
---
## API Key Operations
**URL:** llms-txt#api-key-operations
**Contents:**
- Create API Key
- Derive API Key
- Get API Keys
- Delete API Key
- Access Status
- Get Closed Only Mode Status
<Tip>This endpoint requires an **L1 Header**.</Tip>
Create new API key credentials for a user.
<Tip>This endpoint requires an **L1 Header**. </Tip>
Derive an existing API key for an address and nonce.
<Tip>This endpoint requires an **L2 Header**. </Tip>
Retrieve all API keys associated with a Polygon address.
<Tip>This endpoint requires an **L2 Header**.</Tip>
Delete an API key used to authenticate a request.
Check the value of `cert_required` by signer address.
## Get Closed Only Mode Status
<Tip>This endpoint requires an **L2 Header**.</Tip>
Retrieve the closed-only mode flag status.
**Examples:**
Example 1 (unknown):
```unknown
***
## Derive API Key
<Tip>This endpoint requires an **L1 Header**. </Tip>
Derive an existing API key for an address and nonce.
**HTTP Request:**
```
Example 2 (unknown):
```unknown
***
## Get API Keys
<Tip>This endpoint requires an **L2 Header**. </Tip>
Retrieve all API keys associated with a Polygon address.
**HTTP Request:**
```
Example 3 (unknown):
```unknown
***
## Delete API Key
<Tip>This endpoint requires an **L2 Header**.</Tip>
Delete an API key used to authenticate a request.
**HTTP Request:**
```
Example 4 (unknown):
```unknown
***
## Access Status
Check the value of `cert_required` by signer address.
**HTTP Request:**
```
---
## List comments
**URL:** llms-txt#list-comments
Source: https://docs.polymarket.com/api-reference/comments/list-comments
api-reference/gamma-openapi.json get /comments
---
## Get trades for a user or markets
**URL:** llms-txt#get-trades-for-a-user-or-markets
Source: https://docs.polymarket.com/api-reference/core/get-trades-for-a-user-or-markets
api-reference/data-api-openapi.yaml get /trades
---
## Get event tags
**URL:** llms-txt#get-event-tags
Source: https://docs.polymarket.com/api-reference/events/get-event-tags
api-reference/gamma-openapi.json get /events/{id}/tags
---
## Create and Place an Order
**URL:** llms-txt#create-and-place-an-order
**Contents:**
- Request Payload Parameters
- Order types
- Response Format
- Insert Error Messages
- Insert Statuses
<Tip> This endpoint requires a L2 Header </Tip>
Create and place an order using the Polymarket CLOB API clients. All orders are represented as "limit" orders, but "market" orders are also supported. To place a market order, simply ensure your price is marketable against current resting limit orders, which are executed on input at the best price.
`POST /<clob-endpoint>/order`
### Request Payload Parameters
| Name | Required | Type | Description |
| --------- | -------- | ------ | -------------------------------- |
| order | yes | Order | signed object |
| owner | yes | string | api key of order owner |
| orderType | yes | string | order type ("FOK", "GTC", "GTD") |
An `order` object is the form:
| Name | Required | Type | Description |
| ------------- | -------- | ------- | -------------------------------------------------- |
| salt | yes | integer | random salt used to create unique order |
| maker | yes | string | maker address (funder) |
| signer | yes | string | signing address |
| taker | yes | string | taker address (operator) |
| tokenId | yes | string | ERC1155 token ID of conditional token being traded |
| makerAmount | yes | string | maximum amount maker is willing to spend |
| takerAmount | yes | string | minimum amount taker will pay the maker in return |
| expiration | yes | string | unix expiration timestamp |
| nonce | yes | string | maker's exchange nonce of the order is associated |
| feeRateBps | yes | string | fee rate basis points as required by the operator |
| side | yes | string | buy or sell enum index |
| signatureType | yes | integer | signature type enum index |
| signature | yes | string | hex encoded signature |
* **FOK**: A Fill-Or-Kill order is an market order to buy (in dollars) or sell (in shares) shares that must be executed immediately in its entirety; otherwise, the entire order will be cancelled.
* **FAK**: A Fill-And-Kill order is a market order to buy (in dollars) or sell (in shares) that will be executed immediately for as many shares as are available; any portion not filled at once is cancelled.
* **GTC**: A Good-Til-Cancelled order is a limit order that is active until it is fulfilled or cancelled.
* **GTD**: A Good-Til-Date order is a type of order that is active until its specified date (UTC seconds timestamp), unless it has already been fulfilled or cancelled. There is a security threshold of one minute. If the order needs to expire in 90 seconds the correct expiration value is: now + 1 minute + 30 seconds
| Name | Type | Description |
| ----------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| success | boolean | boolean indicating if server-side err (`success = false`) -> server-side error |
| errorMsg | string | error message in case of unsuccessful placement (in case `success = false`, e.g. `client-side error`, the reason is in `errorMsg`) |
| orderId | string | id of order |
| orderHashes | string\[] | hash of settlement transaction order was marketable and triggered a match |
### Insert Error Messages
If the `errorMsg` field of the response object from placement is not an empty string, the order was not able to be immediately placed. This might be because of a delay or because of a failure. If the `success` is not `true`, then there was an issue placing the order. The following `errorMessages` are possible:
| Error | Success | Message | Description |
| ------------------------------------ | ------- | --------------------------------------------------------------------------------------- | --------------------------------------------------------------------- |
| INVALID\_ORDER\_MIN\_TICK\_SIZE | yes | order is invalid. Price breaks minimum tick size rules | order price isn't accurate to correct tick sizing |
| INVALID\_ORDER\_MIN\_SIZE | yes | order is invalid. Size lower than the minimum | order size must meet min size threshold requirement |
| INVALID\_ORDER\_DUPLICATED | yes | order is invalid. Duplicated. Same order has already been placed, can't be placed again | |
| INVALID\_ORDER\_NOT\_ENOUGH\_BALANCE | yes | not enough balance / allowance | funder address doesn't have sufficient balance or allowance for order |
| INVALID\_ORDER\_EXPIRATION | yes | invalid expiration | expiration field expresses a time before now |
| INVALID\_ORDER\_ERROR | yes | could not insert order | system error while inserting order |
| EXECUTION\_ERROR | yes | could not run the execution | system error while attempting to execute trade |
| ORDER\_DELAYED | no | order match delayed due to market conditions | order placement delayed |
| DELAYING\_ORDER\_ERROR | yes | error delaying the order | system error while delaying order |
| FOK\_ORDER\_NOT\_FILLED\_ERROR | yes | order couldn't be fully filled, FOK orders are fully filled/killed | FOK order not fully filled so can't be placed |
| MARKET\_NOT\_READY | no | the market is not yet ready to process new orders | system not accepting orders for market yet |
When placing an order, a status field is included. The status field provides additional information regarding the order's state as a result of the placement. Possible values include:
| Status | Description |
| --------- | ------------------------------------------------------------ |
| matched | order placed and matched with an existing resting order |
| live | order placed and resting on the book |
| delayed | order marketable, but subject to matching delay |
| unmatched | order marketable, but failure delaying, placement successful |
**Examples:**
Example 1 (unknown):
```unknown
```
---
## Get series by id
**URL:** llms-txt#get-series-by-id
Source: https://docs.polymarket.com/api-reference/series/get-series-by-id
api-reference/gamma-openapi.json get /series/{id}
---
## List markets
**URL:** llms-txt#list-markets
Source: https://docs.polymarket.com/api-reference/markets/list-markets
api-reference/gamma-openapi.json get /markets
---
## Get bid-ask spreads
**URL:** llms-txt#get-bid-ask-spreads
Source: https://docs.polymarket.com/api-reference/spreads/get-bid-ask-spreads
api-reference/clob-subset-openapi.yaml post /spreads
Retrieves bid-ask spreads for multiple tokens
---
## List series
**URL:** llms-txt#list-series
Source: https://docs.polymarket.com/api-reference/series/list-series
api-reference/gamma-openapi.json get /series
---
## Search markets, events, and profiles
**URL:** llms-txt#search-markets,-events,-and-profiles
Source: https://docs.polymarket.com/api-reference/search/search-markets-events-and-profiles
api-reference/gamma-openapi.json get /public-search
---
## Get multiple order books summaries by request
**URL:** llms-txt#get-multiple-order-books-summaries-by-request
Source: https://docs.polymarket.com/api-reference/orderbook/get-multiple-order-books-summaries-by-request
api-reference/clob-subset-openapi.yaml post /books
Retrieves order book summaries for specified tokens via POST request
---
## Get multiple market prices
**URL:** llms-txt#get-multiple-market-prices
Source: https://docs.polymarket.com/api-reference/pricing/get-multiple-market-prices
api-reference/clob-subset-openapi.yaml get /prices
Retrieves market prices for multiple tokens and sides
---
## Get midpoint price
**URL:** llms-txt#get-midpoint-price
Source: https://docs.polymarket.com/api-reference/pricing/get-midpoint-price
api-reference/clob-subset-openapi.yaml get /midpoint
Retrieves the midpoint price for a specific token
---
## List teams
**URL:** llms-txt#list-teams
Source: https://docs.polymarket.com/api-reference/sports/list-teams
api-reference/gamma-openapi.json get /teams
---
## Get current positions for a user
**URL:** llms-txt#get-current-positions-for-a-user
Source: https://docs.polymarket.com/api-reference/core/get-current-positions-for-a-user
api-reference/data-api-openapi.yaml get /positions
Returns positions filtered by user and optional filters.
---
## Health check
**URL:** llms-txt#health-check
Source: https://docs.polymarket.com/api-reference/health/health-check
api-reference/data-api-openapi.yaml get /
---
## Get tags related to a tag id
**URL:** llms-txt#get-tags-related-to-a-tag-id
Source: https://docs.polymarket.com/api-reference/tags/get-tags-related-to-a-tag-id
api-reference/gamma-openapi.json get /tags/{id}/related-tags/tags
---
## Get multiple market prices by request
**URL:** llms-txt#get-multiple-market-prices-by-request
Source: https://docs.polymarket.com/api-reference/pricing/get-multiple-market-prices-by-request
api-reference/clob-subset-openapi.yaml post /prices
Retrieves market prices for specified tokens and sides via POST request
---
## Get market tags by id
**URL:** llms-txt#get-market-tags-by-id
Source: https://docs.polymarket.com/api-reference/markets/get-market-tags-by-id
api-reference/gamma-openapi.json get /markets/{id}/tags
---
## Get closed positions for a user
**URL:** llms-txt#get-closed-positions-for-a-user
Source: https://docs.polymarket.com/api-reference/core/get-closed-positions-for-a-user
api-reference/data-api-openapi.yaml get /closed-positions
Fetches closed positions for a user(address)
---
## Get event by slug
**URL:** llms-txt#get-event-by-slug
Source: https://docs.polymarket.com/api-reference/events/get-event-by-slug
api-reference/gamma-openapi.json get /events/slug/{slug}
---
## Get live volume for an event
**URL:** llms-txt#get-live-volume-for-an-event
Source: https://docs.polymarket.com/api-reference/misc/get-live-volume-for-an-event
api-reference/data-api-openapi.yaml get /live-volume
---
## Get tag by slug
**URL:** llms-txt#get-tag-by-slug
Source: https://docs.polymarket.com/api-reference/tags/get-tag-by-slug
api-reference/gamma-openapi.json get /tags/slug/{slug}
---
## Get comments by user address
**URL:** llms-txt#get-comments-by-user-address
Source: https://docs.polymarket.com/api-reference/comments/get-comments-by-user-address
api-reference/gamma-openapi.json get /comments/user_address/{user_address}
---
## Get order book summary
**URL:** llms-txt#get-order-book-summary
Source: https://docs.polymarket.com/api-reference/orderbook/get-order-book-summary
api-reference/clob-subset-openapi.yaml get /book
Retrieves the order book summary for a specific token
---
## Endpoint
**URL:** llms-txt#endpoint
[https://gamma-api.polymarket.com](https://gamma-api.polymarket.com)
---
## Get top holders for markets
**URL:** llms-txt#get-top-holders-for-markets
Source: https://docs.polymarket.com/api-reference/core/get-top-holders-for-markets
api-reference/data-api-openapi.yaml get /holders
---
## Get event by id
**URL:** llms-txt#get-event-by-id
Source: https://docs.polymarket.com/api-reference/events/get-event-by-id
api-reference/gamma-openapi.json get /events/{id}
---
## Get price history for a traded token
**URL:** llms-txt#get-price-history-for-a-traded-token
Source: https://docs.polymarket.com/api-reference/pricing/get-price-history-for-a-traded-token
api-reference/clob-subset-openapi.yaml get /prices-history
Fetches historical price data for a specified market token
---

View File

@ -0,0 +1,370 @@
# Polymarket - Getting Started
**Pages:** 8
---
## CLOB Introduction
**URL:** llms-txt#clob-introduction
**Contents:**
- System
- API
- Security
- Fees
- Schedule
- Overview
- Additional Resources
Source: https://docs.polymarket.com/developers/CLOB/introduction
Welcome to the Polymarket Order Book API! This documentation provides overviews, explanations, examples, and annotations to simplify interaction with the order book. The following sections detail the Polymarket Order Book and the API usage.
Polymarket's Order Book, or CLOB (Central Limit Order Book), is hybrid-decentralized. It includes an operator for off-chain matching/ordering, with settlement executed on-chain, non-custodially, via signed order messages.
The exchange uses a custom Exchange contract facilitating atomic swaps between binary Outcome Tokens (CTF ERC1155 assets and ERC20 PToken assets) and collateral assets (ERC20), following signed limit orders. Designed for binary markets, the contract enables complementary tokens to match across a unified order book.
Orders are EIP712-signed structured data. Matched orders have one maker and one or more takers, with price improvements benefiting the taker. The operator handles off-chain order management and submits matched trades to the blockchain for on-chain execution.
The Polymarket Order Book API enables market makers and traders to programmatically manage market orders. Orders of any amount can be created, listed, fetched, or read from the market order books. Data includes all available markets, market prices, and order history via REST and WebSocket endpoints.
Polymarket's Exchange contract has been audited by Chainsecurity ([View Audit](https://github.com/Polymarket/ctf-exchange/blob/main/audit/ChainSecurity_Polymarket_Exchange_audit.pdf)).
The operator's privileges are limited to order matching, non-censorship, and ensuring correct ordering. Operators can't set prices or execute unauthorized trades. Users can cancel orders on-chain independently if trust issues arise.
| Volume Level | Maker Fee Base Rate (bps) | Taker Fee Base Rate (bps) |
| ------------ | ------------------------- | ------------------------- |
| >0 USDC | 0 | 0 |
Fees apply symmetrically in output assets (proceeds). This symmetry ensures fairness and market integrity. Fees are calculated differently depending on whether you are buying or selling:
* **Selling outcome tokens (base) for collateral (quote):**
$$
feeQuote = baseRate \times \min(price, 1 - price) \times size
$$
* **Buying outcome tokens (base) with collateral (quote):**
$$
feeBase = baseRate \times \min(price, 1 - price) \times \frac{size}{price}
$$
## Additional Resources
* [Exchange contract source code](https://github.com/Polymarket/ctf-exchange/tree/main/src)
* [Exchange contract documentation](https://github.com/Polymarket/ctf-exchange/blob/main/docs/Overview.md)
---
## API Rate Limits
**URL:** llms-txt#api-rate-limits
**Contents:**
- How Rate Limiting Works
- General Rate Limits
- Data API Rate Limits
- GAMMA API Rate Limits
- CLOB API Rate Limits
- General CLOB Endpoints
- CLOB Market Data
- CLOB Ledger Endpoints
- CLOB Markets & Pricing
- CLOB Authentication
Source: https://docs.polymarket.com/quickstart/introduction/rate-limits
## How Rate Limiting Works
All rate limits are enforced using Cloudflare's throttling system. When you exceed the maximum configured rate for any endpoint, requests are throttled rather than immediately rejected. This means:
* **Throttling**: Requests over the limit are delayed/queued rather than dropped
* **Burst Allowances**: Some endpoints allow short bursts above the sustained rate
* **Time Windows**: Limits reset based on sliding time windows (e.g., per 10 seconds, per minute)
## General Rate Limits
| Endpoint | Limit | Notes |
| --------------------- | ------------------- | -------------------------------------------------- |
| General Rate Limiting | 5000 requests / 10s | Throttle requests over the maximum configured rate |
| "OK" Endpoint | 50 requests / 10s | Throttle requests over the maximum configured rate |
## Data API Rate Limits
| Endpoint | Limit | Notes |
| ---------------------- | ------------------------ | -------------------------------------------------- |
| Data API (General) | 200 requests / 10s | Throttle requests over the maximum configured rate |
| Data API (Alternative) | 1200 requests / 1 minute | 10 minutes block on violation |
| Data API `/trades` | 75 requests / 10s | Throttle requests over the maximum configured rate |
| Data API "OK" Endpoint | 10 requests / 10s | Throttle requests over the maximum configured rate |
## GAMMA API Rate Limits
| Endpoint | Limit | Notes |
| -------------------------------- | ------------------ | -------------------------------------------------- |
| GAMMA (General) | 750 requests / 10s | Throttle requests over the maximum configured rate |
| GAMMA Get Comments | 100 requests / 10s | Throttle requests over the maximum configured rate |
| GAMMA `/events` | 100 requests / 10s | Throttle requests over the maximum configured rate |
| GAMMA `/markets` | 125 requests / 10s | Throttle requests over the maximum configured rate |
| GAMMA `/markets` /events listing | 100 requests / 10s | Throttle requests over the maximum configured rate |
| GAMMA Tags | 100 requests / 10s | Throttle requests over the maximum configured rate |
| GAMMA Search | 300 requests / 10s | Throttle requests over the maximum configured rate |
## CLOB API Rate Limits
### General CLOB Endpoints
| Endpoint | Limit | Notes |
| ----------------------------- | ------------------- | -------------------------------------------------- |
| CLOB (General) | 5000 requests / 10s | Throttle requests over the maximum configured rate |
| CLOB GET Balance Allowance | 125 requests / 10s | Throttle requests over the maximum configured rate |
| CLOB UPDATE Balance Allowance | 20 requests / 10s | Throttle requests over the maximum configured rate |
| Endpoint | Limit | Notes |
| ----------------- | ------------------ | -------------------------------------------------- |
| CLOB `/book` | 200 requests / 10s | Throttle requests over the maximum configured rate |
| CLOB `/books` | 80 requests / 10s | Throttle requests over the maximum configured rate |
| CLOB `/price` | 200 requests / 10s | Throttle requests over the maximum configured rate |
| CLOB `/prices` | 80 requests / 10s | Throttle requests over the maximum configured rate |
| CLOB `/midprice` | 200 requests / 10s | Throttle requests over the maximum configured rate |
| CLOB `/midprices` | 80 requests / 10s | Throttle requests over the maximum configured rate |
### CLOB Ledger Endpoints
| Endpoint | Limit | Notes |
| ----------------------------------------------------------- | ------------------ | -------------------------------------------------- |
| CLOB Ledger (`/trades` `/orders` `/notifications` `/order`) | 300 requests / 10s | Throttle requests over the maximum configured rate |
| CLOB Ledger `/data/orders` | 150 requests / 10s | Throttle requests over the maximum configured rate |
| CLOB Ledger `/data/trades` | 150 requests / 10s | Throttle requests over the maximum configured rate |
| CLOB `/notifications` | 125 requests / 10s | Throttle requests over the maximum configured rate |
### CLOB Markets & Pricing
| Endpoint | Limit | Notes |
| ----------------------- | ------------------ | -------------------------------------------------- |
| CLOB Price History | 100 requests / 10s | Throttle requests over the maximum configured rate |
| CLOB Markets | 250 requests / 10s | Throttle requests over the maximum configured rate |
| CLOB Market Tick Size | 50 requests / 10s | Throttle requests over the maximum configured rate |
| CLOB `markets/0x` | 50 requests / 10s | Throttle requests over the maximum configured rate |
| CLOB `/markets` listing | 100 requests / 10s | Throttle requests over the maximum configured rate |
### CLOB Authentication
| Endpoint | Limit | Notes |
| ------------- | ----------------- | -------------------------------------------------- |
| CLOB API Keys | 50 requests / 10s | Throttle requests over the maximum configured rate |
### CLOB Trading Endpoints
| Endpoint | Limit | Notes |
| ----------------------------------- | ---------------------------------- | ---------------------------------------------------------- |
| CLOB POST `/order` | 2400 requests / 10s (240/s) | BURST - Throttle requests over the maximum configured rate |
| CLOB POST `/order` | 24000 requests / 10 minutes (40/s) | Throttle requests over the maximum configured rate |
| CLOB DELETE `/order` | 2400 requests / 10s (240/s) | BURST - Throttle requests over the maximum configured rate |
| CLOB DELETE `/order` | 24000 requests / 10 minutes (40/s) | Throttle requests over the maximum configured rate |
| CLOB POST `/orders` | 800 requests / 10s (80/s) | BURST - Throttle requests over the maximum configured rate |
| CLOB POST `/orders` | 12000 requests / 10 minutes (20/s) | Throttle requests over the maximum configured rate |
| CLOB DELETE `/orders` | 800 requests / 10s (80/s) | BURST - Throttle requests over the maximum configured rate |
| CLOB DELETE `/orders` | 12000 requests / 10 minutes (20/s) | Throttle requests over the maximum configured rate |
| CLOB DELETE `/cancel-all` | 200 requests / 10s (20/s) | BURST - Throttle requests over the maximum configured rate |
| CLOB DELETE `/cancel-all` | 3000 requests / 10 minutes (5/s) | Throttle requests over the maximum configured rate |
| CLOB DELETE `/cancel-market-orders` | 800 requests / 10s (80/s) | BURST - Throttle requests over the maximum configured rate |
| CLOB DELETE `/cancel-market-orders` | 12000 requests / 10 minutes (20/s) | Throttle requests over the maximum configured rate |
## Other API Rate Limits
| Endpoint | Limit | Notes |
| ----------------- | ---------------------- | -------------------------------------------------- |
| RELAYER `/submit` | 15 requests / 1 minute | Throttle requests over the maximum configured rate |
| User PNL API | 100 requests / 10s | Throttle requests over the maximum configured rate |
---
## Glossary
**URL:** llms-txt#glossary
Source: https://docs.polymarket.com/quickstart/introduction/definitions
| Term | Definition |
| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Token** | A token represents a stake in a specific Yes/No outcome in a Market. The price of a token can fluctuate between $0 - $1 based on the market belief in the outcome. When a market resolves, the token associated with the correct prediction can be redeemed for \$1 USDC. This is also sometimes called an *Asset Id* |
| **Market** | A single event outcome. Corresponds to a pair of CLOB token IDs(Yes/No), a market address, a question ID and a condition ID. |
| **Event** | A collection of related markets grouped under a common topic or theme. |
| **SLUG** | A human readable identification for a market or event. Can be found in the URL of any Polymarket Market or Event. You can use this slug to find more detailed information about a market or event by using it as a parameter in the [Get Events](/developers/gamma-markets-api/get-events) or [Get Markets](/developers/gamma-markets-api/get-markets) endpoints. |
| **Negative Risk (negrisk)** | A group of Markets(Event) in which only one Market can resolve as yes. For more detail see [Negrisk Details](https://docs.polymarket.com/developers/neg-risk/overview) |
| **Central Limit Order Book** | The off-chain order matching system. This is where you place resting orders and market orders are matched with existing orders before being sent on-chain. |
| **Polygon Network** | A scalable, multi-chain blockchain platform used by Polymarket to facilitate on-chain activities(contract creation, token transfers, etc) |
---
## WSS Quickstart
**URL:** llms-txt#wss-quickstart
**Contents:**
- Getting your API Keys
- Using those keys to connect to the Market or User Websocket
Source: https://docs.polymarket.com/quickstart/websocket/WSS-Quickstart
The following code samples and explanation will show you how to subsribe to the Marker and User channels of the Websocket.
You'll need your API keys to do this so we'll start with that.
## Getting your API Keys
## Using those keys to connect to the Market or User Websocket
<CodeGroup>
</CodeGroup>
**Examples:**
Example 1 (unknown):
```unknown
```
Example 2 (unknown):
```unknown
</CodeGroup>
## Using those keys to connect to the Market or User Websocket
<CodeGroup>
```
---
## Does Polymarket have an API?
**URL:** llms-txt#does-polymarket-have-an-api?
Source: https://docs.polymarket.com/polymarket-learn/FAQ/does-polymarket-have-an-api
Getting data from Polymarket
Yes! Developers can find all the information they need for interacting with Polymarket. This includes [documentation on market discovery, resolution, trading etc.](/quickstart/introduction/main)
Whether you are an academic researcher a market maker or an indepedent developer, this documentation should provide you what you need to get started. All the code you find linked here and on our [GitHub](https://github.com/polymarket) is open source and free to use.
<Tip>
If you have any questions please join our [Discord](https://discord.com/invite/polymarket) and direct your questions to the #devs channel.
</Tip>
---
## Developer Quickstart
**URL:** llms-txt#developer-quickstart
Source: https://docs.polymarket.com/quickstart/introduction/main
This section of the documentation will provide all the essential resources to help you perform basic trading actions on the Polymarket platform. If you're just getting started, you're in the right place.
Everything you need to start building with the Polymarket API is right here. Lets get started.
[Not sure what to build next? Get inspired by checking out real examples from other developers using the API.](/quickstart/introduction/showcase)
---
## What is a Prediction Market?
**URL:** llms-txt#what-is-a-prediction-market?
**Contents:**
- How it works
- Making predictions
- Free-market trading
- Trust the markets
Source: https://docs.polymarket.com/polymarket-learn/FAQ/what-are-prediction-markets
How people collectively forecast the future.
A prediction market is a platform where people can bet on the outcome of future events. By buying and selling shares in the outcomes, participants collectively forecast the likelihood of events such as sports results, political elections, or entertainment awards.
Market Prices = Probabilities: The price of shares in a prediction market represents the current probability of an event happening. For example, if shares of an event are trading at 20 cents, it indicates a 20% chance of that event occurring.
### Making predictions
If you believe the actual probability of an event is higher than the market price suggests, you can buy shares. For instance, if you think a team has a better than 20% chance of winning, you would buy shares at 20 cents. If the event occurs, each share becomes worth \$1, yielding a profit.
### Free-market trading
You can buy or sell shares at any time before the event concludes, based on new information or changing circumstances. This flexibility allows the market prices to continuously reflect the most current and accurate probabilities.
### Trust the markets
Prediction markets provide unbiased and accurate probabilities in real time, cutting through the noise of human and media biases. Traditional sources often have their own incentives and slants, but prediction markets operate on the principle of "put your money where your mouth is." Here, participants are financially motivated to provide truthful insights, as their profits depend on the accuracy of their predictions.
In a prediction market, prices reflect the aggregated sentiment of all participants, weighing news, data, expert opinions, and culture to determine the true odds. Unlike media narratives, which can be swayed by various biases, prediction markets offer a transparent view of where people genuinely believe we're heading.
#### Why use prediction markets?
Prediction markets are often more accurate than traditional polls and expert predictions. The collective wisdom of diverse participants, each motivated by the potential for profit, leads to highly reliable forecasts. This makes prediction markets an excellent tool for gauging real-time probabilities of future events.
Polymarket, the world's largest prediction market, offers a user-friendly platform to bet on a wide range of topics, from sports to politics. By participating, you can profit from your knowledge while contributing to the accuracy of market predictions.
---
## What is Polymarket?
**URL:** llms-txt#what-is-polymarket?
**Contents:**
- Quick Overview
- Understanding Prices
- Making money on markets
- How accurate are Polymarket odds?
Source: https://docs.polymarket.com/polymarket-learn/get-started/what-is-polymarket
Polymarket is the worlds largest prediction market, allowing you to stay informed and profit from your knowledge by betting on future events across various topics.
Studies show prediction markets are often more accurate than pundits because they combine news, polls, and expert opinions into a single value that represents the market's view of an event's odds. Our markets reflect *accurate, unbiased, and real-time probabilities* for the events that matter most to you. Markets seek truth.
* On Polymarket, you can [buy and sell shares](making-your-first-trade) representing future event outcomes (i.e. "Will TikTok be banned in the U.S. this year?")
* Shares in event outcomes are [always priced](what-is-polymarket/#understanding-prices) between 0.00 and 1.00 [USDC](../FAQ/why-do-i-need-crypto/#why-usdc), and every pair of event outcomes (i.e. each pair of "YES" + "NO" shares) is fully collateralized by \$1.00 USDC.
* Shares are created when [opposing sides come to an agreement on odds](../trading/limit-orders), such that the sum of what each side is willing to pay is equal to \$1.00.
* The shares representing the *correct, final outcome* are paid out \$1.00 USDC each upon [market resolution](../markets/how-are-markets-resolved).
* Unlike sportsbooks, you are not betting against "the house" the counterparty to each trade is another Polymarket user. As such:
* Shares can be sold before the event outcome is known\_ (i.e. to lock in profits or cut losses)
* *There is no "house" to ban you for winning too much.*
### Understanding Prices
Prices = Probabilities.
<VideoPlayer src="https://www.youtube.com/embed/v0CvPEYBzTI?si=9cirMPQ72orQzLyS" />
*Prices (odds) on Polymarket represent the current probability of an event occurring.* For example, in a market predicting whether the Miami Heat will win the 2025 NBA Finals, if YES shares are trading at 18 cents, it indicates a 18% chance of Miami winning.
These odds are determined by what price other Polymarket users are currently willing to buy & sell those shares at. Just how stock exchanges don't "set" the prices of stocks, Polymarket does not set prices / odds - they're a function of supply & demand.
[Learn more >](/docs/guides/trading/how-are-prices-calculated)
### Making money on markets
In the example above, if you believe Miami's chances of winning are higher than 18%, you would buy “Yes” shares at 18 cents each. If Miami wins, each “Yes” share would be worth \$1, resulting in an 82-cent profit per share. Conversely, any trader who owned “No” shares would see their investment become worthless once the game is over.
Since it's a market, you're not locked into your trade. You can sell your shares at any time at the current market price. As the news changes, the supply and demand for shares fluctuates, causing the share price to reflect the new odds for the event.
### How accurate are Polymarket odds?
Research shows prediction markets are often more accurate than experts, polls, and pundits. Traders aggregate news, polls, and expert opinions, making informed trades. Their economic incentives ensure market prices adjust to reflect true odds as more knowledgeable participants join.
This makes prediction markets the best source of real-time event probabilities. People use Polymarket for the most accurate odds, gaining the ability to make informed decisions about the future.
If you're an expert on a certain topic, Polymarket is your opportunity to profit from trading based on your knowledge, while improving the market's accuracy.
---

View File

@ -0,0 +1,235 @@
# Polymarket - Guides
**Pages:** 3
---
## Example
**URL:** llms-txt#example
* **\[Event]** Where will Barron Trump attend College?
* **\[Market]** Will Barron attend Georgetown?
* **\[Market]** Will Barron attend NYU?
* **\[Market]** Will Barron attend UPenn?
* **\[Market]** Will Barron attend Harvard?
* **\[Market]** Will Barron attend another college?
---
## How to Fetch Markets
**URL:** llms-txt#how-to-fetch-markets
**Contents:**
- Overview
- 1. Fetch by Slug
- How to Extract the Slug
- API Endpoints
- Examples
- 2. Fetch by Tags
- Discover Available Tags
- Using Tags in Market Requests
- Additional Tag Filtering
- 3. Fetch All Active Markets
Source: https://docs.polymarket.com/developers/gamma-markets-api/fetch-markets-guide
<Tip>Both the getEvents and getMarkets are paginated. See [pagination section](#pagination) for details.</Tip>
This guide covers the three recommended approaches for fetching market data from the Gamma API, each optimized for different use cases.
There are three main strategies for retrieving market data:
1. **By Slug** - Best for fetching specific individual markets or events
2. **By Tags** - Ideal for filtering markets by category or sport
3. **Via Events Endpoint** - Most efficient for retrieving all active markets
**Use Case:** When you need to retrieve a specific market or event that you already know about.
Individual markets and events are best fetched using their unique slug identifier. The slug can be found directly in the Polymarket frontend URL.
### How to Extract the Slug
From any Polymarket URL, the slug is the path segment after `/event/` or `/market/`:
**For Events:** [GET /events/slug/{slug}](/api-reference/events/list-events)
**For Markets:** [GET /markets/slug/{slug}](/api-reference/markets/list-markets)
**Use Case:** When you want to filter markets by category, sport, or topic.
Tags provide a powerful way to categorize and filter markets. You can discover available tags and then use them to filter your market requests.
### Discover Available Tags
**General Tags:** [GET /tags](/api-reference/tags/list-tags)
**Sports Tags & Metadata:** [GET /sports](/api-reference/sports/get-sports-metadata-information)
The `/sports` endpoint returns comprehensive metadata for sports including tag IDs, images, resolution sources, and series information.
### Using Tags in Market Requests
Once you have tag IDs, you can use them with the `tag_id` parameter in both markets and events endpoints.
**Markets with Tags:** [GET /markets](/api-reference/markets/list-markets)
**Events with Tags:** [GET /events](/api-reference/events/list-events)
### Additional Tag Filtering
* Use `related_tags=true` to include related tag markets
* Exclude specific tags with `exclude_tag_id`
## 3. Fetch All Active Markets
**Use Case:** When you need to retrieve all available active markets, typically for broader analysis or market discovery.
The most efficient approach is to use the `/events` endpoint and work backwards, as events contain their associated markets.
**Events Endpoint:** [GET /events](/api-reference/events/list-events)
**Markets Endpoint:** [GET /markets](/api-reference/markets/list-markets)
* `order=id` - Order by event ID
* `ascending=false` - Get newest events first
* `closed=false` - Only active markets
* `limit` - Control response size
* `offset` - For pagination
This approach gives you all active markets ordered from newest to oldest, allowing you to systematically process all available trading opportunities.
For large datasets, use pagination with `limit` and `offset` parameters:
* `limit=50` - Return 50 results per page
* `offset=0` - Start from the beginning (increment by limit for subsequent pages)
**Pagination Examples:**
```bash theme={null}
**Examples:**
Example 1 (unknown):
```unknown
https://polymarket.com/event/fed-decision-in-october?tid=1758818660485
Slug: fed-decision-in-october
```
Example 2 (unknown):
```unknown
***
## 2. Fetch by Tags
**Use Case:** When you want to filter markets by category, sport, or topic.
Tags provide a powerful way to categorize and filter markets. You can discover available tags and then use them to filter your market requests.
### Discover Available Tags
**General Tags:** [GET /tags](/api-reference/tags/list-tags)
**Sports Tags & Metadata:** [GET /sports](/api-reference/sports/get-sports-metadata-information)
The `/sports` endpoint returns comprehensive metadata for sports including tag IDs, images, resolution sources, and series information.
### Using Tags in Market Requests
Once you have tag IDs, you can use them with the `tag_id` parameter in both markets and events endpoints.
**Markets with Tags:** [GET /markets](/api-reference/markets/list-markets)
**Events with Tags:** [GET /events](/api-reference/events/list-events)
```
Example 3 (unknown):
```unknown
### Additional Tag Filtering
You can also:
* Use `related_tags=true` to include related tag markets
* Exclude specific tags with `exclude_tag_id`
***
## 3. Fetch All Active Markets
**Use Case:** When you need to retrieve all available active markets, typically for broader analysis or market discovery.
The most efficient approach is to use the `/events` endpoint and work backwards, as events contain their associated markets.
**Events Endpoint:** [GET /events](/api-reference/events/list-events)
**Markets Endpoint:** [GET /markets](/api-reference/markets/list-markets)
### Key Parameters
* `order=id` - Order by event ID
* `ascending=false` - Get newest events first
* `closed=false` - Only active markets
* `limit` - Control response size
* `offset` - For pagination
### Examples
```
Example 4 (unknown):
```unknown
This approach gives you all active markets ordered from newest to oldest, allowing you to systematically process all available trading opportunities.
### Pagination
For large datasets, use pagination with `limit` and `offset` parameters:
* `limit=50` - Return 50 results per page
* `offset=0` - Start from the beginning (increment by limit for subsequent pages)
**Pagination Examples:**
```
---
## Market Orders
**URL:** llms-txt#market-orders
**Contents:**
- Video Walkthrough
- Placing a Market Order
Once you've [signed up](../get-started/how-to-signup) and [deposited funds](../get-started/how-to-deposit), you're ready to start trading on Polymarket. Here's a step-by-step guide to get you started.
<iframe width="560" height="315" src="https://www.youtube.com/embed/1lFgkHLqo28?si=i7e61-roRsOVeRMW" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen />
## Placing a Market Order
\_Before trading, you'll want to visit the [markets page](https://polymarket.com/markets) to find a market that interests you.
<Steps>
<Steps.Step>
### [Choose a market](https://polymarket.com/markets)
Locate the 'buy' modal, on the right side of the screen. Click the outcome you want to buy (usually Yes or No), then enter the dollar amount you wish to invest.
</Steps.Step>
<Steps.Step>
### Buy shares
Click **Buy** and confirm the transaction in your wallet. Once your trade goes through, you'll receive a notification confirming its success.
<Tip>Congrats, you're officially a Polymarket trader!</Tip>
</Steps.Step>
<Steps.Step>
### Share your bet slip
You'll also see a bet slip to share on social media. We love sending \$\$\$ to traders who post their trades on Twitter and tag us!
</Steps.Step>
</Steps>
Simple, right? If you think you've got the hang of it, it's time to learn about more advanced trading and order types. [Limit Orders](../trading/limit-orders/).
---

View File

@ -0,0 +1,24 @@
# Polymarket Documentation Index
## Platform Documentation
- **api.md** - Polymarket API documentation
- **getting_started.md** - Getting started guide
- **guides.md** - Development guides
- **learn.md** - Learning resources
- **trading.md** - Trading and market operations
- **other.md** - Additional resources and tools
## Real-Time Data Streaming
- **realtime-client.md** - WebSocket real-time data client (complete API reference)
- **README.md** - Platform overview
## LLM Integration
- **llms.md** - LLM integration guide (summary)
- **llms-full.md** - Complete LLM documentation
---
**Use these reference files for detailed information on specific topics.**

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,127 @@
# Polymarket Documentation
## Docs
- [Get comments by comment id](https://docs.polymarket.com/api-reference/comments/get-comments-by-comment-id.md)
- [Get comments by user address](https://docs.polymarket.com/api-reference/comments/get-comments-by-user-address.md)
- [List comments](https://docs.polymarket.com/api-reference/comments/list-comments.md)
- [Get closed positions for a user](https://docs.polymarket.com/api-reference/core/get-closed-positions-for-a-user.md): Fetches closed positions for a user(address)
- [Get current positions for a user](https://docs.polymarket.com/api-reference/core/get-current-positions-for-a-user.md): Returns positions filtered by user and optional filters.
- [Get top holders for markets](https://docs.polymarket.com/api-reference/core/get-top-holders-for-markets.md)
- [Get total value of a user's positions](https://docs.polymarket.com/api-reference/core/get-total-value-of-a-users-positions.md)
- [Get trades for a user or markets](https://docs.polymarket.com/api-reference/core/get-trades-for-a-user-or-markets.md)
- [Get user activity](https://docs.polymarket.com/api-reference/core/get-user-activity.md): Returns on-chain activity for a user.
- [Get event by id](https://docs.polymarket.com/api-reference/events/get-event-by-id.md)
- [Get event by slug](https://docs.polymarket.com/api-reference/events/get-event-by-slug.md)
- [Get event tags](https://docs.polymarket.com/api-reference/events/get-event-tags.md)
- [List events](https://docs.polymarket.com/api-reference/events/list-events.md)
- [Health check](https://docs.polymarket.com/api-reference/health/health-check.md)
- [Get market by id](https://docs.polymarket.com/api-reference/markets/get-market-by-id.md)
- [Get market by slug](https://docs.polymarket.com/api-reference/markets/get-market-by-slug.md)
- [Get market tags by id](https://docs.polymarket.com/api-reference/markets/get-market-tags-by-id.md)
- [List markets](https://docs.polymarket.com/api-reference/markets/list-markets.md)
- [Get live volume for an event](https://docs.polymarket.com/api-reference/misc/get-live-volume-for-an-event.md)
- [Get open interest](https://docs.polymarket.com/api-reference/misc/get-open-interest.md)
- [Get total markets a user has traded](https://docs.polymarket.com/api-reference/misc/get-total-markets-a-user-has-traded.md)
- [Get multiple order books summaries by request](https://docs.polymarket.com/api-reference/orderbook/get-multiple-order-books-summaries-by-request.md): Retrieves order book summaries for specified tokens via POST request
- [Get order book summary](https://docs.polymarket.com/api-reference/orderbook/get-order-book-summary.md): Retrieves the order book summary for a specific token
- [Get market price](https://docs.polymarket.com/api-reference/pricing/get-market-price.md): Retrieves the market price for a specific token and side
- [Get midpoint price](https://docs.polymarket.com/api-reference/pricing/get-midpoint-price.md): Retrieves the midpoint price for a specific token
- [Get multiple market prices](https://docs.polymarket.com/api-reference/pricing/get-multiple-market-prices.md): Retrieves market prices for multiple tokens and sides
- [Get multiple market prices by request](https://docs.polymarket.com/api-reference/pricing/get-multiple-market-prices-by-request.md): Retrieves market prices for specified tokens and sides via POST request
- [Get price history for a traded token](https://docs.polymarket.com/api-reference/pricing/get-price-history-for-a-traded-token.md): Fetches historical price data for a specified market token
- [Search markets, events, and profiles](https://docs.polymarket.com/api-reference/search/search-markets-events-and-profiles.md)
- [Get series by id](https://docs.polymarket.com/api-reference/series/get-series-by-id.md)
- [List series](https://docs.polymarket.com/api-reference/series/list-series.md)
- [Get sports metadata information](https://docs.polymarket.com/api-reference/sports/get-sports-metadata-information.md): Retrieves metadata for various sports including images, resolution sources, ordering preferences, tags, and series information. This endpoint provides comprehensive sport configuration data used throughout the platform.
- [List teams](https://docs.polymarket.com/api-reference/sports/list-teams.md)
- [Get bid-ask spreads](https://docs.polymarket.com/api-reference/spreads/get-bid-ask-spreads.md): Retrieves bid-ask spreads for multiple tokens
- [Get related tags (relationships) by tag id](https://docs.polymarket.com/api-reference/tags/get-related-tags-relationships-by-tag-id.md)
- [Get related tags (relationships) by tag slug](https://docs.polymarket.com/api-reference/tags/get-related-tags-relationships-by-tag-slug.md)
- [Get tag by id](https://docs.polymarket.com/api-reference/tags/get-tag-by-id.md)
- [Get tag by slug](https://docs.polymarket.com/api-reference/tags/get-tag-by-slug.md)
- [Get tags related to a tag id](https://docs.polymarket.com/api-reference/tags/get-tags-related-to-a-tag-id.md)
- [Get tags related to a tag slug](https://docs.polymarket.com/api-reference/tags/get-tags-related-to-a-tag-slug.md)
- [List tags](https://docs.polymarket.com/api-reference/tags/list-tags.md)
- [Polymarket Changelog](https://docs.polymarket.com/changelog/changelog.md): Welcome to the Polymarket Changelog. Here you will find any important changes to Polymarket, including but not limited to CLOB, API, UI and Mobile Applications.
- [null](https://docs.polymarket.com/developers/CLOB/authentication.md)
- [null](https://docs.polymarket.com/developers/CLOB/clients.md)
- [null](https://docs.polymarket.com/developers/CLOB/endpoints.md)
- [CLOB Introduction](https://docs.polymarket.com/developers/CLOB/introduction.md)
- [Cancel Orders(s)](https://docs.polymarket.com/developers/CLOB/orders/cancel-orders.md): Multiple endpoints to cancel a single order, multiple orders, all orders or all orders from a single market.
- [Check Order Reward Scoring](https://docs.polymarket.com/developers/CLOB/orders/check-scoring.md): Check if an order is eligble or scoring for Rewards purposes
- [Place Single Order](https://docs.polymarket.com/developers/CLOB/orders/create-order.md): Detailed instructions for creating, placing, and managing orders using Polymarket's CLOB API.
- [Place Multiple Orders (Batching)](https://docs.polymarket.com/developers/CLOB/orders/create-order-batch.md): Instructions for placing multiple orders(Batch)
- [Get Active Orders](https://docs.polymarket.com/developers/CLOB/orders/get-active-order.md)
- [Get Order](https://docs.polymarket.com/developers/CLOB/orders/get-order.md): Get information about an existing order
- [Onchain Order Info](https://docs.polymarket.com/developers/CLOB/orders/onchain-order-info.md)
- [Orders Overview](https://docs.polymarket.com/developers/CLOB/orders/orders.md): Detailed instructions for creating, placing, and managing orders using Polymarket's CLOB API.
- [null](https://docs.polymarket.com/developers/CLOB/status.md)
- [Get Trades](https://docs.polymarket.com/developers/CLOB/trades/trades.md)
- [Trades Overview](https://docs.polymarket.com/developers/CLOB/trades/trades-overview.md)
- [Market Channel](https://docs.polymarket.com/developers/CLOB/websocket/market-channel.md)
- [User Channel](https://docs.polymarket.com/developers/CLOB/websocket/user-channel.md)
- [WSS Authentication](https://docs.polymarket.com/developers/CLOB/websocket/wss-auth.md)
- [WSS Overview](https://docs.polymarket.com/developers/CLOB/websocket/wss-overview.md): Overview and general information about the Polymarket Websocket
- [Deployment and Additional Information](https://docs.polymarket.com/developers/CTF/deployment-resources.md)
- [Merging Tokens](https://docs.polymarket.com/developers/CTF/merge.md)
- [Overview](https://docs.polymarket.com/developers/CTF/overview.md)
- [Reedeeming Tokens](https://docs.polymarket.com/developers/CTF/redeem.md)
- [Splitting USDC](https://docs.polymarket.com/developers/CTF/split.md)
- [RTDS Comments](https://docs.polymarket.com/developers/RTDS/RTDS-comments.md)
- [RTDS Crypto Prices](https://docs.polymarket.com/developers/RTDS/RTDS-crypto-prices.md)
- [Real Time Data Socket](https://docs.polymarket.com/developers/RTDS/RTDS-overview.md)
- [How to Fetch Markets](https://docs.polymarket.com/developers/gamma-markets-api/fetch-markets-guide.md)
- [Gamma Structure](https://docs.polymarket.com/developers/gamma-markets-api/gamma-structure.md)
- [null](https://docs.polymarket.com/developers/gamma-markets-api/overview.md)
- [Overview](https://docs.polymarket.com/developers/neg-risk/overview.md)
- [null](https://docs.polymarket.com/developers/proxy-wallet.md)
- [Resolution](https://docs.polymarket.com/developers/resolution/UMA.md)
- [Liquidity Rewards](https://docs.polymarket.com/developers/rewards/overview.md): Polymarket provides incentives aimed at catalyzing the supply and demand side of the marketplace. Specifically there is a public liquidity rewards program as well as one-off public pnl/volume competitions.
- [null](https://docs.polymarket.com/developers/subgraph/overview.md)
- [Does Polymarket have an API?](https://docs.polymarket.com/polymarket-learn/FAQ/does-polymarket-have-an-api.md): Getting data from Polymarket
- [How To Use Embeds](https://docs.polymarket.com/polymarket-learn/FAQ/embeds.md): Adding market embeds to your Substack or website.
- [How Do I Export My Key?](https://docs.polymarket.com/polymarket-learn/FAQ/how-to-export-private-key.md): Exporting your private key on Magic.Link
- [Is My Money Safe?](https://docs.polymarket.com/polymarket-learn/FAQ/is-my-money-safe.md): Yes. Polymarket is non-custodial, so you're in control of your funds.
- [Is Polymarket The House?](https://docs.polymarket.com/polymarket-learn/FAQ/is-polymarket-the-house.md): No, Polymarket is not the house. All trades happen peer-to-peer (p2p).
- [Polymarket vs. Polling](https://docs.polymarket.com/polymarket-learn/FAQ/polling.md): How is Polymarket better than traditional / legacy polling?
- [Recover Missing Deposit](https://docs.polymarket.com/polymarket-learn/FAQ/recover-missing-deposit.md): If you deposited the wrong cryptocurrency on Ethereum or Polygon, use these tools to recover those funds.
- [Can I Sell Early?](https://docs.polymarket.com/polymarket-learn/FAQ/sell-early.md)
- [How Do I Contact Support?](https://docs.polymarket.com/polymarket-learn/FAQ/support.md): Polymarket offers technical support through our website chat feature, and through Discord.
- [Does Polymarket Have a Token?](https://docs.polymarket.com/polymarket-learn/FAQ/wen-token.md)
- [What is a Prediction Market?](https://docs.polymarket.com/polymarket-learn/FAQ/what-are-prediction-markets.md): How people collectively forecast the future.
- [Why Crypto?](https://docs.polymarket.com/polymarket-learn/FAQ/why-do-i-need-crypto.md): Why Polymarket uses crypto and blockchain technology to create the worlds largest Prediction market.
- [Deposit with Coinbase](https://docs.polymarket.com/polymarket-learn/deposits/coinbase.md): How to buy and deposit USDC to your Polymarket account using Coinbase.
- [How to Withdraw](https://docs.polymarket.com/polymarket-learn/deposits/how-to-withdraw.md): How to withdraw your cash balance from Polymarket.
- [Large Cross Chain Deposits](https://docs.polymarket.com/polymarket-learn/deposits/large-cross-chain-deposits.md)
- [Deposit Using Your Card](https://docs.polymarket.com/polymarket-learn/deposits/moonpay.md): Use MoonPay to deposit cash using your Visa, Mastercard, or bank account.
- [Deposit by Transfering Crypto](https://docs.polymarket.com/polymarket-learn/deposits/supported-tokens.md): Learn what Tokens and Chains are supported for deposit.
- [Deposit USDC on Ethereum](https://docs.polymarket.com/polymarket-learn/deposits/usdc-on-eth.md): How to deposit USDC on the Ethereum Network to your Polymarket account.
- [How to Deposit](https://docs.polymarket.com/polymarket-learn/get-started/how-to-deposit.md): How to add cash to your balance on Polymarket.
- [How to Sign-Up](https://docs.polymarket.com/polymarket-learn/get-started/how-to-signup.md): How to create a Polymarket account.
- [Making Your First Trade](https://docs.polymarket.com/polymarket-learn/get-started/making-your-first-trade.md): How to buy shares.
- [What is Polymarket?](https://docs.polymarket.com/polymarket-learn/get-started/what-is-polymarket.md)
- [How Are Markets Disputed?](https://docs.polymarket.com/polymarket-learn/markets/dispute.md)
- [How Are Markets Clarified?](https://docs.polymarket.com/polymarket-learn/markets/how-are-markets-clarified.md): How are markets on Polymarket clarified?
- [How Are Markets Created?](https://docs.polymarket.com/polymarket-learn/markets/how-are-markets-created.md): Markets are created by the markets team with input from users and the community.
- [How Are Prediction Markets Resolved?](https://docs.polymarket.com/polymarket-learn/markets/how-are-markets-resolved.md): Markets are resolved by the UMA Optimistic Oracle, a smart-contract based optimistic oracle.
- [Trading Fees](https://docs.polymarket.com/polymarket-learn/trading/fees.md)
- [Holding Rewards](https://docs.polymarket.com/polymarket-learn/trading/holding-rewards.md)
- [How Are Prices Calculated?](https://docs.polymarket.com/polymarket-learn/trading/how-are-prices-calculated.md): The prices probabilities displayed on Polymarket are the midpoint of the bid-ask spread in the orderbook.
- [Limit Orders](https://docs.polymarket.com/polymarket-learn/trading/limit-orders.md): What are limit orders and how to make them.
- [Liquidity Rewards](https://docs.polymarket.com/polymarket-learn/trading/liquidity-rewards.md): Learn how to earn rewards merely by placing trades on Polymarket
- [Market Orders](https://docs.polymarket.com/polymarket-learn/trading/market-orders.md): How to buy shares.
- [Does Polymarket Have Trading Limits?](https://docs.polymarket.com/polymarket-learn/trading/no-limits.md)
- [Using the Order Book](https://docs.polymarket.com/polymarket-learn/trading/using-the-orderbook.md): Understanding the Order Book will help you become an advanced trader.
- [Glossary](https://docs.polymarket.com/quickstart/introduction/definitions.md)
- [Developer Quickstart](https://docs.polymarket.com/quickstart/introduction/main.md)
- [API Rate Limits](https://docs.polymarket.com/quickstart/introduction/rate-limits.md)
- [Your First Order](https://docs.polymarket.com/quickstart/orders/first-order.md)
- [WSS Quickstart](https://docs.polymarket.com/quickstart/websocket/WSS-Quickstart.md)
## Optional
- [Polymarket](https://polymarket.com)
- [Discord Community](https://discord.gg/polymarket)
- [Twitter](https://x.com/polymarket)

View File

@ -0,0 +1,540 @@
# Polymarket - Other
**Pages:** 7
---
## Deployment and Additional Information
**URL:** llms-txt#deployment-and-additional-information
**Contents:**
- Deployment
- Resources
Source: https://docs.polymarket.com/developers/CTF/deployment-resources
The CTF contract is deployed (and verified) at the following addresses:
| Network | Deployed Address |
| --------------- | ------------------------------------------------------------------------------------------------------------------------ |
| Polygon Mainnet | [0x4D97DCd97eC945f40cF65F87097ACe5EA0476045](https://polygonscan.com/address/0x4D97DCd97eC945f40cF65F87097ACe5EA0476045) |
| Polygon Mainnet | [0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E](https://polygonscan.com/address/0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E) |
Polymarket provides code samples in both Python and TypeScript for interacting
with our smart chain contracts. You will need an RPC endpoint to access the
blockchain, and you'll be responsible for paying gas fees when executing these
RPC/function calls. Please ensure you're using the correct example for your wallet
type (Safe Wallet vs Proxy Wallet) when implementing.
* [On-Chain Code Samples](https://github.com/Polymarket/examples/tree/main/examples)
* [Polygon RPC List](https://chainlist.org/chain/137)
* [CTF Source Code](https://github.com/gnosis/conditional-tokens-contracts)
* [Audits](https://github.com/gnosis/conditional-tokens-contracts/tree/master/docs/audit)
* [Gist For positionId Calculation](https://gist.github.com/L-Kov/950bce141a9d1aa1ed3b1cfce6d30217)
---
## Gamma Structure
**URL:** llms-txt#gamma-structure
Source: https://docs.polymarket.com/developers/gamma-markets-api/gamma-structure
Gamma provides some organizational models. These include events, and markets. The most fundamental element is always markets and the other models simply provide additional organization.
---
## Real Time Data Socket
**URL:** llms-txt#real-time-data-socket
**Contents:**
- Overview
- Connection Details
- Authentication
- Connection Management
- Available Subscription Types
- Message Structure
- Subscription Management
- Subscribe to Topics
- Unsubscribe from Topics
- Error Handling
Source: https://docs.polymarket.com/developers/RTDS/RTDS-overview
The Polymarket Real-Time Data Socket (RTDS) is a WebSocket-based streaming service that provides real-time updates for various Polymarket data streams. The service allows clients to subscribe to multiple data feeds simultaneously and receive live updates as events occur on the platform.
<Note>Polymarket provides a Typescript client for interacting with this streaming service. [Download and view it's documentation here](https://github.com/Polymarket/real-time-data-client)</Note>
### Connection Details
* **WebSocket URL**: `wss://ws-live-data.polymarket.com`
* **Protocol**: WebSocket
* **Data Format**: JSON
The RTDS supports two types of authentication depending on the subscription type:
1. **CLOB Authentication**: Required for certain trading-related subscriptions
* `key`: API key
* `secret`: API secret
* `passphrase`: API passphrase
2. **Gamma Authentication**: Required for user-specific data
* `address`: User wallet address
### Connection Management
The WebSocket connection supports:
* **Dynamic Subscriptions**: Without disconnecting from the socket users can add, remove and modify topics and filters they are subscribed to.
* **Ping/Pong**: You should send PING messages (every 5 seconds ideally) to maintain connection
## Available Subscription Types
<Note>Although this connection technically supports additional activity and subscription types, they are not fully supported at this time. Users are free to use them but there may be some unexpected behavior.</Note>
The RTDS currently supports the following subscription types:
1. **[Crypto Prices](/developers/RTDS/RTDS-crypto-prices)** - Real-time cryptocurrency price updates
2. **[Comments](/developers/RTDS/RTDS-comments)** - Comment-related events including reactions
All messages received from the WebSocket follow this structure:
* `topic`: The subscription topic (e.g., "crypto\_prices", "comments", "activity")
* `type`: The message type/event (e.g., "update", "reaction\_created", "orders\_matched")
* `timestamp`: Unix timestamp in milliseconds
* `payload`: Event-specific data object
## Subscription Management
### Subscribe to Topics
To subscribe to data streams, send a JSON message with this structure:
### Unsubscribe from Topics
To unsubscribe from data streams, send a similar message with `"action": "unsubscribe"`.
* Connection errors will trigger automatic reconnection attempts
* Invalid subscription messages may result in connection closure
* Authentication failures will prevent successful subscription to protected topics
**Examples:**
Example 1 (unknown):
```unknown
* `topic`: The subscription topic (e.g., "crypto\_prices", "comments", "activity")
* `type`: The message type/event (e.g., "update", "reaction\_created", "orders\_matched")
* `timestamp`: Unix timestamp in milliseconds
* `payload`: Event-specific data object
## Subscription Management
### Subscribe to Topics
To subscribe to data streams, send a JSON message with this structure:
```
---
## RTDS Crypto Prices
**URL:** llms-txt#rtds-crypto-prices
**Contents:**
- Overview
- Binance Source (`crypto_prices`)
- Subscription Details
- Subscription Message
- With Symbol Filter
- Chainlink Source (`crypto_prices_chainlink`)
- Subscription Details
- Subscription Message
- With Symbol Filter
- Message Format
Source: https://docs.polymarket.com/developers/RTDS/RTDS-crypto-prices
<Note>Polymarket provides a Typescript client for interacting with this streaming service. [Download and view it's documentation here](https://github.com/Polymarket/real-time-data-client)</Note>
The crypto prices subscription provides real-time updates for cryptocurrency price data from two different sources:
* **Binance Source** (`crypto_prices`): Real-time price data from Binance exchange
* **Chainlink Source** (`crypto_prices_chainlink`): Price data from Chainlink oracle networks
Both streams deliver current market prices for various cryptocurrency trading pairs, but use different symbol formats and subscription structures.
## Binance Source (`crypto_prices`)
### Subscription Details
* **Topic**: `crypto_prices`
* **Type**: `update`
* **Authentication**: Not required
* **Filters**: Optional (specific symbols can be filtered)
* **Symbol Format**: Lowercase concatenated pairs (e.g., `solusdt`, `btcusdt`)
### Subscription Message
### With Symbol Filter
To subscribe to specific cryptocurrency symbols, include a filters parameter:
## Chainlink Source (`crypto_prices_chainlink`)
### Subscription Details
* **Topic**: `crypto_prices_chainlink`
* **Type**: `*` (all types)
* **Authentication**: Not required
* **Filters**: Optional (JSON object with symbol specification)
* **Symbol Format**: Slash-separated pairs (e.g., `eth/usd`, `btc/usd`)
### Subscription Message
### With Symbol Filter
To subscribe to specific cryptocurrency symbols, include a JSON filters parameter:
### Binance Source Message Format
When subscribed to Binance crypto prices (`crypto_prices`), you'll receive messages with the following structure:
### Chainlink Source Message Format
When subscribed to Chainlink crypto prices (`crypto_prices_chainlink`), you'll receive messages with the following structure:
| Field | Type | Description |
| ----------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `symbol` | string | Trading pair symbol<br />**Binance**: lowercase concatenated (e.g., "solusdt", "btcusdt")<br />**Chainlink**: slash-separated (e.g., "eth/usd", "btc/usd") |
| `timestamp` | number | Price timestamp in Unix milliseconds |
| `value` | number | Current price value in the quote currency |
### Binance Source Examples
#### Solana Price Update (Binance)
#### Bitcoin Price Update (Binance)
### Chainlink Source Examples
#### Ethereum Price Update (Chainlink)
#### Bitcoin Price Update (Chainlink)
### Binance Source Symbols
The Binance source supports various cryptocurrency trading pairs using lowercase concatenated format:
* `btcusdt` - Bitcoin to USDT
* `ethusdt` - Ethereum to USDT
* `solusdt` - Solana to USDT
* `xrpusdt` - XRP to USDT
### Chainlink Source Symbols
The Chainlink source supports cryptocurrency trading pairs using slash-separated format:
* `btc/usd` - Bitcoin to USD
* `eth/usd` - Ethereum to USD
* `sol/usd` - Solana to USD
* `xrp/usd` - XRP to USD
* Price updates are sent as market prices change
* The timestamp in the payload represents when the price was recorded
* The outer timestamp represents when the message was sent via WebSocket
* No authentication is required for crypto price data
**Examples:**
Example 1 (unknown):
```unknown
### With Symbol Filter
To subscribe to specific cryptocurrency symbols, include a filters parameter:
```
Example 2 (unknown):
```unknown
## Chainlink Source (`crypto_prices_chainlink`)
### Subscription Details
* **Topic**: `crypto_prices_chainlink`
* **Type**: `*` (all types)
* **Authentication**: Not required
* **Filters**: Optional (JSON object with symbol specification)
* **Symbol Format**: Slash-separated pairs (e.g., `eth/usd`, `btc/usd`)
### Subscription Message
```
Example 3 (unknown):
```unknown
### With Symbol Filter
To subscribe to specific cryptocurrency symbols, include a JSON filters parameter:
```
Example 4 (unknown):
```unknown
## Message Format
### Binance Source Message Format
When subscribed to Binance crypto prices (`crypto_prices`), you'll receive messages with the following structure:
```
---
## RTDS Comments
**URL:** llms-txt#rtds-comments
**Contents:**
- Overview
- Subscription Details
- Subscription Message
- Message Format
- Message Types
- comment\_created
- comment\_removed
- reaction\_created
- reaction\_removed
- Payload Fields
Source: https://docs.polymarket.com/developers/RTDS/RTDS-comments
<Note>Polymarket provides a Typescript client for interacting with this streaming service. [Download and view it's documentation here](https://github.com/Polymarket/real-time-data-client)</Note>
The comments subscription provides real-time updates for comment-related events on the Polymarket platform. This includes new comments being created, as well as other comment interactions like reactions and replies.
## Subscription Details
* **Topic**: `comments`
* **Type**: `comment_created` (and potentially other comment event types like `reaction_created`)
* **Authentication**: May require Gamma authentication for user-specific data
* **Filters**: Optional (can filter by specific comment IDs, users, or events)
## Subscription Message
When subscribed to comments, you'll receive messages with the following structure:
Triggered when a user creates a new comment on an event or in reply to another comment.
Triggered when a comment is removed or deleted.
### reaction\_created
Triggered when a user adds a reaction to an existing comment.
### reaction\_removed
Triggered when a reaction is removed from a comment.
| Field | Type | Description |
| ------------------ | ------ | ------------------------------------------------------------------------- |
| `body` | string | The text content of the comment |
| `createdAt` | string | ISO 8601 timestamp when the comment was created |
| `id` | string | Unique identifier for this comment |
| `parentCommentID` | string | ID of the parent comment if this is a reply (null for top-level comments) |
| `parentEntityID` | number | ID of the parent entity (event, market, etc.) |
| `parentEntityType` | string | Type of parent entity (e.g., "Event", "Market") |
| `profile` | object | Profile information of the user who created the comment |
| `reactionCount` | number | Current number of reactions on this comment |
| `replyAddress` | string | Polygon address for replies (may be different from userAddress) |
| `reportCount` | number | Current number of reports on this comment |
| `userAddress` | string | Polygon address of the user who created the comment |
### Profile Object Fields
| Field | Type | Description |
| ----------------------- | ------- | ------------------------------------------------- |
| `baseAddress` | string | User profile address |
| `displayUsernamePublic` | boolean | Whether the username should be displayed publicly |
| `name` | string | User's display name |
| `proxyWallet` | string | Proxy wallet address used for transactions |
| `pseudonym` | string | Generated pseudonym for the user |
## Parent Entity Types
The following parent entity types are supported:
* `Event` - Comments on prediction events
* `Market` - Comments on specific markets
* Additional entity types may be available
### New Comment Created
### Reply to Existing Comment
Comments support nested threading:
* **Top-level comments**: `parentCommentID` is null or empty
* **Reply comments**: `parentCommentID` contains the ID of the parent comment
* All comments are associated with a `parentEntityID` and `parentEntityType`
* Real-time comment feed displays
* Discussion thread monitoring
* Community sentiment analysis
* Comments include `reactionCount` and `reportCount`
* Comment body contains the full text content
* The `createdAt` timestamp uses ISO 8601 format with timezone information
* The outer `timestamp` field represents when the WebSocket message was sent
* User profiles include both primary addresses and proxy wallet addresses
**Examples:**
Example 1 (unknown):
```unknown
## Message Format
When subscribed to comments, you'll receive messages with the following structure:
```
Example 2 (unknown):
```unknown
## Message Types
### comment\_created
Triggered when a user creates a new comment on an event or in reply to another comment.
### comment\_removed
Triggered when a comment is removed or deleted.
### reaction\_created
Triggered when a user adds a reaction to an existing comment.
### reaction\_removed
Triggered when a reaction is removed from a comment.
## Payload Fields
| Field | Type | Description |
| ------------------ | ------ | ------------------------------------------------------------------------- |
| `body` | string | The text content of the comment |
| `createdAt` | string | ISO 8601 timestamp when the comment was created |
| `id` | string | Unique identifier for this comment |
| `parentCommentID` | string | ID of the parent comment if this is a reply (null for top-level comments) |
| `parentEntityID` | number | ID of the parent entity (event, market, etc.) |
| `parentEntityType` | string | Type of parent entity (e.g., "Event", "Market") |
| `profile` | object | Profile information of the user who created the comment |
| `reactionCount` | number | Current number of reactions on this comment |
| `replyAddress` | string | Polygon address for replies (may be different from userAddress) |
| `reportCount` | number | Current number of reports on this comment |
| `userAddress` | string | Polygon address of the user who created the comment |
### Profile Object Fields
| Field | Type | Description |
| ----------------------- | ------- | ------------------------------------------------- |
| `baseAddress` | string | User profile address |
| `displayUsernamePublic` | boolean | Whether the username should be displayed publicly |
| `name` | string | User's display name |
| `proxyWallet` | string | Proxy wallet address used for transactions |
| `pseudonym` | string | Generated pseudonym for the user |
## Parent Entity Types
The following parent entity types are supported:
* `Event` - Comments on prediction events
* `Market` - Comments on specific markets
* Additional entity types may be available
## Example Messages
### New Comment Created
```
Example 3 (unknown):
```unknown
### Reply to Existing Comment
```
---
## UMA Optimistic Oracle Integration
**URL:** llms-txt#uma-optimistic-oracle-integration
**Contents:**
- Overview
- Clarifications
- Resolution Process
- Actions
- Possible Flows
- Deployed Addresses
- v3.0
- v2.0
- v1.0
- Additional Resources
Polymarket leverages UMA's Optimistic Oracle (OO) to resolve arbitrary questions, permissionlessly. From [UMA's docs](https://docs.uma.xyz/protocol-overview/how-does-umas-oracle-work):
"UMA's Optimistic Oracle allows contracts to quickly request and receive data information ... The Optimistic Oracle acts as a generalized escalation game between contracts that initiate a price request and UMA's dispute resolution system known as the Data Verification Mechanism (DVM). Prices proposed by the Optimistic Oracle will not be sent to the DVM unless it is disputed. If a dispute is raised, a request is sent to the DVM. All contracts built on UMA use the DVM as a backstop to resolve disputes. Disputes sent to the DVM will be resolved within a few days -- after UMA tokenholders vote on what the correct outcome should have been."
To allow CTF markets to be resolved via the OO, Polymarket developed a custom adapter contract called `UmaCtfAdapter` that provides a way for the two contract systems to interface.
Recent versions (v2+) of the `UmaCtfAdapter` also include a bulletin board feature that allows market creators to issue "clarifications". Questions that allow updates will include the sentence in their ancillary data:
"Updates made by the question creator via the bulletin board on 0x6A5D0222186C0FceA7547534cC13c3CFd9b7b6A4F74 should be considered. In summary, clarifications that do not impact the question's intent should be considered."
Where the [transaction](https://polygonscan.com/tx/0xa14f01b115c4913624fc3f508f960f4dea252758e73c28f5f07f8e19d7bca066) reference outlining what outlining should be considered.
## Resolution Process
* **Initiate** - Binary CTF markets are initialized via the `UmaCtfAdapter`'s `initialize()` function. This stores the question parameters on the contract, prepares the CTF and requests a price for a question from the OO. It returns a `questionID` that is also used to reference on the `UmaCtfAdapter`. The caller provides:
1. `ancillaryData` - data used to resolve a question (i.e the question + clarifications)
2. `rewardToken` - ERC20 token address used for payment of rewards and fees
3. `reward` - Reward amount offered to a successful proposer. The caller must have set allowance so that the contract can pull this reward in.
4. `proposalBond` - Bond required to be posted by OO proposers/disputers. If 0, the default OO bond is used.
5. `liveness` - UMA liveness period in seconds. If 0, the default liveness period is used.
* **Propose Price** - Anyone can then propose a price to the question on the OO. To do this they must post the `proposalBond`. The liveness period begins after a price is proposed.
* **Dispute** - Anyone that disagrees with the proposed price has the opportunity to dispute the price by posting a counter bond via the OO, this proposed will now be escalated to the DVM for a voter-wide vote.
When the first proposed price is disputed for a `questionID` on the adapter, a callback is made and posted as the reward for this new proposal. This means a second `questionID`, making a new `questionID` to the OO (the reward is returned before the callback is made and posted as the reward for this new proposal). This allows for a second round of resolution, and correspondingly a second dispute is required for it to go to the DVM. The thinking behind this is to doubles the cost of a potential griefing vector (two disputes are required just one) and also allows far-fetched (incorrect) first price proposals to not delay the resolution. As such there are two possible flows:
* **Initialize (CTFAdapter) -> Propose (OO) -> Resolve (CTFAdapter)**
* **Initialize (CTFAdaptor) -> Propose (OO) -> Challenge (OO) -> Propose (OO) -> Resolve (CTFAdaptor)**
* **Initialize (CTFAdaptor) -> Propose (OO) -> Challenge (OO) -> Propose (OO) -> Challenge (CtfAdapter) -> Resolve (CTFAdaptor)**
## Deployed Addresses
| Network | Address |
| --------------- | ------------------------------------------------------------------------------------------------------------------------ |
| Polygon Mainnet | [0x2F5e3684cb1F318ec51b00Edba38d79Ac2c0aA9d](https://polygonscan.com/address/0x2F5e3684cb1F318ec51b00Edba38d79Ac2c0aA9d) |
| Network | Address |
| --------------- | --------------------------------------------------------------------------------------------------------------------------- |
| Polygon Mainnet | [0x6A9D0222186C0FceA7547534cC13c3CFd9b7b6A4F74](https://polygonscan.com/address/0x6A9D222616C90FcA5754cd1333cFD9b7fb6a4F74) |
| Network | Address |
| --------------- | -------------------------------------------------------------------------------------------------------------------------- |
| Polygon Mainnet | [0xC8B122858a4EF82C2d4eE2E6A276C719e692995130](https://polygonscan.com/address/0xCB1822859cEF82Cd2Eb4E6276C7916e692995130) |
## Additional Resources
* [Audit](https://github.com/Polymarket/uma-ctf-adapter/blob/main/audit/Polymarket_UMA_Optimistic_Oracle_Adapter_Audit.pdf)
* [Source Code](https://github.com/Polymarket/uma-ctf-adapter)
* [UMA Documentation](https://docs.uma.xyz/)
* [UMA Oracle Portal](https://oracle.uma.xyz/)
---
## Resolution
**URL:** llms-txt#resolution
Source: https://docs.polymarket.com/developers/resolution/UMA
---

View File

@ -0,0 +1,396 @@
# Real time data client
This client provides a wrapper to connect to the `real-time-data-streaming` `WebSocket` service.
## How to use it
Here is a quick example about how to connect to the service and start receiving messages (you can find more in the folder `examples/`):
```typescript
import { RealTimeDataClient } from "../src/client";
import { Message } from "../src/model";
const onMessage = (message: Message): void => {
console.log(message.topic, message.type, message.payload);
};
const onConnect = (client: RealTimeDataClient): void => {
// Subscribe to a topic
client.subscribe({
subscriptions: [
{
topic: "comments",
type: "*", // "*"" can be used to connect to all the types of the topic
filters: `{"parentEntityID":100,"parentEntityType":"Event"}`, // empty means no filter
},
],
});
};
new RealTimeDataClient({ onMessage, onConnect }).connect();
```
## How to subscribe and unsubscribe from messages
Once the connection is stablished and you have a `client: RealTimeDataClient` object, you can `subscribe` and `unsubscribe` to many messages streamings using the same connection.
### Subscribe
Subscribe to 'trades' messages from the topic 'activity' and to the all comments messages.
```typescript
client.subscribe({
subscriptions: [
{
topic: "activity",
type: "trades",
},
],
});
client.subscribe({
subscriptions: [
{
topic: "comments",
type: "*", // "*"" can be used to connect to all the types of the topic
},
],
});
```
### Unsubscribe
Unsubscribe from the new trades messages of the topic 'activity'. If 'activity' has more messages types and I used '\*' to connect to all of them, this will only unsubscribe from the type 'trades'.
```typescript
client.subscribe({
subscriptions: [
{
topic: "activity",
type: "trades",
},
],
});
```
### Disconnect
The `client` object provides a method to disconnect from the `WebSocket` server:
```typescript
client.disconnect();
```
## Messages hierarchy
| Topic | Type | Auth | Filters (if it is empty the messages won't be filtered) | Schema | Subscription Handler |
| ------------------------- | ------------------ | -------- | --------------------------------------------------------------- | ----------------------------------- | ----------------------------------------------------------- |
| `activity` | `trades` | - | `{"event_slug":"string"}' OR '{"market_slug":"string"}` | [`Trade`](#trade) | |
| `activity` | `orders_matched` | - | `{"event_slug":"string"}' OR '{"market_slug":"string"}` | [`Trade`](#trade) | |
| `comments` | `comment_created` | - | `{"parentEntityID":number,"parentEntityType":"Event / Series"}` | [`Comment`](#comment) | |
| `comments` | `comment_removed` | - | `{"parentEntityID":number,"parentEntityType":"Event / Series"}` | [`Comment`](#comment) | |
| `comments` | `reaction_created` | - | `{"parentEntityID":number,"parentEntityType":"Event / Series"}` | [`Reaction`](#reaction) | |
| `comments` | `reaction_removed` | - | `{"parentEntityID":number,"parentEntityType":"Event / Series"}` | [`Reaction`](#reaction) | |
| `rfq` | `request_created` | - | - | [`Request`](#request) | |
| `rfq` | `request_edited` | - | - | [`Request`](#request) | |
| `rfq` | `request_canceled` | - | - | [`Request`](#request) | |
| `rfq` | `request_expired` | - | - | [`Request`](#request) | |
| `rfq` | `quote_created` | - | - | [`Quote`](#quote) | |
| `rfq` | `quote_edited` | - | - | [`Quote`](#quote) | |
| `rfq` | `quote_canceled` | - | - | [`Quote`](#quote) | |
| `rfq` | `quote_expired` | - | - | [`Quote`](#quote) | |
| `crypto_prices` | `update` | - | `{"symbol":string}` | [`CryptoPrice`](#cryptoprice) | [`CryptoPriceHistorical`](#initial-data-dump-on-connection) |
| `crypto_prices_chainlink` | `update` | - | `{"symbol":string}` | [`CryptoPrice`](#cryptoprice) | [`CryptoPriceHistorical`](#initial-data-dump-on-connection) |
| `clob_user` | `order` | ClobAuth | - | [`Order`](#order) | |
| `clob_user` | `trade` | ClobAuth | - | [`Trade`](#trade-1) | |
| `clob_market` | `price_change` | - | `["100","200",...]` (filters are mandatory on this one) | [`PriceChanges`](#pricechanges) | |
| `clob_market` | `agg_orderbook` | - | `["100","200",...]` | [`AggOrderbook`](#aggorderbook) | [`AggOrderbook`](#aggorderbook) |
| `clob_market` | `last_trade_price` | - | `["100","200",...]` | [`LastTradePrice`](#lasttradeprice) | |
| `clob_market` | `tick_size_change` | - | `["100","200",...]` | [`TickSizeChange`](#ticksizechange) | |
| `clob_market` | `market_created` | - | - | [`ClobMarket`](#clobmarket) | |
| `clob_market` | `market_resolved` | - | - | [`ClobMarket`](#clobmarket) | |
## Auth
### ClobAuth
```typescript
/**
* API key credentials for CLOB authentication.
*/
export interface ClobApiKeyCreds {
/** API key used for authentication */
key: string;
/** API secret associated with the key */
secret: string;
/** Passphrase required for authentication */
passphrase: string;
}
```
```typescript
client.subscribe({
subscriptions: [
{
topic: "clob_user",
type: "*",
clob_auth: {
key: "xxxxxx-xxxx-xxxxx-xxxx-xxxxxx",
secret: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
passphrase: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
},
},
],
});
```
## Message types
### Activity
#### Trade
| Name | Type | Description |
| ----------------- | ------- | -------------------------------------------------- |
| `asset` | string | ERC1155 token ID of conditional token being traded |
| `bio` | string | Bio of the user of the trade |
| `conditionId` | string | Id of market which is also the CTF condition ID |
| `eventSlug` | string | Slug of the event |
| `icon` | string | URL to the market icon image |
| `name` | string | Name of the user of the trade |
| `outcome` | string | Human readable outcome of the market |
| `outcomeIndex` | integer | Index of the outcome |
| `price` | float | Price of the trade |
| `profileImage` | string | URL to the user profile image |
| `proxyWallet` | string | Address of the user proxy wallet |
| `pseudonym` | string | Pseudonym of the user |
| `side` | string | Side of the trade (`BUY`/`SELL`) |
| `size` | integer | Size of the trade |
| `slug` | string | Slug of the market |
| `timestamp` | integer | Timestamp of the trade |
| `title` | string | Title of the event |
| `transactionHash` | string | Hash of the transaction |
### Comments
#### Comment
| Name | Type | Description |
| ------------------ | ------ | ------------------------------------------- |
| `id` | string | Unique identifier of comment |
| `body` | string | Content of the comment |
| `parentEntityType` | string | Type of the parent entity (Event or Series) |
| `parentEntityID` | number | ID of the parent entity |
| `parentCommentID` | string | ID of the parent comment |
| `userAddress` | string | Address of the user |
| `replyAddress` | string | Address of the reply user |
| `createdAt` | string | Creation timestamp |
| `updatedAt` | string | Last update timestamp |
#### Reaction
| Name | Type | Description |
| -------------- | ------ | ------------------------------ |
| `id` | string | Unique identifier of reaction |
| `commentID` | number | ID of the comment |
| `reactionType` | string | Type of the reaction |
| `icon` | string | Icon representing the reaction |
| `userAddress` | string | Address of the user |
| `createdAt` | string | Creation timestamp |
### RFQ
#### Request
| Name | Type | Description |
| -------------- | ------ | --------------------------------------------------------------- |
| `requestId` | string | Unique identifier for the request |
| `proxyAddress` | string | User proxy address |
| `market` | string | Id of market which is also the CTF condition ID |
| `token` | string | `ERC1155` token ID of conditional token being traded |
| `complement` | string | Complement `ERC1155` token ID of conditional token being traded |
| `state` | string | Current state of the request |
| `side` | string | Indicates buy or sell side |
| `sizeIn` | number | Input size of the request |
| `sizeOut` | number | Output size of the request |
| `price` | number | Price from in/out sizes |
| `expiry` | number | Expiry timestamp (UNIX format) |
#### Quote
| Name | Type | Description |
| -------------- | ------ | --------------------------------------------------------------- |
| `quoteId` | string | Unique identifier for the quote |
| `requestId` | string | Associated request identifier |
| `proxyAddress` | string | User proxy address |
| `token` | string | `ERC1155` token ID of conditional token being traded |
| `state` | string | Current state of the quote |
| `side` | string | Indicates buy or sell side |
| `sizeIn` | number | Input size of the quote |
| `sizeOut` | number | Output size of the quote |
| `sizeOut` | number | Output size of the request |
| `condition` | string | Id of market which is also the CTF condition ID |
| `complement` | string | Complement `ERC1155` token ID of conditional token being traded |
| `expiry` | number | Expiry timestamp (UNIX format) |
### CryptoPrice
| Name | Type | Description |
| ----------- | ------ | ---------------------------------------- |
| `symbol` | string | Symbol of the asset |
| `timestamp` | number | Timestamp in milliseconds for the update |
| `value` | number | Value at the time of update |
#### Filters
- `{"symbol":"btcusdt"}`
- `{"symbol":"ethusdt"}`
- `{"symbol":"xrpusdt"}`
- `{"symbol":"solusdt"}`
#### Initial data dump on connection
When the connection is stablished, if a `filter` is used, the server will dump an initial snapshoot of recent data
| Name | Type | Description |
| ------ | ------ | ---------------------------------------------------------------- |
| symbol | string | Symbol of the asset |
| data | array | Array of price data objects, each containing timestamp and value |
### CLOB User
#### Order
| Name | Type | Description |
| --------------- | ------------------ | --------------------------------------------------------- |
| `asset_id` | string | Order's `ERC1155` token ID of conditional token |
| `created_at` | string (timestamp) | Order's creation UNIX timestamp |
| `expiration` | string (timestamp) | Order's expiration UNIX timestamp |
| `id` | string | Unique order hash identifier |
| `maker_address` | string | Makers address (funder) |
| `market` | string | Condition ID or market identifier |
| `order_type` | string | Type of order: `GTC`, `GTD`, `FOK`, `FAK` |
| `original_size` | string | Original size of the order at placement |
| `outcome` | string | Order outcome: `YES` / `NO` |
| `owner` | string | UUID of the order owner |
| `price` | string | Order price (e.g., in decimals like `0.5`) |
| `side` | string | Side of the trade: `BUY` or `SELL` |
| `size_matched` | string | Amount of order that has been matched |
| `status` | string | Status of the order (e.g., `MATCHED`) |
| `type` | string | Type of update: `PLACEMENT`, `CANCELLATION`, `FILL`, etc. |
#### Trade
| Name | Type | Description |
| ------------------ | ------------------ | ----------------------------------------------------------------- |
| `asset_id` | string | `ERC1155` token ID of the conditional token involved in the trade |
| `fee_rate_bps` | string | Fee rate in basis points (bps) |
| `id` | string | Unique identifier for the match record |
| `last_update` | string (timestamp) | Last update timestamp (UNIX) |
| `maker_address` | string | Makers address |
| `maker_orders` | array | List of maker orders (see nested schema below) |
| `market` | string | Condition ID or market identifier |
| `match_time` | string (timestamp) | Match execution timestamp (UNIX) |
| `outcome` | string | Outcome of the market: `YES` / `NO` |
| `owner` | string | UUID of the taker (owner of the matched order) |
| `price` | string | Matched price (in decimal format, e.g., `0.5`) |
| `side` | string | Taker side of the trade: `BUY` or `SELL` |
| `size` | string | Total matched size |
| `status` | string | Status of the match: e.g., `MINED` |
| `taker_order_id` | string | ID of the taker's order |
| `transaction_hash` | string | Transaction hash where the match was settled |
##### `maker_orders`
| Name | Type | Description |
| ---------------- | ------ | ---------------------------------------------------------------- |
| `asset_id` | string | `ERC1155` token ID of the conditional token of the maker's order |
| `fee_rate_bps` | string | Maker's fee rate in basis points |
| `maker_address` | string | Makers address |
| `matched_amount` | string | Amount matched from the maker's order |
| `order_id` | string | ID of the maker's order |
| `outcome` | string | Outcome targeted by the maker's order (`YES` / `NO`) |
| `owner` | string | UUID of the maker |
| `price` | string | Order price |
| `side` | string | Side of the maker: `BUY` or `SELL` |
### CLOB market
#### PriceChanges
| Name | Type | Description |
| ------------------- | ------------------ | --------------------------------------------------------- |
| `m` (market) | string | Condition ID |
| `pc` (price change) | array | Price changes by book |
| `t` (timestamp) | string (timestamp) | Timestamp in milliseconds since epoch (UNIX time \* 1000) |
##### PriceChange
NOTE: Filters are mandatory for this topic/type. Example: `["100","200",...]` (collection of token ids)
| Name | Type | Description |
| --------------- | ------ | --------------------------------------------------------------- |
| `a` (asset_id) | string | Asset identifier |
| `h` (hash) | string | Unique hash ID of the book snapshot |
| `p` (price) | string | Price quoted (e.g., `0.5`) |
| `s` (side) | string | Side of the quote: `BUY` or `SELL` |
| `si` (size) | string | Size or volume available at the quoted price (e.g., `0`, `100`) |
| `ba` (best_ask) | string | Best ask price |
| `bb` (best_bid) | string | Best bid price |
#### AggOrderbook
| Name | Type | Description |
| ---------------- | ------------------ | ----------------------------------------------------------------------- |
| `asks` | array | List of ask aggregated orders (sell side), each with `price` and `size` |
| `asset_id` | string | Asset Id identifier |
| `bids` | array | List of aggregated bid orders (buy side), each with `price` and `size` |
| `hash` | string | Unique hash ID for this orderbook snapshot |
| `market` | string | Market or condition ID |
| `min_order_size` | string | Minimum allowed order size |
| `neg_risk` | boolean | NegRisk or not |
| `tick_size` | string | Minimum tick size |
| `timestamp` | string (timestamp) | Timestamp in milliseconds since epoch (UNIX time \* 1000) |
##### `asks`/`bids` scheema
| Name | Type | Description |
| ------- | ------ | ------------------ |
| `price` | string | Price level |
| `size` | string | Size at that price |
##### Initial data dump on connection
When the connection is stablished, if a `filter` is used, the server will dump an initial snapshoot of recent data
#### LastTradePrice
| Name | Type | Description |
| -------------- | ------ | ---------------------------------- |
| `asset_id` | string | Asset Id identifier |
| `fee_rate_bps` | string | Fee rate in basis points (bps) |
| `market` | string | Market or condition ID |
| `price` | string | Trade price (e.g., `0.5`) |
| `side` | string | Side of the order: `BUY` or `SELL` |
| `size` | string | Size of the trade |
#### TickSizeChange
| Name | Type | Description |
| --------------- | ------ | ------------------------------------ |
| `market` | string | Market or condition ID |
| `asset_id` | string | Array of two `ERC1155` asset ID |
| `old_tick_size` | string | Previous tick size before the change |
| `new_tick_size` | string | Updated tick size after the change |
#### ClobMarket
| Name | Type | Description |
| ---------------- | --------- | ------------------------------------------------------------------ |
| `market` | string | Market or condition ID |
| `asset_ids` | [2]string | Array of two `ERC1155` asset ID identifiers associated with market |
| `min_order_size` | string | Minimum size allowed for an order |
| `tick_size` | string | Minimum allowable price increment |
| `neg_risk` | boolean | Indicates if the market is negative risk |

File diff suppressed because it is too large Load Diff

143
skills/postgresql/SKILL.md Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,11 @@
# Postgresql Documentation Index
## Categories
### Getting Started
**File:** `getting_started.md`
**Pages:** 36
### Sql
**File:** `sql.md`
**Pages:** 460

File diff suppressed because it is too large Load Diff

291
skills/proxychains/SKILL.md Normal file
View File

@ -0,0 +1,291 @@
---
name: proxychains
description: Auto-detect network issues and force proxy usage with proxychains4. Use this skill when encountering connection timeouts, DNS failures, or blocked network access. Default proxy is http://127.0.0.1:9910
---
# Proxychains Network Proxy Skill
**自动使用代理解决网络问题** - 当遇到网络连接失败、超时或访问受限时,自动使用 proxychains4 强制走代理。
## When to Use This Skill
**触发条件(自动应用):**
- ❌ Connection timeout errors
- ❌ DNS resolution failures
- ❌ "Connection refused" errors
- ❌ HTTP 403/451 blocked access
- ❌ GitHub/PyPI/npm 等国外资源访问失败
- ❌ curl/wget/git/pip 等命令失败
**Claude 应该:**
1. 检测到网络错误后,自动在命令前添加 `proxychains4`
2. 使用默认代理配置:`http://127.0.0.1:9910`
3. 如果代理失败,提示用户检查代理服务状态
## Quick Reference
### 基本用法模式
```bash
# ❌ 原命令失败
curl https://github.com/user/repo
# ✅ 使用代理重试
proxychains4 curl https://github.com/user/repo
```
### 常见场景自动应用
**场景 1: Git 操作失败**
```bash
# 原命令
git clone https://github.com/user/repo.git
# 自动改为
proxychains4 git clone https://github.com/user/repo.git
```
**场景 2: Python pip 安装失败**
```bash
# 原命令
pip install requests
# 自动改为
proxychains4 pip install requests
```
**场景 3: npm/yarn 安装失败**
```bash
# 原命令
npm install package-name
# 自动改为
proxychains4 npm install package-name
```
**场景 4: wget/curl 下载失败**
```bash
# 原命令
wget https://example.com/file.tar.gz
# 自动改为
proxychains4 wget https://example.com/file.tar.gz
```
**场景 5: Docker 拉取镜像失败**
```bash
# 原命令
docker pull image:tag
# 自动改为
proxychains4 docker pull image:tag
```
**场景 6: SSH 连接失败**
```bash
# 原命令
ssh user@remote-host
# 自动改为
proxychains4 ssh user@remote-host
```
## 配置详情
### 默认代理配置
**本地代理地址:** `http://127.0.0.1:9910`
**配置文件位置:**
- `~/.proxychains/proxychains.conf` (推荐)
- `/etc/proxychains.conf` (系统级)
### 快速配置脚本
创建用户级配置(自动使用 127.0.0.1:9910
```bash
mkdir -p ~/.proxychains
cat > ~/.proxychains/proxychains.conf << 'EOF'
# Proxychains configuration
strict_chain
proxy_dns
remote_dns_subnet 224
tcp_read_time_out 15000
tcp_connect_time_out 8000
[ProxyList]
http 127.0.0.1 9910
EOF
```
### 环境变量方式(临时使用)
```bash
# 设置代理环境变量
export PROXYCHAINS_SOCKS5_HOST=127.0.0.1
export PROXYCHAINS_SOCKS5_PORT=9910
# 使用
proxychains4 curl https://github.com
```
## 工作原理
Proxychains 通过 LD_PRELOAD 机制拦截程序的网络调用:
1. **拦截系统调用**Hook socket 相关的 libc 函数
2. **重定向连接**:将所有 TCP 连接重定向到代理服务器
3. **DNS 代理**:通过代理服务器解析域名
4. **透明代理**:应用程序无需修改
**重要限制:**
- 只支持动态链接的程序statically linked 程序不支持)
- 只支持 TCP 连接UDP 不支持)
- 部分使用特殊网络库的程序可能不兼容
## Claude 自动化规则
### 规则 1: 网络错误自动重试
```
IF 命令返回网络相关错误timeout, connection refused, DNS failure
THEN 自动使用 proxychains4 重试该命令
```
### 规则 2: 已知慢速源强制代理
```
IF 访问以下域名/服务:
- github.com
- raw.githubusercontent.com
- pypi.org
- npmjs.org
- registry.npmjs.org
- docker.io
- gcr.io
THEN 直接使用 proxychains4不等待失败
```
### 规则 3: 失败提示
```
IF proxychains4 命令也失败
THEN 提示用户:
1. 检查代理服务是否运行127.0.0.1:9910
2. 检查 proxychains 配置文件
3. 尝试其他代理地址
```
## 故障排除
### 检查代理服务状态
```bash
# 测试代理是否可用
curl -x http://127.0.0.1:9910 https://www.google.com
# 检查端口是否监听
netstat -tunlp | grep 9910
# 或
ss -tunlp | grep 9910
```
### 验证 proxychains 配置
```bash
# 测试配置是否正确
proxychains4 curl https://ipinfo.io/json
# 应该显示代理服务器的 IP而不是本机 IP
```
### 常见错误处理
**错误 1: "proxychains: command not found"**
```bash
# 安装 proxychains4
sudo apt install proxychains4 # Debian/Ubuntu
sudo yum install proxychains-ng # CentOS/RHEL
```
**错误 2: "timeout"**
```bash
# 检查代理地址配置是否正确
cat ~/.proxychains/proxychains.conf | grep -A 2 "\[ProxyList\]"
# 修改超时时间(在配置文件中)
tcp_connect_time_out 15000
tcp_read_time_out 30000
```
**错误 3: "can't read configuration file"**
```bash
# 创建配置文件
mkdir -p ~/.proxychains
cp /etc/proxychains.conf ~/.proxychains/proxychains.conf
# 然后编辑配置
```
## 高级用法
### 多代理链
```conf
# ~/.proxychains/proxychains.conf
strict_chain # 按顺序使用所有代理
[ProxyList]
http 127.0.0.1 9910
socks5 127.0.0.1 1080
```
### 动态代理链
```conf
dynamic_chain # 自动跳过死代理
[ProxyList]
http 127.0.0.1 9910
http 127.0.0.1 8080
socks5 127.0.0.1 1080
```
### 随机代理链
```conf
random_chain
chain_len = 2 # 随机选择 2 个代理
[ProxyList]
http 127.0.0.1 9910
socks5 127.0.0.1 1080
socks5 127.0.0.1 1081
```
### 自定义 DNS 服务器
```bash
# 使用自定义 DNS 通过代理解析
export PROXY_DNS_SERVER=8.8.8.8
proxychains4 curl https://example.com
```
## 参考资源
- **官方仓库**: https://github.com/haad/proxychains
- **配置文件**: `references/proxychains.conf` (完整示例)
- **故障排除**: `references/troubleshooting.md`
- **命令速查**: `references/quick-reference.md`
## 总结
**记住这些原则:**
1. ❌ **遇到网络错误** → ✅ 自动加上 `proxychains4`
2. 🌐 **访问国外资源** → ✅ 主动使用 `proxychains4`
3. 🔧 **代理也失败** → ✅ 提示用户检查代理服务
**默认代理:** `http://127.0.0.1:9910`
---
**这个技能让 Claude 在遇到网络问题时自动使用代理,无需用户手动干预!**

View File

@ -0,0 +1,101 @@
# Proxychains 参考文档索引
## 核心文档
- **proxychains.conf** - 完整配置文件示例(针对 127.0.0.1:9910 优化)
- **quick-reference.md** - 快速命令参考和常见场景
- **troubleshooting.md** - 故障排除指南
- **setup-guide.md** - 安装和初始配置指南
## 使用场景
本技能包专为以下场景设计:
1. **自动代理重试** - Claude 检测到网络错误时自动使用代理
2. **已知慢速源** - 访问 GitHub、PyPI、npm 等自动走代理
3. **一键配置** - 快速配置代理指向 127.0.0.1:9910
## 快速开始
### 1. 安装 proxychains4
```bash
# Ubuntu/Debian
sudo apt install proxychains4
# CentOS/RHEL
sudo yum install proxychains-ng
# macOS
brew install proxychains-ng
```
### 2. 配置代理127.0.0.1:9910
```bash
mkdir -p ~/.proxychains
cat > ~/.proxychains/proxychains.conf << 'EOF'
strict_chain
proxy_dns
remote_dns_subnet 224
tcp_read_time_out 15000
tcp_connect_time_out 8000
[ProxyList]
http 127.0.0.1 9910
EOF
```
### 3. 测试代理
```bash
# 测试配置
proxychains4 curl https://ipinfo.io/json
# 应该显示代理服务器的 IP 地址
```
## 核心概念
**Proxychains 工作原理:**
- 通过 LD_PRELOAD 拦截程序的 socket 调用
- 将所有 TCP 连接重定向到代理服务器
- 支持 HTTP、SOCKS4、SOCKS5 代理协议
- 透明代理,应用程序无需修改
**适用范围:**
- ✅ 动态链接的程序
- ✅ TCP 连接
- ✅ HTTP/HTTPS 请求
- ❌ 静态链接程序
- ❌ UDP 连接
## 参考文档说明
### proxychains.conf
完整的配置文件模板,已针对 127.0.0.1:9910 优化,包含:
- 超时时间设置
- DNS 代理配置
- 代理链模式选择
### quick-reference.md
快速命令参考,包含:
- 常用命令模式
- 不同工具的代理使用方法
- 环境变量配置
### troubleshooting.md
故障排除指南,包含:
- 常见错误和解决方案
- 代理服务检查方法
- 配置验证步骤
### setup-guide.md
详细的安装和配置指南,包含:
- 不同系统的安装方法
- 配置文件详解
- 高级配置选项
---
**使用提示:** Claude 会自动使用这些参考文档中的信息来帮助解决网络问题。

View File

@ -0,0 +1,79 @@
# Proxychains 配置文件
# 针对本地代理 127.0.0.1:9910 优化
# 代理链模式(三选一)
# ===========================
# strict_chain - 严格按顺序使用所有代理(推荐)
# 所有代理必须在线,任何一个失败则整个链失败
strict_chain
# dynamic_chain - 动态代理链
# 自动跳过离线代理,至少需要一个可用
#dynamic_chain
# random_chain - 随机代理链
# 从列表中随机选择代理
#random_chain
#chain_len = 2 # 随机链长度
# 代理 DNS 请求
# ===========================
# 通过代理服务器解析 DNS避免 DNS 泄漏
proxy_dns
# DNS 解析设置
# ===========================
# remote_dns_subnet - 用于代理 DNS 的虚拟子网
# 默认 224范围 1-255
remote_dns_subnet 224
# 超时设置(毫秒)
# ===========================
# tcp_read_time_out - 读取超时
tcp_read_time_out 15000
# tcp_connect_time_out - 连接超时
tcp_connect_time_out 8000
# 日志设置
# ===========================
# 安静模式(不输出代理链信息)
# quiet_mode
# 代理列表
# ===========================
# 格式type host port [username password]
# 支持类型http, socks4, socks5
#
# 示例:
# http 127.0.0.1 8080 username password
# socks4 127.0.0.1 1080
# socks5 127.0.0.1 1080 username password
[ProxyList]
# 默认本地代理127.0.0.1:9910
http 127.0.0.1 9910
# 备用代理(取消注释以启用)
# ===========================
# http 127.0.0.1 8080
# socks5 127.0.0.1 1080
# 使用说明
# ===========================
# 1. 将此文件保存为:
# ~/.proxychains/proxychains.conf (用户级,推荐)
# /etc/proxychains.conf (系统级)
#
# 2. 测试配置:
# proxychains4 curl https://ipinfo.io/json
#
# 3. 使用示例:
# proxychains4 git clone https://github.com/user/repo.git
# proxychains4 pip install package-name
# proxychains4 npm install package-name
#
# 4. 检查代理服务:
# netstat -tunlp | grep 9910
# curl -x http://127.0.0.1:9910 https://www.google.com

View File

@ -0,0 +1,379 @@
# Proxychains 快速参考
## 基本语法
```bash
proxychains4 [command] [arguments]
```
## 常用命令模式
### Git 操作
```bash
# 克隆仓库
proxychains4 git clone https://github.com/user/repo.git
# 拉取更新
proxychains4 git pull
# 推送代码
proxychains4 git push origin main
# 添加子模块
proxychains4 git submodule update --init --recursive
```
### Python/pip
```bash
# 安装包
proxychains4 pip install requests
proxychains4 pip install -r requirements.txt
# 升级包
proxychains4 pip install --upgrade package-name
# 搜索包
proxychains4 pip search package-name
# 使用国内镜像 + 代理(双保险)
proxychains4 pip install -i https://pypi.tuna.tsinghua.edu.cn/simple package-name
```
### Node.js/npm/yarn
```bash
# npm 安装
proxychains4 npm install package-name
proxychains4 npm install -g package-name
proxychains4 npm install
# yarn 安装
proxychains4 yarn add package-name
proxychains4 yarn install
# 清理缓存后安装
proxychains4 npm cache clean --force
proxychains4 npm install
```
### curl/wget
```bash
# curl 下载
proxychains4 curl -O https://example.com/file.tar.gz
proxychains4 curl -L https://example.com/redirect
# wget 下载
proxychains4 wget https://example.com/file.tar.gz
proxychains4 wget -c https://example.com/large-file.iso
# API 请求
proxychains4 curl -X POST https://api.example.com/endpoint
```
### Docker
```bash
# 拉取镜像
proxychains4 docker pull ubuntu:latest
proxychains4 docker pull nginx:alpine
# 构建镜像(如果需要下载基础镜像)
proxychains4 docker build -t myapp:latest .
# 推送镜像
proxychains4 docker push myregistry.com/myapp:latest
```
### SSH/SCP
```bash
# SSH 连接
proxychains4 ssh user@remote-host
# SCP 文件传输
proxychains4 scp file.txt user@remote-host:/path/
proxychains4 scp -r folder/ user@remote-host:/path/
# rsync 同步
proxychains4 rsync -avz folder/ user@remote-host:/path/
```
### 其他工具
```bash
# telnet
proxychains4 telnet example.com 80
# nc (netcat)
proxychains4 nc example.com 80
# ftp
proxychains4 ftp ftp.example.com
# svn
proxychains4 svn checkout https://example.com/svn/repo
# mercurial (hg)
proxychains4 hg clone https://example.com/hg/repo
```
## 配置文件选项
### 指定配置文件
```bash
# 使用自定义配置文件
proxychains4 -f /path/to/proxychains.conf curl https://example.com
# 使用当前目录配置
proxychains4 -f ./proxychains.conf command
```
### 环境变量方式
```bash
# 设置代理主机和端口SOCKS5
export PROXYCHAINS_SOCKS5_HOST=127.0.0.1
export PROXYCHAINS_SOCKS5_PORT=9910
proxychains4 curl https://example.com
# 指定配置文件路径
export PROXYCHAINS_CONF_FILE=~/.proxychains/custom.conf
proxychains4 command
# 自定义 DNS 服务器
export PROXY_DNS_SERVER=8.8.8.8
proxychains4 curl https://example.com
```
### 启动代理会话
```bash
# 在代理环境中启动 shell
proxychains4 bash
# 或
proxychains4 zsh
# 然后所有命令都会通过代理
git clone https://github.com/user/repo.git
pip install requests
npm install package-name
# 退出代理会话
exit
```
## 诊断和测试
### 测试代理连接
```bash
# 测试 HTTP 代理
proxychains4 curl https://ipinfo.io/json
proxychains4 curl https://ifconfig.me
# 测试特定网站
proxychains4 curl -I https://github.com
proxychains4 curl -I https://google.com
# 详细输出(调试)
proxychains4 -q curl -v https://example.com
```
### 检查代理服务
```bash
# 检查端口是否监听
netstat -tunlp | grep 9910
ss -tunlp | grep 9910
lsof -i :9910
# 测试代理直接连接(不用 proxychains
curl -x http://127.0.0.1:9910 https://www.google.com
curl -x socks5://127.0.0.1:1080 https://www.google.com
# 测试代理认证
curl -x http://username:password@127.0.0.1:9910 https://www.google.com
```
### DNS 解析测试
```bash
# 通过代理解析 DNS
proxychains4 nslookup google.com
proxychains4 dig google.com
# 使用 proxyresolv 工具proxychains 自带)
proxyresolv google.com
proxyresolv github.com
```
## 快速配置生成
### 单行命令创建配置
```bash
# 创建用户级配置HTTP 代理 127.0.0.1:9910
mkdir -p ~/.proxychains && cat > ~/.proxychains/proxychains.conf << 'EOF'
strict_chain
proxy_dns
remote_dns_subnet 224
tcp_read_time_out 15000
tcp_connect_time_out 8000
[ProxyList]
http 127.0.0.1 9910
EOF
# 创建 SOCKS5 配置
mkdir -p ~/.proxychains && cat > ~/.proxychains/proxychains.conf << 'EOF'
strict_chain
proxy_dns
[ProxyList]
socks5 127.0.0.1 1080
EOF
```
### 临时配置(当前目录)
```bash
# 在当前目录创建临时配置
cat > proxychains.conf << 'EOF'
strict_chain
proxy_dns
[ProxyList]
http 127.0.0.1 9910
EOF
# 使用临时配置
proxychains4 -f ./proxychains.conf curl https://github.com
```
## 性能优化
### 减少延迟
```bash
# 配置文件中调整超时
tcp_connect_time_out 5000 # 5秒
tcp_read_time_out 10000 # 10秒
# 使用 quiet_mode 减少输出
quiet_mode
```
### 并行下载
```bash
# aria2 多线程下载
proxychains4 aria2c -x 16 https://example.com/large-file.iso
# wget 多连接下载
proxychains4 wget --limit-rate=10m https://example.com/file.tar.gz
```
## 常见组合场景
### 场景 1: Python 项目依赖安装
```bash
# 克隆项目
proxychains4 git clone https://github.com/user/project.git
cd project
# 创建虚拟环境
python3 -m venv venv
source venv/bin/activate
# 安装依赖
proxychains4 pip install -r requirements.txt
```
### 场景 2: Node.js 项目初始化
```bash
# 克隆项目
proxychains4 git clone https://github.com/user/project.git
cd project
# 安装依赖
proxychains4 npm install
# 或
proxychains4 yarn install
# 运行项目(如果需要下载额外资源)
proxychains4 npm start
```
### 场景 3: Docker 镜像构建
```bash
# 拉取基础镜像
proxychains4 docker pull node:18-alpine
# 构建镜像Dockerfile 中有 FROM 远程镜像)
proxychains4 docker build -t myapp:latest .
# 推送到仓库
proxychains4 docker push myregistry.com/myapp:latest
```
### 场景 4: 系统软件更新
```bash
# Ubuntu/Debian
proxychains4 sudo apt update
proxychains4 sudo apt upgrade
# CentOS/RHEL
proxychains4 sudo yum update
# Arch Linux
proxychains4 sudo pacman -Syu
```
## 别名设置(可选)
```bash
# 添加到 ~/.bashrc 或 ~/.zshrc
alias pc='proxychains4'
alias pcgit='proxychains4 git'
alias pcpip='proxychains4 pip'
alias pcnpm='proxychains4 npm'
alias pccurl='proxychains4 curl'
alias pcwget='proxychains4 wget'
# 使用别名
pc curl https://github.com
pcgit clone https://github.com/user/repo.git
pcpip install requests
```
## 故障排除快速检查清单
```bash
# 1. 检查 proxychains 是否安装
which proxychains4
# 2. 检查配置文件是否存在
ls -la ~/.proxychains/proxychains.conf
cat ~/.proxychains/proxychains.conf
# 3. 检查代理服务是否运行
netstat -tunlp | grep 9910
# 4. 测试代理直接连接
curl -x http://127.0.0.1:9910 https://www.google.com
# 5. 测试 proxychains 连接
proxychains4 curl https://ipinfo.io/json
# 6. 查看详细错误信息
proxychains4 curl -v https://example.com
```
---
**提示:** 将常用命令保存为 shell 脚本或别名,可以提高效率。

View File

@ -0,0 +1,640 @@
# Proxychains 安装和配置指南
## 安装 Proxychains
### Linux 系统
#### Ubuntu/Debian
```bash
# 更新包列表
sudo apt update
# 安装 proxychains4
sudo apt install proxychains4
# 验证安装
proxychains4 --version
```
#### CentOS/RHEL 7/8
```bash
# 安装 EPEL 仓库
sudo yum install epel-release
# 安装 proxychains-ng
sudo yum install proxychains-ng
# 验证安装
proxychains4 --version
```
#### Fedora
```bash
# 安装 proxychains-ng
sudo dnf install proxychains-ng
# 验证安装
proxychains4 --version
```
#### Arch Linux
```bash
# 安装 proxychains-ng
sudo pacman -S proxychains-ng
# 验证安装
proxychains4 --version
```
#### 从源码编译(通用方法)
```bash
# 安装依赖
sudo apt install build-essential git # Debian/Ubuntu
# 或
sudo yum install gcc git make # CentOS/RHEL
# 克隆仓库
git clone https://github.com/haad/proxychains.git
cd proxychains
# 编译安装
./configure --prefix=/usr --sysconfdir=/etc
make
sudo make install
sudo make install-config # 安装默认配置文件
# 验证安装
proxychains4 --version
```
### macOS
```bash
# 使用 Homebrew 安装
brew install proxychains-ng
# 验证安装
proxychains4 --version
```
### WSL (Windows Subsystem for Linux)
```bash
# 在 WSL 中安装(使用 Ubuntu 示例)
sudo apt update
sudo apt install proxychains4
# 验证安装
proxychains4 --version
```
---
## 基础配置
### 配置文件位置
Proxychains 按以下顺序查找配置文件:
1. `${PROXYCHAINS_CONF_FILE}` 环境变量指定的路径
2. 命令行 `-f` 参数指定的路径
3. `./proxychains.conf` (当前目录)
4. `~/.proxychains/proxychains.conf` (用户主目录) **推荐**
5. `/etc/proxychains.conf` (系统级)
### 创建用户级配置(推荐)
```bash
# 创建配置目录
mkdir -p ~/.proxychains
# 创建配置文件(针对 127.0.0.1:9910
cat > ~/.proxychains/proxychains.conf << 'EOF'
# Proxychains 配置文件
# 代理地址127.0.0.1:9910
# 代理链模式
strict_chain
# 代理 DNS 请求
proxy_dns
# DNS 设置
remote_dns_subnet 224
# 超时设置(毫秒)
tcp_read_time_out 15000
tcp_connect_time_out 8000
# 代理列表
[ProxyList]
http 127.0.0.1 9910
EOF
# 设置权限
chmod 644 ~/.proxychains/proxychains.conf
```
### 创建系统级配置(可选)
```bash
# 需要 root 权限
sudo cat > /etc/proxychains.conf << 'EOF'
strict_chain
proxy_dns
remote_dns_subnet 224
tcp_read_time_out 15000
tcp_connect_time_out 8000
[ProxyList]
http 127.0.0.1 9910
EOF
# 设置权限
sudo chmod 644 /etc/proxychains.conf
```
---
## 配置详解
### 代理链模式
在配置文件中只能选择一种模式:
#### strict_chain严格链推荐
```conf
# 严格按顺序使用所有代理
# 所有代理必须在线,任何一个失败则整个链失败
strict_chain
```
**适用场景:**
- 只有一个代理服务器
- 需要确保所有代理都被使用
- 对安全性要求高
#### dynamic_chain动态链
```conf
# 自动跳过离线代理
# 至少需要一个可用代理
dynamic_chain
```
**适用场景:**
- 有多个代理服务器
- 某些代理可能不稳定
- 需要自动故障转移
#### random_chain随机链
```conf
# 从列表中随机选择代理
random_chain
chain_len = 2 # 随机链长度(可选)
```
**适用场景:**
- 需要隐藏流量模式
- 有多个代理可用
- 对匿名性要求高
### DNS 设置
```conf
# 通过代理服务器解析 DNS
proxy_dns
# DNS 解析使用的虚拟子网1-255
remote_dns_subnet 224
# 可选:自定义 DNS 服务器(通过环境变量)
# export PROXY_DNS_SERVER=8.8.8.8
```
### 超时设置
```conf
# TCP 读取超时(毫秒)
tcp_read_time_out 15000 # 15秒
# TCP 连接超时(毫秒)
tcp_connect_time_out 8000 # 8秒
```
**调优建议:**
- 慢速网络:增加到 30000 和 15000
- 快速网络:减少到 10000 和 5000
- 本地代理:可以设置为 5000 和 3000
### 日志设置
```conf
# 静默模式(不输出代理链信息)
quiet_mode
```
**注意:** 调试时应注释掉此选项以查看详细输出。
---
## 代理列表配置
### 基本格式
```conf
[ProxyList]
# 格式type host port [username password]
```
### HTTP 代理
```conf
# 不需要认证
http 127.0.0.1 9910
# 需要认证
http 127.0.0.1 8080 username password
```
### SOCKS4 代理
```conf
# 不需要认证
socks4 127.0.0.1 1080
# SOCKS4 不支持用户认证
```
### SOCKS5 代理
```conf
# 不需要认证
socks5 127.0.0.1 1080
# 需要认证
socks5 127.0.0.1 1080 username password
```
### 多代理配置
```conf
[ProxyList]
# 主代理
http 127.0.0.1 9910
# 备用代理strict_chain 模式下会按顺序使用)
# 取消注释以启用
#http 127.0.0.1 8080
#socks5 127.0.0.1 1080
```
### 代理链示例
```conf
# 多级代理(流量经过多个代理)
strict_chain
[ProxyList]
http 127.0.0.1 9910
socks5 proxy2.example.com 1080
http proxy3.example.com 8080
```
---
## 高级配置
### 使用环境变量
```bash
# SOCKS5 代理(简化配置)
export PROXYCHAINS_SOCKS5_HOST=127.0.0.1
export PROXYCHAINS_SOCKS5_PORT=9910
proxychains4 curl https://github.com
# 指定配置文件
export PROXYCHAINS_CONF_FILE=~/.proxychains/custom.conf
proxychains4 command
# 自定义 DNS 服务器
export PROXY_DNS_SERVER=8.8.8.8
proxychains4 curl https://example.com
```
### 多配置文件管理
```bash
# 为不同场景创建不同配置文件
mkdir -p ~/.proxychains
# 国内代理配置
cat > ~/.proxychains/cn.conf << 'EOF'
strict_chain
proxy_dns
[ProxyList]
http 127.0.0.1 9910
EOF
# 国外代理配置
cat > ~/.proxychains/intl.conf << 'EOF'
strict_chain
proxy_dns
[ProxyList]
socks5 proxy.example.com 1080
EOF
# 使用特定配置
proxychains4 -f ~/.proxychains/cn.conf curl https://github.com
proxychains4 -f ~/.proxychains/intl.conf curl https://google.com
```
### 创建 Shell 别名
```bash
# 添加到 ~/.bashrc 或 ~/.zshrc
cat >> ~/.bashrc << 'EOF'
# Proxychains 别名
alias pc='proxychains4'
alias pccn='proxychains4 -f ~/.proxychains/cn.conf'
alias pcintl='proxychains4 -f ~/.proxychains/intl.conf'
# 常用命令别名
alias pcgit='proxychains4 git'
alias pcpip='proxychains4 pip'
alias pcnpm='proxychains4 npm'
alias pccurl='proxychains4 curl'
alias pcwget='proxychains4 wget'
alias pcssh='proxychains4 ssh'
EOF
# 重新加载配置
source ~/.bashrc
```
---
## 测试配置
### 基本连接测试
```bash
# 测试 proxychains 是否工作
proxychains4 curl https://ipinfo.io/json
# 应该显示代理服务器的 IP 地址,而不是本机 IP
```
### 对比测试
```bash
# 不使用代理的 IP
curl https://ipinfo.io/json
# 使用代理的 IP应该不同
proxychains4 curl https://ipinfo.io/json
```
### DNS 测试
```bash
# 测试 DNS 解析
proxychains4 nslookup google.com
proxychains4 dig github.com
# 使用 proxyresolv 工具
proxyresolv google.com
```
### 完整功能测试
```bash
# HTTP 请求
proxychains4 curl -I https://github.com
# HTTPS 请求
proxychains4 curl https://www.google.com
# SSH 连接(如果有测试服务器)
proxychains4 ssh user@example.com
# Git 克隆
proxychains4 git clone https://github.com/haad/proxychains.git /tmp/test-repo
```
---
## 与代理软件集成
### V2Ray
```bash
# 假设 V2Ray HTTP 代理端口是 10809
# 更新 proxychains 配置
cat > ~/.proxychains/proxychains.conf << 'EOF'
strict_chain
proxy_dns
[ProxyList]
http 127.0.0.1 10809
EOF
```
### Clash
```bash
# 假设 Clash HTTP 代理端口是 7890
# 更新 proxychains 配置
cat > ~/.proxychains/proxychains.conf << 'EOF'
strict_chain
proxy_dns
[ProxyList]
http 127.0.0.1 7890
EOF
```
### Shadowsocks
```bash
# 假设 Shadowsocks SOCKS5 端口是 1080
# 更新 proxychains 配置
cat > ~/.proxychains/proxychains.conf << 'EOF'
strict_chain
proxy_dns
[ProxyList]
socks5 127.0.0.1 1080
EOF
```
### SSH 动态端口转发
```bash
# 创建 SSH 动态端口转发SOCKS5
ssh -fN -D 1080 user@remote-server
# 配置 proxychains 使用 SSH 隧道
cat > ~/.proxychains/proxychains.conf << 'EOF'
strict_chain
proxy_dns
[ProxyList]
socks5 127.0.0.1 1080
EOF
# 使用
proxychains4 curl https://example.com
```
---
## 常见配置模板
### 模板 1: 单个 HTTP 代理(默认)
```conf
strict_chain
proxy_dns
remote_dns_subnet 224
tcp_read_time_out 15000
tcp_connect_time_out 8000
[ProxyList]
http 127.0.0.1 9910
```
### 模板 2: 单个 SOCKS5 代理
```conf
strict_chain
proxy_dns
remote_dns_subnet 224
tcp_read_time_out 15000
tcp_connect_time_out 8000
[ProxyList]
socks5 127.0.0.1 1080
```
### 模板 3: 多代理动态链(自动故障转移)
```conf
dynamic_chain
proxy_dns
remote_dns_subnet 224
tcp_read_time_out 15000
tcp_connect_time_out 8000
[ProxyList]
http 127.0.0.1 9910
http 127.0.0.1 8080
socks5 127.0.0.1 1080
```
### 模板 4: 低延迟优化
```conf
strict_chain
proxy_dns
remote_dns_subnet 224
tcp_read_time_out 10000
tcp_connect_time_out 5000
quiet_mode
[ProxyList]
http 127.0.0.1 9910
```
---
## 持久化配置
### 系统启动时自动使用代理
**不推荐全局使用,仅对特定用户/命令使用**
```bash
# 创建启动脚本(示例)
cat > ~/start-with-proxy.sh << 'EOF'
#!/bin/bash
proxychains4 bash
EOF
chmod +x ~/start-with-proxy.sh
```
### 为特定应用创建包装脚本
```bash
# Git 包装脚本
cat > ~/bin/git-proxy << 'EOF'
#!/bin/bash
proxychains4 git "$@"
EOF
chmod +x ~/bin/git-proxy
# 使用
git-proxy clone https://github.com/user/repo.git
```
---
## 故障排除配置
如果遇到问题,使用此配置进行调试:
```conf
# 调试配置
strict_chain
proxy_dns
remote_dns_subnet 224
tcp_read_time_out 30000
tcp_connect_time_out 15000
# 注释掉 quiet_mode 以查看详细输出
[ProxyList]
http 127.0.0.1 9910
```
---
## 安全建议
1. **配置文件权限**
```bash
chmod 644 ~/.proxychains/proxychains.conf
```
2. **不要在配置文件中明文存储密码**
- 如果必须使用认证,确保配置文件权限正确
- 考虑使用环境变量
3. **定期更新 proxychains**
```bash
sudo apt update && sudo apt upgrade proxychains4
```
4. **验证代理服务器可信度**
- 只使用信任的代理服务器
- 避免使用公共免费代理
---
## 下一步
配置完成后:
1. 阅读 `quick-reference.md` 了解常用命令
2. 阅读 `troubleshooting.md` 了解问题解决
3. 开始使用 proxychains4
---
**提示:** 配置文件修改后立即生效,无需重启服务。

View File

@ -0,0 +1,475 @@
# Proxychains 故障排除指南
## 常见错误及解决方案
### 错误 1: "proxychains: command not found"
**症状:**
```bash
$ proxychains4 curl https://github.com
bash: proxychains4: command not found
```
**原因:** proxychains 未安装
**解决方案:**
```bash
# Ubuntu/Debian
sudo apt update
sudo apt install proxychains4
# CentOS/RHEL
sudo yum install epel-release
sudo yum install proxychains-ng
# Fedora
sudo dnf install proxychains-ng
# macOS
brew install proxychains-ng
# Arch Linux
sudo pacman -S proxychains-ng
# 验证安装
proxychains4 --version
```
---
### 错误 2: "can't read configuration file"
**症状:**
```bash
$ proxychains4 curl https://github.com
[proxychains] can't read configuration file /etc/proxychains.conf
```
**原因:** 配置文件不存在或路径错误
**解决方案:**
```bash
# 方法 1: 创建用户级配置文件
mkdir -p ~/.proxychains
cat > ~/.proxychains/proxychains.conf << 'EOF'
strict_chain
proxy_dns
[ProxyList]
http 127.0.0.1 9910
EOF
# 方法 2: 复制系统配置模板
sudo cp /usr/share/doc/proxychains*/proxychains.conf /etc/
# 或
sudo cp /usr/local/etc/proxychains.conf /etc/
# 方法 3: 指定配置文件路径
proxychains4 -f /path/to/proxychains.conf curl https://github.com
# 验证配置文件
cat ~/.proxychains/proxychains.conf
```
---
### 错误 3: "timeout"
**症状:**
```bash
$ proxychains4 curl https://github.com
[proxychains] Strict chain ... 127.0.0.1:9910 ... github.com:443 ... timeout
curl: (28) Connection timed out after 10000 milliseconds
```
**原因:** 代理服务未运行、端口错误或防火墙阻止
**解决方案:**
```bash
# 1. 检查代理服务是否运行
netstat -tunlp | grep 9910
ss -tunlp | grep 9910
lsof -i :9910
# 2. 测试代理服务直接连接
curl -x http://127.0.0.1:9910 https://www.google.com
# 3. 检查防火墙规则
sudo iptables -L -n | grep 9910
sudo ufw status
# 4. 确认代理配置正确
cat ~/.proxychains/proxychains.conf | grep -A 2 "\[ProxyList\]"
# 5. 增加超时时间(编辑配置文件)
tcp_connect_time_out 15000
tcp_read_time_out 30000
# 6. 如果代理服务未运行,启动代理服务
# (根据你的代理软件,例如:)
# v2ray、clash、shadowsocks 等
```
---
### 错误 4: "connection refused"
**症状:**
```bash
$ proxychains4 curl https://github.com
[proxychains] Strict chain ... 127.0.0.1:9910 ... connect refused
curl: (7) Failed to connect to 127.0.0.1 port 9910: Connection refused
```
**原因:** 代理端口未监听或代理服务未启动
**解决方案:**
```bash
# 1. 确认代理服务状态
# 检查你的代理软件是否运行v2ray、clash、shadowsocks 等)
# 2. 验证代理端口
netstat -tunlp | grep 9910
# 如果没有输出,说明端口未监听
# 3. 检查代理软件配置
# 确认代理软件监听的端口是 9910
# 4. 尝试其他可能的代理端口
# 常见端口1080 (SOCKS), 7890 (HTTP), 8080 (HTTP)
netstat -tunlp | grep -E '1080|7890|8080|9910'
# 5. 更新 proxychains 配置为正确端口
nano ~/.proxychains/proxychains.conf
# 修改 [ProxyList] 部分:
# http 127.0.0.1 [正确的端口]
# 6. 重启代理服务
# 根据你的代理软件执行相应命令
```
---
### 错误 5: "DNS request timed out"
**症状:**
```bash
$ proxychains4 curl https://github.com
[proxychains] DNS request timed out
curl: (6) Could not resolve host: github.com
```
**原因:** DNS 解析失败或 proxy_dns 配置问题
**解决方案:**
```bash
# 1. 检查配置文件中的 proxy_dns 设置
cat ~/.proxychains/proxychains.conf | grep proxy_dns
# 应该有proxy_dns
# 2. 如果没有,添加 proxy_dns
nano ~/.proxychains/proxychains.conf
# 添加:
proxy_dns
remote_dns_subnet 224
# 3. 测试 DNS 解析
proxychains4 nslookup github.com
proxychains4 dig github.com
# 4. 使用自定义 DNS 服务器
export PROXY_DNS_SERVER=8.8.8.8
proxychains4 curl https://github.com
# 5. 或者使用 IP 地址直接访问(跳过 DNS
proxychains4 curl https://140.82.114.4 # GitHub IP
# 6. 检查 /etc/resolv.conf
cat /etc/resolv.conf
# 确保有有效的 nameserver
```
---
### 错误 6: "Program not supported"
**症状:**
```bash
$ proxychains4 ./static-binary
[proxychains] Program not supported
```
**原因:** 程序是静态链接的proxychains 只支持动态链接程序
**解决方案:**
```bash
# 1. 检查程序是否静态链接
ldd ./program
# 如果输出 "not a dynamic executable",则为静态链接
# 2. 对于静态链接程序,需要其他方案:
# - 使用系统级代理iptables 转发)
# - 使用 VPN
# - 使用容器级代理
# 3. Go 程序示例(通常是静态链接)
# 设置环境变量而不是用 proxychains
export HTTP_PROXY=http://127.0.0.1:9910
export HTTPS_PROXY=http://127.0.0.1:9910
./go-program
# 4. 对于可重新编译的程序
# 编译为动态链接版本
```
---
### 错误 7: "strict chain ... all proxy servers are down"
**症状:**
```bash
$ proxychains4 curl https://github.com
[proxychains] strict chain ... all proxy servers are down!
curl: (97) Failure in receiving network data
```
**原因:** strict_chain 模式下所有代理都不可用
**解决方案:**
```bash
# 1. 测试代理列表中的每个代理
cat ~/.proxychains/proxychains.conf | grep -A 10 "\[ProxyList\]"
# 逐个测试
curl -x http://127.0.0.1:9910 https://www.google.com
curl -x http://127.0.0.1:8080 https://www.google.com
# 2. 切换到 dynamic_chain 模式(自动跳过死代理)
nano ~/.proxychains/proxychains.conf
# 注释掉:#strict_chain
# 启用dynamic_chain
# 3. 或者移除不可用的代理
nano ~/.proxychains/proxychains.conf
# 只保留可用的代理在 [ProxyList] 中
# 4. 重新测试
proxychains4 curl https://ipinfo.io/json
```
---
### 错误 8: "Permission denied"
**症状:**
```bash
$ proxychains4 curl https://github.com
[proxychains] Permission denied
```
**原因:** 配置文件或 proxychains 可执行文件权限问题
**解决方案:**
```bash
# 1. 检查配置文件权限
ls -la ~/.proxychains/proxychains.conf
# 2. 修复权限
chmod 644 ~/.proxychains/proxychains.conf
# 3. 检查目录权限
ls -la ~/.proxychains/
# 4. 修复目录权限
chmod 755 ~/.proxychains/
# 5. 检查 proxychains 可执行文件权限
ls -la $(which proxychains4)
# 6. 如果是系统级配置文件
sudo chmod 644 /etc/proxychains.conf
```
---
## 高级故障排除
### 调试模式
```bash
# 启用详细输出
# 编辑配置文件,注释掉 quiet_mode
nano ~/.proxychains/proxychains.conf
# 注释:#quiet_mode
# 使用 strace 跟踪系统调用
strace -e trace=network proxychains4 curl https://github.com
# 查看环境变量
env | grep -i proxy
```
### 日志分析
```bash
# proxychains 输出到文件
proxychains4 curl https://github.com 2>&1 | tee proxychains.log
# 分析连接过程
cat proxychains.log | grep -E 'chain|connect|timeout'
```
### 网络连通性测试
```bash
# 测试本地连接
ping 127.0.0.1
telnet 127.0.0.1 9910
# 测试外部连接(不通过代理)
curl https://ipinfo.io/json
# 测试外部连接(通过代理)
proxychains4 curl https://ipinfo.io/json
# 比较 IP 地址
# 不通过代理的 IP 应该是本机 IP
# 通过代理的 IP 应该是代理服务器 IP
```
### 配置验证
```bash
# 验证配置文件语法
proxychains4 -f ~/.proxychains/proxychains.conf true
# 测试不同的代理类型
# HTTP
proxychains4 -f - curl https://github.com << 'EOF'
strict_chain
[ProxyList]
http 127.0.0.1 9910
EOF
# SOCKS5
proxychains4 -f - curl https://github.com << 'EOF'
strict_chain
[ProxyList]
socks5 127.0.0.1 1080
EOF
```
---
## 性能问题
### 连接缓慢
**症状:** 命令执行很慢
**解决方案:**
```bash
# 1. 减少超时时间
nano ~/.proxychains/proxychains.conf
tcp_connect_time_out 5000
tcp_read_time_out 10000
# 2. 启用 quiet_mode 减少输出
quiet_mode
# 3. 使用更快的代理服务器
# 4. 测试代理延迟
time proxychains4 curl -I https://github.com
# 5. 使用 dynamic_chain 跳过慢速代理
dynamic_chain
```
### 频繁断开
**症状:** 连接经常中断
**解决方案:**
```bash
# 1. 增加超时时间
tcp_read_time_out 30000
# 2. 检查代理服务器稳定性
# 持续 ping 测试
ping -c 100 127.0.0.1
# 3. 更换代理服务器
# 4. 检查网络稳定性
mtr 8.8.8.8
```
---
## 检查清单
使用此清单快速诊断问题:
```bash
# ✅ 检查 1: proxychains 已安装
which proxychains4
# ✅ 检查 2: 配置文件存在
ls -la ~/.proxychains/proxychains.conf
# ✅ 检查 3: 配置文件格式正确
cat ~/.proxychains/proxychains.conf
# ✅ 检查 4: 代理服务运行中
netstat -tunlp | grep 9910
# ✅ 检查 5: 代理可直接访问
curl -x http://127.0.0.1:9910 https://www.google.com
# ✅ 检查 6: DNS 解析正常
proxychains4 nslookup github.com
# ✅ 检查 7: proxychains 连接正常
proxychains4 curl https://ipinfo.io/json
# ✅ 检查 8: IP 地址已变更
# 对比直接访问和代理访问的 IP 应该不同
curl https://ipinfo.io/json
proxychains4 curl https://ipinfo.io/json
```
---
## 获取帮助
如果以上方法都无法解决问题:
```bash
# 查看帮助文档
man proxychains4
proxychains4 --help
# 查看系统日志
sudo journalctl -xe | grep proxy
dmesg | grep -i proxy
# 检查 proxychains 版本
proxychains4 --version
# GitHub Issues
# https://github.com/haad/proxychains/issues
```
---
**提示:** 大多数问题都是由于代理服务未运行或端口配置错误造成的。首先确保代理服务正常运行。

View File

@ -0,0 +1,122 @@
#!/bin/bash
# Proxychains 快速配置脚本
# 自动配置代理指向 127.0.0.1:9910
set -e
echo "=========================================="
echo "Proxychains 快速配置脚本"
echo "=========================================="
echo
# 检查 proxychains4 是否安装
if ! command -v proxychains4 &> /dev/null; then
echo "❌ proxychains4 未安装"
echo
echo "请先安装 proxychains4"
echo
echo " Ubuntu/Debian:"
echo " sudo apt install proxychains4"
echo
echo " CentOS/RHEL:"
echo " sudo yum install epel-release"
echo " sudo yum install proxychains-ng"
echo
echo " macOS:"
echo " brew install proxychains-ng"
echo
exit 1
fi
echo "✅ proxychains4 已安装"
echo
# 创建配置目录
echo "📁 创建配置目录..."
mkdir -p ~/.proxychains
# 创建配置文件
echo "📝 创建配置文件..."
cat > ~/.proxychains/proxychains.conf << 'EOF'
# Proxychains 配置文件
# 代理地址127.0.0.1:9910
# 代理链模式(严格按顺序使用所有代理)
strict_chain
# 代理 DNS 请求(避免 DNS 泄漏)
proxy_dns
# DNS 设置
remote_dns_subnet 224
# 超时设置(毫秒)
tcp_read_time_out 15000
tcp_connect_time_out 8000
# 代理列表
[ProxyList]
# HTTP 代理127.0.0.1:9910
http 127.0.0.1 9910
# 备用代理(取消注释以启用)
#http 127.0.0.1 8080
#socks5 127.0.0.1 1080
EOF
# 设置权限
chmod 644 ~/.proxychains/proxychains.conf
echo "✅ 配置文件已创建: ~/.proxychains/proxychains.conf"
echo
# 测试代理服务
echo "🔍 检查代理服务..."
if curl -s -x http://127.0.0.1:9910 --connect-timeout 3 https://www.google.com > /dev/null 2>&1; then
echo "✅ 代理服务 127.0.0.1:9910 可用"
echo
# 测试 proxychains
echo "🧪 测试 proxychains..."
if proxychains4 curl -s --connect-timeout 5 https://ipinfo.io/json > /dev/null 2>&1; then
echo "✅ Proxychains 配置成功!"
echo
echo "🎉 配置完成!可以开始使用了。"
else
echo "⚠️ Proxychains 测试失败"
echo " 但配置文件已创建,请检查代理服务是否正常"
fi
else
echo "⚠️ 代理服务 127.0.0.1:9910 无法连接"
echo
echo "请检查:"
echo " 1. 代理服务是否运行"
echo " 2. 代理端口是否正确127.0.0.1:9910"
echo " 3. 防火墙设置"
echo
echo "检查代理端口:"
echo " netstat -tunlp | grep 9910"
echo " ss -tunlp | grep 9910"
echo
echo "配置文件已创建,代理服务就绪后即可使用。"
fi
echo
echo "=========================================="
echo "使用方法:"
echo "=========================================="
echo
echo " proxychains4 curl https://github.com"
echo " proxychains4 git clone https://github.com/user/repo.git"
echo " proxychains4 pip install package-name"
echo " proxychains4 npm install package-name"
echo
echo "配置文件位置:"
echo " ~/.proxychains/proxychains.conf"
echo
echo "查看配置:"
echo " cat ~/.proxychains/proxychains.conf"
echo
echo "修改代理地址:"
echo " nano ~/.proxychains/proxychains.conf"
echo "=========================================="

274
skills/snapdom/SKILL.md Normal file
View File

@ -0,0 +1,274 @@
---
name: snapdom
description: snapDOM is a fast, accurate DOM-to-image capture tool that converts HTML elements into scalable SVG images. Use for capturing HTML elements, converting DOM to images (SVG, PNG, JPG, WebP), preserving styles, fonts, and pseudo-elements.
---
# SnapDOM Skill
Fast, dependency-free DOM-to-image capture library for converting HTML elements into scalable SVG or raster image formats.
## When to Use This Skill
Use SnapDOM when you need to:
- Convert HTML elements to images (SVG, PNG, JPG, WebP)
- Capture styled DOM with pseudo-elements and shadows
- Export elements with embedded fonts and icons
- Create screenshots with custom dimensions or scaling
- Handle CORS-blocked resources using proxy fallback
- Implement custom rendering pipelines with plugins
- Optimize performance on large or complex elements
## Key Features
### Universal Export Options
- **SVG** - Scalable vector format, embeds all styles
- **PNG, JPG, WebP** - Raster formats with configurable quality
- **Canvas** - Get raw Canvas element for further processing
- **Blob** - Raw binary data for custom handling
### Performance
- Ultra-fast capture (1.6ms for small elements, ~171ms for 4000×2000)
- **No dependencies** - Uses standard Web APIs only
- Outperforms html2canvas by 10-40x on complex elements
### Style Support
- Embedded fonts (including icon fonts)
- CSS pseudo-elements (::before, ::after)
- CSS counters
- CSS line-clamp
- Transform and shadow effects
- Shadow DOM content
### Advanced Capabilities
- Same-origin iframe support
- CORS proxy fallback for blocked assets
- Plugin system for custom transformations
- Straighten transforms (remove rotate/translate)
- Selective element exclusion
- Tight bounding box calculation
## Installation
### NPM/Yarn
```bash
npm install @zumer/snapdom
# or
yarn add @zumer/snapdom
```
### CDN (ES Module)
```html
<script type="module">
import { snapdom } from "https://unpkg.com/@zumer/snapdom/dist/snapdom.mjs";
</script>
```
### CDN (UMD)
```html
<script src="https://unpkg.com/@zumer/snapdom/dist/snapdom.umd.js"></script>
```
## Quick Start Examples
### Basic Reusable Capture
```javascript
// Create reusable capture object
const result = await snapdom(document.querySelector('#target'));
// Export to different formats
const png = await result.toPng();
const jpg = await result.toJpg();
const svg = await result.toSvg();
const canvas = await result.toCanvas();
const blob = await result.toBlob();
// Use the result
document.body.appendChild(png);
```
### One-Step Export
```javascript
// Direct export without intermediate object
const png = await snapdom.toPng(document.querySelector('#target'));
const svg = await snapdom.toSvg(element);
```
### Download Element
```javascript
// Automatically download as file
await snapdom.download(element, 'screenshot.png');
await snapdom.download(element, 'image.svg');
```
### With Options
```javascript
const result = await snapdom(element, {
scale: 2, // 2x resolution
width: 800, // Custom width
height: 600, // Custom height
embedFonts: true, // Include @font-face
exclude: '.no-capture', // Hide elements
useProxy: true, // Enable CORS proxy
straighten: true, // Remove transforms
noShadows: false // Keep shadows
});
const png = await result.toPng({ quality: 0.95 });
```
## Essential Options Reference
| Option | Type | Purpose |
|--------|------|---------|
| `scale` | Number | Scale output (e.g., 2 for 2x resolution) |
| `width` | Number | Custom output width in pixels |
| `height` | Number | Custom output height in pixels |
| `embedFonts` | Boolean | Include non-icon @font-face rules |
| `useProxy` | String\|Boolean | Enable CORS proxy (URL or true for default) |
| `exclude` | String | CSS selector for elements to hide |
| `straighten` | Boolean | Remove translate/rotate transforms |
| `noShadows` | Boolean | Strip shadow effects |
## Common Patterns
### Responsive Screenshots
```javascript
// Capture at different scales
const mobile = await snapdom.toPng(element, { scale: 1 });
const tablet = await snapdom.toPng(element, { scale: 1.5 });
const desktop = await snapdom.toPng(element, { scale: 2 });
```
### Exclude Elements
```javascript
// Hide specific elements from capture
const png = await snapdom.toPng(element, {
exclude: '.controls, .watermark, [data-no-capture]'
});
```
### Fixed Dimensions
```javascript
// Capture with specific size
const result = await snapdom(element, {
width: 1200,
height: 630 // Standard social media size
});
```
### CORS Handling
```javascript
// Fallback for CORS-blocked resources
const png = await snapdom.toPng(element, {
useProxy: 'https://cors.example.com/?' // Custom proxy
});
```
### Plugin System (Beta)
```javascript
// Extend with custom exporters
snapdom.plugins([pluginFactory, { colorOverlay: true }]);
// Hook into lifecycle
defineExports(context) {
return {
pdf: async (ctx, opts) => { /* generate PDF */ }
};
}
// Lifecycle hooks available:
// beforeSnap → beforeClone → afterClone →
// beforeRender → beforeExport → afterExport
```
## Performance Comparison
SnapDOM significantly outperforms html2canvas:
| Scenario | SnapDOM | html2canvas | Improvement |
|----------|---------|-------------|-------------|
| Small (200×100) | 1.6ms | 68ms | 42x faster |
| Medium (800×600) | 12ms | 280ms | 23x faster |
| Large (4000×2000) | 171ms | 1,800ms | 10x faster |
## Development
### Setup
```bash
git clone https://github.com/zumerlab/snapdom.git
cd snapdom
npm install
```
### Build
```bash
npm run compile
```
### Testing
```bash
npm test
```
## Browser Support
- Chrome/Edge 90+
- Firefox 88+
- Safari 14+
- Mobile browsers (iOS Safari 14+, Chrome Mobile)
## Resources
### Documentation
- **Official Website:** https://snapdom.dev/
- **GitHub Repository:** https://github.com/zumerlab/snapdom
- **NPM Package:** https://www.npmjs.com/package/@zumer/snapdom
- **License:** MIT
### scripts/
Add helper scripts here for automation, e.g.:
- `batch-screenshot.js` - Capture multiple elements
- `pdf-export.js` - Convert snapshots to PDF
- `compare-outputs.js` - Compare SVG vs PNG quality
### assets/
Add templates and examples:
- HTML templates for common capture scenarios
- CSS frameworks pre-configured with snapdom
- Boilerplate projects integrating snapdom
## Related Tools
- **html2canvas** - Alternative DOM capture (slower but more compatible)
- **Orbit CSS Toolkit** - Companion toolkit by Zumerlab (https://github.com/zumerlab/orbit)
## Tips & Best Practices
1. **Performance**: Use `scale` instead of `width`/`height` for better performance
2. **Fonts**: Set `embedFonts: true` to ensure custom fonts appear correctly
3. **CORS Issues**: Use `useProxy: true` if images fail to load
4. **Large Elements**: Break into smaller chunks for complex pages
5. **Quality**: For PNG/JPG, use `quality: 0.95` for best quality
6. **SVG Vectors**: Prefer SVG export for charts and graphics
## Troubleshooting
### Elements Not Rendering
- Check if element has sufficient height/width
- Verify CSS is fully loaded before capture
- Try `straighten: false` if transforms are causing issues
### Missing Fonts
- Set `embedFonts: true`
- Ensure fonts are loaded before calling snapdom
- Check browser console for font loading errors
### CORS Issues
- Enable `useProxy: true`
- Use custom proxy URL if default fails
- Check if resources are from same origin
### Performance Issues
- Reduce `scale` value
- Use `noShadows: true` to skip shadow rendering
- Consider splitting large captures into smaller sections

View File

@ -0,0 +1,7 @@
# Snapdom Documentation Index
## Categories
### Other
**File:** `other.md`
**Pages:** 1

View File

@ -0,0 +1,53 @@
# Snapdom - Other
**Pages:** 1
---
## snapDOM HTML to Image capture with superior accuracy and speed - Now with Plugins!
**URL:** https://snapdom.dev/
**Contents:**
- 🏁 Benchmark: snapDOM vs html2canvas
- 📦 Basic
- Hello SnapDOM!
- Transforms & Shadows
- 🅰️ ASCII Plugin
- 🕒 Timestamp Plugin
- 🚀 Fun Transition
- Orbit CSS toolkit - Go to repo
- 🔤 Google Fonts
- Unique Typography!
Each library will capture the same DOM element to canvas 5 times. We'll calculate average speed and show the winner.
Capture it just with outerTransforms / outerShadows.
I'm dancing and changing color!
Google Fonts with embedFonts: true.
**Examples:**
Example 1 (unknown):
```unknown
outerTransforms
```
Example 2 (unknown):
```unknown
outerShadows
```
Example 3 (unknown):
```unknown
outerTransforms
```
Example 4 (unknown):
```unknown
outerShadows
```
---

View File

@ -0,0 +1,760 @@
---
name: telegram-dev
description: Telegram 生态开发全栈指南 - 涵盖 Bot API、Mini Apps (Web Apps)、MTProto 客户端开发。包括消息处理、支付、内联模式、Webhook、认证、存储、传感器 API 等完整开发资源。
---
# Telegram 生态开发技能
全面的 Telegram 开发指南,涵盖 Bot 开发、Mini Apps (Web Apps)、客户端开发的完整技术栈。
## 何时使用此技能
当需要以下帮助时使用此技能:
- 开发 Telegram Bot消息机器人
- 创建 Telegram Mini Apps小程序
- 构建自定义 Telegram 客户端
- 集成 Telegram 支付和业务功能
- 实现 Webhook 和长轮询
- 使用 Telegram 认证和存储
- 处理消息、媒体和文件
- 实现内联模式和键盘
## Telegram 开发生态概览
### 三大核心 API
1. **Bot API** - 创建机器人程序
- HTTP 接口,简单易用
- 自动处理加密和通信
- 适合:聊天机器人、自动化工具
2. **Mini Apps API** (Web Apps) - 创建 Web 应用
- JavaScript 接口
- 在 Telegram 内运行
- 适合:小程序、游戏、电商
3. **Telegram API & TDLib** - 创建客户端
- 完整的 Telegram 协议实现
- 支持所有平台
- 适合:自定义客户端、企业应用
## Bot API 开发
### 快速开始
**API 端点:**
```
https://api.telegram.org/bot<TOKEN>/METHOD_NAME
```
**获取 Bot Token**
1. 与 @BotFather 对话
2. 发送 `/newbot`
3. 按提示设置名称
4. 获取 token
**第一个 Bot (Python)**
```python
import requests
BOT_TOKEN = "your_bot_token_here"
API_URL = f"https://api.telegram.org/bot{BOT_TOKEN}"
# 发送消息
def send_message(chat_id, text):
url = f"{API_URL}/sendMessage"
data = {"chat_id": chat_id, "text": text}
return requests.post(url, json=data)
# 获取更新(长轮询)
def get_updates(offset=None):
url = f"{API_URL}/getUpdates"
params = {"offset": offset, "timeout": 30}
return requests.get(url, params=params).json()
# 主循环
offset = None
while True:
updates = get_updates(offset)
for update in updates.get("result", []):
chat_id = update["message"]["chat"]["id"]
text = update["message"]["text"]
# 回复消息
send_message(chat_id, f"你说了:{text}")
offset = update["update_id"] + 1
```
### 核心 API 方法
**更新管理:**
- `getUpdates` - 长轮询获取更新
- `setWebhook` - 设置 Webhook
- `deleteWebhook` - 删除 Webhook
- `getWebhookInfo` - 查询 Webhook 状态
**消息操作:**
- `sendMessage` - 发送文本消息
- `sendPhoto` / `sendVideo` / `sendDocument` - 发送媒体
- `sendAudio` / `sendVoice` - 发送音频
- `sendLocation` / `sendVenue` - 发送位置
- `editMessageText` - 编辑消息
- `deleteMessage` - 删除消息
- `forwardMessage` / `copyMessage` - 转发/复制消息
**交互元素:**
- `sendPoll` - 发送投票(最多 12 个选项)
- 内联键盘 (InlineKeyboardMarkup)
- 回复键盘 (ReplyKeyboardMarkup)
- `answerCallbackQuery` - 响应回调查询
**文件操作:**
- `getFile` - 获取文件信息
- `downloadFile` - 下载文件
- 支持最大 2GB 文件(本地 Bot API 模式)
**支付功能:**
- `sendInvoice` - 发送发票
- `answerPreCheckoutQuery` - 处理支付
- Telegram Stars 支付(最高 10,000 Stars
### Webhook 配置
**设置 Webhook**
```python
import requests
BOT_TOKEN = "your_token"
WEBHOOK_URL = "https://yourdomain.com/webhook"
requests.post(
f"https://api.telegram.org/bot{BOT_TOKEN}/setWebhook",
json={"url": WEBHOOK_URL}
)
```
**Flask Webhook 示例:**
```python
from flask import Flask, request
import requests
app = Flask(__name__)
BOT_TOKEN = "your_token"
@app.route('/webhook', methods=['POST'])
def webhook():
update = request.get_json()
chat_id = update["message"]["chat"]["id"]
text = update["message"]["text"]
# 发送回复
requests.post(
f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage",
json={"chat_id": chat_id, "text": f"收到: {text}"}
)
return "OK"
if __name__ == '__main__':
app.run(port=5000)
```
**Webhook 要求:**
- 必须使用 HTTPS
- 支持 TLS 1.2+
- 端口443, 80, 88, 8443
- 公共可访问的 URL
### 内联键盘
**创建内联键盘:**
```python
def send_inline_keyboard(chat_id):
keyboard = {
"inline_keyboard": [
[
{"text": "按钮 1", "callback_data": "btn1"},
{"text": "按钮 2", "callback_data": "btn2"}
],
[
{"text": "打开链接", "url": "https://example.com"}
]
]
}
requests.post(
f"{API_URL}/sendMessage",
json={
"chat_id": chat_id,
"text": "选择一个选项:",
"reply_markup": keyboard
}
)
```
**处理回调:**
```python
def handle_callback_query(callback_query):
query_id = callback_query["id"]
data = callback_query["data"]
chat_id = callback_query["message"]["chat"]["id"]
# 响应回调
requests.post(
f"{API_URL}/answerCallbackQuery",
json={"callback_query_id": query_id, "text": f"你点击了 {data}"}
)
# 更新消息
requests.post(
f"{API_URL}/editMessageText",
json={
"chat_id": chat_id,
"message_id": callback_query["message"]["message_id"],
"text": f"你选择了:{data}"
}
)
```
### 内联模式
**配置内联模式:**
@BotFather 对话,发送 `/setinline`
**处理内联查询:**
```python
def handle_inline_query(inline_query):
query_id = inline_query["id"]
query_text = inline_query["query"]
# 创建结果
results = [
{
"type": "article",
"id": "1",
"title": "结果 1",
"input_message_content": {
"message_text": f"你搜索了:{query_text}"
}
}
]
requests.post(
f"{API_URL}/answerInlineQuery",
json={"inline_query_id": query_id, "results": results}
)
```
## Mini Apps (Web Apps) 开发
### 初始化 Mini App
**HTML 模板:**
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://telegram.org/js/telegram-web-app.js"></script>
<title>My Mini App</title>
</head>
<body>
<h1>Telegram Mini App</h1>
<button id="mainBtn">主按钮</button>
<script>
// 获取 Telegram WebApp 对象
const tg = window.Telegram.WebApp;
// 通知 Telegram 应用已准备好
tg.ready();
// 展开到全屏
tg.expand();
// 显示用户信息
const user = tg.initDataUnsafe?.user;
if (user) {
console.log("用户名:", user.first_name);
console.log("用户ID:", user.id);
}
// 配置主按钮
tg.MainButton.text = "提交";
tg.MainButton.show();
tg.MainButton.onClick(() => {
// 发送数据到 Bot
tg.sendData(JSON.stringify({action: "submit"}));
});
// 添加返回按钮
tg.BackButton.show();
tg.BackButton.onClick(() => {
tg.close();
});
</script>
</body>
</html>
```
### Mini App 核心 API
**WebApp 对象主要属性:**
```javascript
// 初始化数据
tg.initData // 原始初始化字符串
tg.initDataUnsafe // 解析后的对象
// 用户和主题
tg.initDataUnsafe.user // 用户信息
tg.themeParams // 主题颜色
tg.colorScheme // 'light' 或 'dark'
// 状态
tg.isExpanded // 是否全屏
tg.isFullscreen // 是否全屏
tg.viewportHeight // 视口高度
tg.platform // 平台类型
// 版本
tg.version // WebApp 版本
```
**主要方法:**
```javascript
// 窗口控制
tg.ready() // 标记应用准备就绪
tg.expand() // 展开到全高度
tg.close() // 关闭 Mini App
tg.requestFullscreen() // 请求全屏
// 数据发送
tg.sendData(data) // 发送数据到 Bot
// 导航
tg.openLink(url) // 打开外部链接
tg.openTelegramLink(url) // 打开 Telegram 链接
// 对话框
tg.showPopup(params, callback) // 显示弹窗
tg.showAlert(message) // 显示警告
tg.showConfirm(message) // 显示确认
// 分享
tg.shareMessage(message) // 分享消息
tg.shareUrl(url) // 分享链接
```
### UI 控件
**主按钮 (MainButton)**
```javascript
tg.MainButton.setText("点击我");
tg.MainButton.show();
tg.MainButton.enable();
tg.MainButton.showProgress(); // 显示加载
tg.MainButton.hideProgress();
tg.MainButton.onClick(() => {
console.log("主按钮被点击");
});
```
**次要按钮 (SecondaryButton)**
```javascript
tg.SecondaryButton.setText("取消");
tg.SecondaryButton.show();
tg.SecondaryButton.onClick(() => {
tg.close();
});
```
**返回按钮 (BackButton)**
```javascript
tg.BackButton.show();
tg.BackButton.onClick(() => {
// 返回逻辑
});
```
**触觉反馈:**
```javascript
tg.HapticFeedback.impactOccurred('light'); // light, medium, heavy
tg.HapticFeedback.notificationOccurred('success'); // success, warning, error
tg.HapticFeedback.selectionChanged();
```
### 存储 API
**云存储:**
```javascript
// 保存数据
tg.CloudStorage.setItem('key', 'value', (error, success) => {
if (success) console.log('保存成功');
});
// 获取数据
tg.CloudStorage.getItem('key', (error, value) => {
console.log('值:', value);
});
// 删除数据
tg.CloudStorage.removeItem('key');
// 获取所有键
tg.CloudStorage.getKeys((error, keys) => {
console.log('所有键:', keys);
});
```
**本地存储:**
```javascript
// 普通本地存储
localStorage.setItem('key', 'value');
const value = localStorage.getItem('key');
// 安全存储(需要生物识别)
tg.SecureStorage.setItem('secret', 'value', callback);
tg.SecureStorage.getItem('secret', callback);
```
### 生物识别认证
```javascript
const bioManager = tg.BiometricManager;
// 初始化
bioManager.init(() => {
if (bioManager.isInited) {
console.log('支持的类型:', bioManager.biometricType);
// 'finger', 'face', 'unknown'
if (bioManager.isAccessGranted) {
// 已授权,可以使用
} else {
// 请求授权
bioManager.requestAccess({reason: '需要验证身份'}, (success) => {
if (success) {
console.log('授权成功');
}
});
}
}
});
// 执行认证
bioManager.authenticate({reason: '确认操作'}, (success, token) => {
if (success) {
console.log('认证成功token:', token);
}
});
```
### 位置和传感器
**获取位置:**
```javascript
tg.LocationManager.init(() => {
if (tg.LocationManager.isInited) {
tg.LocationManager.getLocation((location) => {
console.log('纬度:', location.latitude);
console.log('经度:', location.longitude);
});
}
});
```
**加速度计:**
```javascript
tg.Accelerometer.start({refresh_rate: 100}, (started) => {
if (started) {
tg.Accelerometer.onEvent((event) => {
console.log('加速度:', event.x, event.y, event.z);
});
}
});
// 停止
tg.Accelerometer.stop();
```
**陀螺仪:**
```javascript
tg.Gyroscope.start({refresh_rate: 100}, callback);
tg.Gyroscope.onEvent((event) => {
console.log('旋转速度:', event.x, event.y, event.z);
});
```
**设备方向:**
```javascript
tg.DeviceOrientation.start({refresh_rate: 100}, callback);
tg.DeviceOrientation.onEvent((event) => {
console.log('方向:', event.absolute, event.alpha, event.beta, event.gamma);
});
```
### 支付集成
**发起支付 (Telegram Stars)**
```javascript
tg.openInvoice('https://t.me/$invoice_link', (status) => {
if (status === 'paid') {
console.log('支付成功');
} else if (status === 'cancelled') {
console.log('支付取消');
} else if (status === 'failed') {
console.log('支付失败');
}
});
```
### 数据验证
**服务器端验证 initData (Python)**
```python
import hmac
import hashlib
from urllib.parse import parse_qs
def validate_init_data(init_data, bot_token):
# 解析数据
parsed = parse_qs(init_data)
received_hash = parsed.get('hash', [''])[0]
# 移除 hash
data_check_arr = []
for key, value in parsed.items():
if key != 'hash':
data_check_arr.append(f"{key}={value[0]}")
# 排序
data_check_arr.sort()
data_check_string = '\n'.join(data_check_arr)
# 计算密钥
secret_key = hmac.new(
b"WebAppData",
bot_token.encode(),
hashlib.sha256
).digest()
# 计算哈希
calculated_hash = hmac.new(
secret_key,
data_check_string.encode(),
hashlib.sha256
).hexdigest()
return calculated_hash == received_hash
```
### 启动 Mini App
**从键盘按钮:**
```python
keyboard = {
"keyboard": [[
{
"text": "打开应用",
"web_app": {"url": "https://yourdomain.com/app"}
}
]],
"resize_keyboard": True
}
requests.post(
f"{API_URL}/sendMessage",
json={
"chat_id": chat_id,
"text": "点击按钮打开应用",
"reply_markup": keyboard
}
)
```
**从内联按钮:**
```python
keyboard = {
"inline_keyboard": [[
{
"text": "启动应用",
"web_app": {"url": "https://yourdomain.com/app"}
}
]]
}
```
**从菜单按钮:**
@BotFather 对话:
```
/setmenubutton
→ 选择你的 Bot
→ 提供 URL: https://yourdomain.com/app
```
## 客户端开发 (TDLib)
### 使用 TDLib
**Python 示例 (python-telegram)**
```python
from telegram.client import Telegram
tg = Telegram(
api_id='your_api_id',
api_hash='your_api_hash',
phone='+1234567890',
database_encryption_key='changeme1234',
)
tg.login()
# 发送消息
result = tg.send_message(
chat_id=123456789,
text='Hello from TDLib!'
)
# 获取聊天列表
result = tg.get_chats()
result.wait()
chats = result.update
print(chats)
tg.stop()
```
### MTProto 协议
**特点:**
- 端到端加密
- 高性能
- 支持所有 Telegram 功能
- 需要 API ID/Hash从 https://my.telegram.org 获取)
## 最佳实践
### Bot 开发
1. **错误处理**
```python
try:
response = requests.post(url, json=data, timeout=10)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")
```
2. **速率限制**
- 群组消息:最多 20 条/分钟
- 私聊消息:最多 30 条/秒
- 全局限制:避免过于频繁
3. **使用 Webhook 而非长轮询**
- 更高效
- 更低延迟
- 更好的可扩展性
4. **数据验证**
- 始终验证 initData
- 不要信任客户端数据
- 服务器端验证所有操作
### Mini Apps 开发
1. **响应式设计**
```javascript
// 监听主题变化
tg.onEvent('themeChanged', () => {
document.body.style.backgroundColor = tg.themeParams.bg_color;
});
// 监听视口变化
tg.onEvent('viewportChanged', () => {
console.log('新高度:', tg.viewportHeight);
});
```
2. **性能优化**
- 最小化 JavaScript 包大小
- 使用懒加载
- 优化图片和资源
3. **用户体验**
- 适配深色/浅色主题
- 使用原生 UI 控件MainButton 等)
- 提供触觉反馈
- 快速响应用户操作
4. **安全考虑**
- HTTPS 强制
- 验证 initData
- 不在客户端存储敏感信息
- 使用 SecureStorage 存储密钥
## 常用库和工具
### Python
- `python-telegram-bot` - 功能强大的 Bot 框架
- `aiogram` - 异步 Bot 框架
- `telethon` / `pyrogram` - MTProto 客户端
### Node.js
- `node-telegram-bot-api` - Bot API 包装器
- `telegraf` - 现代 Bot 框架
- `grammy` - 轻量级框架
### 其他语言
- PHP: `telegram-bot-sdk`
- Go: `telegram-bot-api`
- Java: `TelegramBots`
- C#: `Telegram.Bot`
## 参考资源
### 官方文档
- Bot API: https://core.telegram.org/bots/api
- Mini Apps: https://core.telegram.org/bots/webapps
- Mini Apps Platform: https://docs.telegram-mini-apps.com
- Telegram API: https://core.telegram.org
### GitHub 仓库
- Bot API 服务器: https://github.com/tdlib/telegram-bot-api
- Android 客户端: https://github.com/DrKLO/Telegram
- Desktop 客户端: https://github.com/telegramdesktop/tdesktop
- 官方组织: https://github.com/orgs/TelegramOfficial/repositories
### 工具
- @BotFather - 创建和管理 Bot
- https://my.telegram.org - 获取 API ID/Hash
- Telegram Web App 测试环境
## 参考文件
此技能包含详细的 Telegram 开发资源索引和完整实现模板:
- **index.md** - 完整的资源链接和快速导航
- **Telegram_Bot_按钮和键盘实现模板.md** - 交互式按钮和键盘实现指南404 行12 KB
- 三种按钮类型详解Inline/Reply/Command Menu
- python-telegram-bot 和 Telethon 双实现对比
- 完整的即用代码示例和项目结构
- Handler 系统、错误处理和部署方案
- **动态视图对齐实现文档.md** - Telegram 数据展示指南407 行12 KB
- 智能动态对齐算法三步法O(n×m) 复杂度)
- 等宽字体环境的完美对齐方案
- 智能数值格式化系统B/M/K 自动缩写)
- 排行榜和数据表格专业展示
这些精简指南提供了核心的 Telegram Bot 开发解决方案:
- 按钮和键盘交互的所有实现方式
- 消息和数据的专业格式化展示
- 实用的最佳实践和快速参考
---
**使用此技能掌握 Telegram 生态的全栈开发!**

View File

@ -0,0 +1,404 @@
# Telegram Bot 按钮与键盘实现指南
> 完整的 Telegram Bot 交互式功能开发参考
---
## 📋 目录
1. [按钮和键盘类型](#按钮和键盘类型)
2. [实现方式对比](#实现方式对比)
3. [核心代码示例](#核心代码示例)
4. [最佳实践](#最佳实践)
---
## 按钮和键盘类型
### 1. Inline Keyboard内联键盘
**特点**
- 显示在消息下方
- 点击后触发回调,不发送消息
- 支持回调数据、URL、切换查询等
**应用场景**:确认/取消、菜单导航、分页控制、设置选项
### 2. Reply Keyboard底部虚拟键盘
**特点**
- 显示在输入框上方
- 点击后发送文本消息
- 可设置持久化或一次性
**应用场景**:快捷命令、常用操作、表单输入、主菜单
### 3. Bot Command Menu命令菜单
**特点**
- 显示在输入框左侧 "/" 按钮
- 通过 BotFather 或 API 设置
- 提供命令列表和描述
**应用场景**:功能索引、新用户引导、快速命令访问
### 4. 类型对比
| 特性 | Inline | Reply | Command Menu |
|------|--------|-------|--------------|
| 位置 | 消息下方 | 输入框上方 | "/" 菜单 |
| 触发 | 回调查询 | 文本消息 | 命令 |
| 持久化 | 随消息 | 可配置 | 始终存在 |
| 场景 | 临时交互 | 常驻功能 | 命令索引 |
---
## 实现方式对比
### python-telegram-bot推荐 Bot 开发)
**优点**
- 官方推荐,完整的 Handler 系统
- 丰富的按钮和键盘支持
- 异步版本性能优异
**安装**
```bash
pip install python-telegram-bot==20.7
```
### Telethon适合用户账号自动化
**优点**
- 完整的 MTProto API 访问
- 可使用用户账号和 Bot
- 强大的消息监听能力
**安装**
```bash
pip install telethon cryptg
```
---
## 核心代码示例
### 1. Inline Keyboard 实现
**python-telegram-bot**
```python
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, CommandHandler, CallbackQueryHandler, ContextTypes
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""显示内联键盘"""
keyboard = [
[
InlineKeyboardButton("📊 查看数据", callback_data="view_data"),
InlineKeyboardButton("⚙️ 设置", callback_data="settings"),
],
[
InlineKeyboardButton("🔗 访问网站", url="https://example.com"),
],
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text("请选择:", reply_markup=reply_markup)
async def button_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""处理按钮点击"""
query = update.callback_query
await query.answer() # 必须调用
if query.data == "view_data":
await query.edit_message_text("显示数据...")
elif query.data == "settings":
await query.edit_message_text("设置选项...")
# 注册处理器
app = Application.builder().token("TOKEN").build()
app.add_handler(CommandHandler("start", start))
app.add_handler(CallbackQueryHandler(button_callback))
app.run_polling()
```
**Telethon**
```python
from telethon import TelegramClient, events, Button
client = TelegramClient('bot', api_id, api_hash).start(bot_token=BOT_TOKEN)
@client.on(events.NewMessage(pattern='/start'))
async def start(event):
buttons = [
[Button.inline("📊 查看数据", b"view_data"), Button.inline("⚙️ 设置", b"settings")],
[Button.url("🔗 访问网站", "https://example.com")]
]
await event.respond("请选择:", buttons=buttons)
@client.on(events.CallbackQuery)
async def callback(event):
if event.data == b"view_data":
await event.edit("显示数据...")
elif event.data == b"settings":
await event.edit("设置选项...")
client.run_until_disconnected()
```
### 2. Reply Keyboard 实现
**python-telegram-bot**
```python
from telegram import KeyboardButton, ReplyKeyboardMarkup, ReplyKeyboardRemove
async def menu(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""显示底部键盘"""
keyboard = [
[KeyboardButton("📊 查看数据"), KeyboardButton("⚙️ 设置")],
[KeyboardButton("📚 帮助"), KeyboardButton("❌ 隐藏键盘")],
]
reply_markup = ReplyKeyboardMarkup(
keyboard,
resize_keyboard=True,
one_time_keyboard=False
)
await update.message.reply_text("菜单已激活", reply_markup=reply_markup)
async def handle_text(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""处理文本消息"""
text = update.message.text
if text == "📊 查看数据":
await update.message.reply_text("显示数据...")
elif text == "❌ 隐藏键盘":
await update.message.reply_text("已隐藏", reply_markup=ReplyKeyboardRemove())
```
**Telethon**
```python
@client.on(events.NewMessage(pattern='/menu'))
async def menu(event):
buttons = [
[Button.text("📊 查看数据"), Button.text("⚙️ 设置")],
[Button.text("📚 帮助"), Button.text("❌ 隐藏键盘")]
]
await event.respond("菜单已激活", buttons=buttons)
@client.on(events.NewMessage)
async def handle_text(event):
if event.text == "📊 查看数据":
await event.respond("显示数据...")
```
### 3. Bot Command Menu 设置
**通过 BotFather**
```
1. 发送 /setcommands 到 @BotFather
2. 选择你的 Bot
3. 输入命令列表每行格式command - description
start - 启动机器人
help - 获取帮助
menu - 显示主菜单
settings - 配置设置
```
**通过 APIpython-telegram-bot**
```python
from telegram import BotCommand
async def set_commands(app: Application):
"""设置命令菜单"""
commands = [
BotCommand("start", "启动机器人"),
BotCommand("help", "获取帮助"),
BotCommand("menu", "显示主菜单"),
BotCommand("settings", "配置设置"),
]
await app.bot.set_my_commands(commands)
# 在启动时调用
app.post_init = set_commands
```
### 4. 项目结构示例
```
telegram_bot/
├── bot.py # 主程序
├── config.py # 配置管理
├── requirements.txt
├── .env
├── handlers/
│ ├── command_handlers.py # 命令处理器
│ ├── callback_handlers.py # 回调处理器
│ └── message_handlers.py # 消息处理器
├── keyboards/
│ ├── inline_keyboards.py # 内联键盘布局
│ └── reply_keyboards.py # 回复键盘布局
└── utils/
├── logger.py # 日志
└── database.py # 数据库
```
**模块化示例keyboards/inline_keyboards.py**
```python
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
def get_main_menu():
"""主菜单键盘"""
return InlineKeyboardMarkup([
[
InlineKeyboardButton("📊 数据", callback_data="data"),
InlineKeyboardButton("⚙️ 设置", callback_data="settings"),
],
[InlineKeyboardButton("📚 帮助", callback_data="help")],
])
def get_data_menu():
"""数据菜单键盘"""
return InlineKeyboardMarkup([
[
InlineKeyboardButton("📈 实时", callback_data="data_realtime"),
InlineKeyboardButton("📊 历史", callback_data="data_history"),
],
[InlineKeyboardButton("⬅️ 返回", callback_data="back")],
])
```
---
## 最佳实践
### 1. Handler 优先级
```python
# 先注册先匹配,按从特殊到通用的顺序
app.add_handler(CommandHandler("start", start)) # 1. 特定命令
app.add_handler(CallbackQueryHandler(callback)) # 2. 回调查询
app.add_handler(ConversationHandler(...)) # 3. 对话流程
app.add_handler(MessageHandler(filters.TEXT, text_msg)) # 4. 通用消息(最后)
```
### 2. 错误处理
```python
async def error_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""全局错误处理"""
logger.error(f"更新 {update} 引起错误", exc_info=context.error)
# 通知用户
if update and update.effective_message:
await update.effective_message.reply_text("操作失败,请重试")
app.add_error_handler(error_handler)
```
### 3. 回调数据管理
```python
# 使用结构化的 callback_data
callback_data = "action:page:item" # 例如 "view:1:product_123"
# 解析回调数据
async def callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = update.callback_query
parts = query.data.split(":")
action, page, item = parts
if action == "view":
await show_item(query, page, item)
```
### 4. 键盘设计原则
- **简洁**:每行最多 2-3 个按钮
- **清晰**:使用 emoji 增强识别度
- **一致**:保持统一的布局风格
- **响应**:及时反馈用户操作
### 5. 安全考虑
```python
# 验证用户权限
ADMIN_IDS = [123456789]
async def admin_only(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = update.effective_user.id
if user_id not in ADMIN_IDS:
await update.message.reply_text("无权限")
return
# 执行管理员操作
```
### 6. 部署方案
**Webhook推荐生产环境**
```python
from flask import Flask, request
app_flask = Flask(__name__)
@app_flask.route('/webhook', methods=['POST'])
def webhook():
update = Update.de_json(request.get_json(), bot)
application.update_queue.put(update)
return "OK"
# 设置 webhook
bot.set_webhook(f"https://yourdomain.com/webhook")
```
**Systemd ServiceLinux**
```ini
[Unit]
Description=Telegram Bot
After=network.target
[Service]
Type=simple
User=your_user
WorkingDirectory=/path/to/bot
ExecStart=/path/to/venv/bin/python bot.py
Restart=always
[Install]
WantedBy=multi-user.target
```
### 7. 常用库版本
```txt
# requirements.txt
python-telegram-bot==20.7
python-dotenv==1.0.0
aiosqlite==0.19.0
httpx==0.25.2
```
---
## 快速参考
### Inline Keyboard 按钮类型
```python
InlineKeyboardButton("文本", callback_data="data") # 回调按钮
InlineKeyboardButton("链接", url="https://...") # URL按钮
InlineKeyboardButton("切换", switch_inline_query="") # 内联查询
InlineKeyboardButton("登录", login_url=...) # 登录按钮
InlineKeyboardButton("支付", pay=True) # 支付按钮
InlineKeyboardButton("应用", web_app=WebAppInfo(...)) # Mini App
```
### 常用事件类型
- `events.NewMessage` - 新消息
- `events.CallbackQuery` - 回调查询
- `events.InlineQuery` - 内联查询
- `events.ChatAction` - 群组动作
---
**这份指南涵盖了 Telegram Bot 按钮和键盘的所有核心实现!**

View File

@ -0,0 +1,470 @@
# Telegram 生态开发资源索引
## 官方文档
### Bot API
**主文档:** https://core.telegram.org/bots/api
**描述:** Telegram Bot API 完整参考文档
**核心功能:**
- 消息发送和接收
- 媒体文件处理
- 内联模式
- 支付集成
- Webhook 配置
- 游戏和投票
### Mini Apps (Web Apps)
**主文档:** https://core.telegram.org/bots/webapps
**完整平台:** https://docs.telegram-mini-apps.com
**描述:** Telegram 小程序开发文档
**核心功能:**
- WebApp API
- 主题和 UI 控件
- 存储Cloud/Device/Secure
- 生物识别认证
- 位置和传感器
- 支付集成
### Telegram API & MTProto
**主文档:** https://core.telegram.org
**描述:** 完整的 Telegram 协议和客户端开发
**核心功能:**
- MTProto 协议
- TDLib 客户端库
- 认证和加密
- 文件操作
- Secret Chats
## 官方 GitHub 仓库
### Bot API 服务器
**仓库:** https://github.com/tdlib/telegram-bot-api
**描述:** Telegram Bot API 服务器实现
**特点:**
- 本地模式部署
- 支持大文件(最高 2000 MB
- C++ 实现
- TDLib 基础
### Android 客户端
**仓库:** https://github.com/DrKLO/Telegram
**描述:** 官方 Android 客户端源代码
**特点:**
- 完整的 Android 实现
- Material Design
- 可自定义编译
### Desktop 客户端
**仓库:** https://github.com/telegramdesktop/tdesktop
**描述:** 官方桌面客户端 (Windows, macOS, Linux)
**特点:**
- Qt/C++ 实现
- 跨平台支持
- 完整功能
### 官方组织
**组织页面:** https://github.com/orgs/TelegramOfficial/repositories
**包含:**
- Beta 版本
- 支持工具
- 示例代码
## API 方法分类
### 更新管理
- `getUpdates` - 长轮询
- `setWebhook` - 设置 Webhook
- `deleteWebhook` - 删除 Webhook
- `getWebhookInfo` - Webhook 信息
### 消息操作
**发送消息:**
- `sendMessage` - 文本消息
- `sendPhoto` - 图片
- `sendVideo` - 视频
- `sendDocument` - 文档
- `sendAudio` - 音频
- `sendVoice` - 语音
- `sendLocation` - 位置
- `sendVenue` - 地点
- `sendContact` - 联系人
- `sendPoll` - 投票
- `sendDice` - 骰子/飞镖
**编辑消息:**
- `editMessageText` - 编辑文本
- `editMessageCaption` - 编辑标题
- `editMessageMedia` - 编辑媒体
- `editMessageReplyMarkup` - 编辑键盘
- `deleteMessage` - 删除消息
**其他操作:**
- `forwardMessage` - 转发消息
- `copyMessage` - 复制消息
- `sendChatAction` - 发送动作(输入中...
### 文件操作
- `getFile` - 获取文件信息
- 文件下载 URL: `https://api.telegram.org/file/bot<token>/<file_path>`
- 文件上传:支持 multipart/form-data
- 最大文件50 MB (标准), 2000 MB (本地 Bot API)
### 内联模式
- `answerInlineQuery` - 响应内联查询
- 结果类型article, photo, gif, video, audio, voice, document, location, venue, contact, game, sticker
### 回调查询
- `answerCallbackQuery` - 响应按钮点击
- 可显示通知或警告
### 支付
- `sendInvoice` - 发送发票
- `answerPreCheckoutQuery` - 预结账
- `answerShippingQuery` - 配送查询
- 支持提供商Stripe, Yandex.Money, Telegram Stars
### 游戏
- `sendGame` - 发送游戏
- `setGameScore` - 设置分数
- `getGameHighScores` - 获取排行榜
### 群组管理
- `kickChatMember` / `unbanChatMember` - 封禁/解封
- `restrictChatMember` - 限制权限
- `promoteChatMember` - 提升管理员
- `setChatTitle` / `setChatDescription` - 设置信息
- `setChatPhoto` - 设置头像
- `pinChatMessage` / `unpinChatMessage` - 置顶消息
## Mini Apps API 详解
### 初始化
```javascript
const tg = window.Telegram.WebApp;
tg.ready();
tg.expand();
```
### 主要对象
- **WebApp** - 主接口
- **MainButton** - 主按钮
- **SecondaryButton** - 次要按钮
- **BackButton** - 返回按钮
- **SettingsButton** - 设置按钮
- **HapticFeedback** - 触觉反馈
- **CloudStorage** - 云存储
- **BiometricManager** - 生物识别
- **LocationManager** - 位置服务
- **Accelerometer** - 加速度计
- **Gyroscope** - 陀螺仪
- **DeviceOrientation** - 设备方向
### 事件系统
40+ 事件包括:
- `themeChanged` - 主题改变
- `viewportChanged` - 视口改变
- `mainButtonClicked` - 主按钮点击
- `backButtonClicked` - 返回按钮点击
- `settingsButtonClicked` - 设置按钮点击
- `invoiceClosed` - 支付完成
- `popupClosed` - 弹窗关闭
- `qrTextReceived` - 扫码结果
- `clipboardTextReceived` - 剪贴板文本
- `writeAccessRequested` - 写入权限请求
- `contactRequested` - 联系人请求
### 主题参数
```javascript
tg.themeParams = {
bg_color, // 背景色
text_color, // 文本色
hint_color, // 提示色
link_color, // 链接色
button_color, // 按钮色
button_text_color, // 按钮文本色
secondary_bg_color, // 次要背景色
header_bg_color, // 头部背景色
accent_text_color, // 强调文本色
section_bg_color, // 区块背景色
section_header_text_color, // 区块头文本色
subtitle_text_color, // 副标题色
destructive_text_color // 危险操作色
}
```
## 开发工具
### @BotFather 命令
创建和管理 Bot 的核心工具:
**Bot 管理:**
- `/newbot` - 创建新 Bot
- `/mybots` - 管理我的 Bots
- `/deletebot` - 删除 Bot
- `/token` - 重新生成 token
**设置命令:**
- `/setname` - 设置名称
- `/setdescription` - 设置描述
- `/setabouttext` - 设置关于文本
- `/setuserpic` - 设置头像
**功能配置:**
- `/setcommands` - 设置命令列表
- `/setinline` - 启用内联模式
- `/setinlinefeedback` - 内联反馈
- `/setjoingroups` - 允许加入群组
- `/setprivacy` - 隐私模式
**支付和游戏:**
- `/setgamescores` - 游戏分数
- `/setpayments` - 配置支付
**Mini Apps**
- `/newapp` - 创建 Mini App
- `/myapps` - 管理 Mini Apps
- `/setmenubutton` - 设置菜单按钮
### API ID 获取
访问 https://my.telegram.org
1. 登录账号
2. 进入 API development tools
3. 创建应用
4. 获取 API ID 和 API Hash
## 常用 Python 库
### python-telegram-bot
```bash
pip install python-telegram-bot
```
**特点:**
- 完整的 Bot API 包装
- 异步和同步支持
- 丰富的扩展
- 活跃维护
**基础示例:**
```python
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text('你好!')
app = Application.builder().token("TOKEN").build()
app.add_handler(CommandHandler("start", start))
app.run_polling()
```
### aiogram
```bash
pip install aiogram
```
**特点:**
- 纯异步
- 高性能
- FSM 状态机
- 中间件系统
### Telethon / Pyrogram
MTProto 客户端库:
```bash
pip install telethon
pip install pyrogram
```
**用途:**
- 自定义客户端
- 用户账号自动化
- 完整 Telegram 功能
## 常用 Node.js 库
### node-telegram-bot-api
```bash
npm install node-telegram-bot-api
```
### Telegraf
```bash
npm install telegraf
```
**特点:**
- 现代化
- 中间件架构
- TypeScript 支持
### grammY
```bash
npm install grammy
```
**特点:**
- 轻量级
- 类型安全
- 插件生态
## 部署选项
### Webhook 托管
**推荐平台:**
- Heroku
- AWS Lambda
- Google Cloud Functions
- Azure Functions
- Vercel
- Railway
- Render
**要求:**
- HTTPS 支持
- 公网可访问
- 支持的端口443, 80, 88, 8443
### 长轮询托管
**推荐平台:**
- VPS (Vultr, DigitalOcean, Linode)
- Raspberry Pi
- 本地服务器
**优点:**
- 无需 HTTPS
- 简单配置
- 适合开发测试
## 安全最佳实践
1. **Token 安全**
- 不要提交到 Git
- 使用环境变量
- 定期轮换
2. **数据验证**
- 验证 initData
- 服务器端验证
- 不信任客户端
3. **权限控制**
- 检查用户权限
- 管理员验证
- 群组权限
4. **速率限制**
- 实现请求限制
- 防止滥用
- 监控异常
## 调试技巧
### Bot 调试
```python
import logging
logging.basicConfig(level=logging.DEBUG)
```
### Mini App 调试
```javascript
// 开启调试模式
tg.showAlert(JSON.stringify(tg.initDataUnsafe, null, 2));
// 控制台日志
console.log('WebApp version:', tg.version);
console.log('Platform:', tg.platform);
console.log('Theme:', tg.colorScheme);
```
### Webhook 测试
使用 ngrok 本地测试:
```bash
ngrok http 5000
# 将生成的 https URL 设置为 webhook
```
## 社区资源
- **Telegram 开发者群组**: @BotDevelopers
- **Telegram API 讨论**: @TelegramBots
- **Mini Apps 讨论**: @WebAppChat
## 更新日志
**最新功能:**
- Paid Media (付费媒体)
- Checklist Tasks (检查列表任务)
- Gift Conversion (礼物转换)
- Business Features (商业功能)
- Poll 选项增加到 12 个
- Story 发布和编辑
---
## 完整实现模板 (新增)
### Telegram Bot 按钮和键盘实现指南
**文件:** `Telegram_Bot_按钮和键盘实现模板.md`
**行数:** 404 行
**大小:** 12 KB
**语言:** 中文
精简实用的 Telegram Bot 交互式功能实现指南:
**核心内容:**
- 三种按钮类型详解Inline/Reply/Command Menu
- python-telegram-bot 和 Telethon 双实现对比
- 完整的代码示例(即拿即用)
- 项目结构和模块化设计
- Handler 优先级和事件处理
- 生产环境部署方案
- 安全和错误处理最佳实践
**特色:**
- 核心代码精简,去除冗余示例
- 聚焦常用场景和实用技巧
- 完整的快速参考表
---
### 动态视图对齐 - 数据展示指南
**文件:** `动态视图对齐实现文档.md`
**行数:** 407 行
**大小:** 12 KB
**语言:** 中文
专业的等宽字体数据对齐和格式化方案:
**核心功能:**
- 智能动态视图对齐算法(三步法)
- 自动计算列宽,无需硬编码
- 智能对齐规则(文本左,数字右)
- 完整的格式化系统:
- 交易量智能缩写B/M/K
- 价格智能精度(自适应小数位)
- 涨跌幅格式化(+/- 符号)
- 资金流向智能显示
**应用场景:**
- 排行榜、数据表格、实时行情
- 任何需要专业数据展示的 Telegram Bot
**技术特点:**
- O(n×m) 线性复杂度,高效实用
- 1000 行数据处理仅需 5-10ms
- 支持中文字符宽度扩展
**视觉效果示例:**
```
1. BTC $1.23B $45,000 +5.23%
2. ETH $890.5M $2,500 +3.12%
3. SOL $567.8M $101 +8.45%
```
---
**这些模板提供了从基础到生产级别的完整 Telegram Bot 开发解决方案!**

View File

@ -0,0 +1,407 @@
# 📊 动态视图对齐 - Telegram 数据展示指南
> 专业的等宽字体数据对齐和格式化方案
---
## 📑 目录
- [核心原理](#核心原理)
- [实现代码](#实现代码)
- [格式化系统](#格式化系统)
- [应用示例](#应用示例)
- [最佳实践](#最佳实践)
---
## 核心原理
### 问题场景
在 Telegram Bot 中展示排行榜、数据表格时,需要在等宽字体环境(代码块)中实现完美对齐:
**❌ 未对齐:**
```
1. BTC $1.23B $45000 +5.23%
10. DOGE $123.4M $0.0789 -1.45%
```
**✅ 动态对齐:**
```
1. BTC $1.23B $45,000 +5.23%
10. DOGE $123.4M $0.0789 -1.45%
```
### 三步对齐算法
```
步骤 1: 扫描数据,计算每列最大宽度
步骤 2: 根据列类型应用对齐规则(文本左对齐,数字右对齐)
步骤 3: 拼接成最终文本
```
### 对齐规则
| 列索引 | 数据类型 | 对齐方式 | 示例 |
|--------|----------|----------|------|
| 列 0 | 序号 | 左对齐 | `1. `, `10. ` |
| 列 1 | 符号 | 左对齐 | `BTC `, `DOGE ` |
| 列 2+ | 数值 | 右对齐 | ` $1.23B`, `$123.4M` |
---
## 实现代码
### 核心函数
```python
def dynamic_align_format(data_rows):
"""
动态视图对齐格式化
参数:
data_rows: 二维列表 [["1.", "BTC", "$1.23B", ...], ...]
返回:
对齐后的文本字符串
"""
if not data_rows:
return "暂无数据"
# ========== 步骤 1: 计算每列最大宽度 ==========
max_widths = []
for row in data_rows:
for i, cell in enumerate(row):
# 动态扩展列表
if i >= len(max_widths):
max_widths.append(0)
# 更新最大宽度
max_widths[i] = max(max_widths[i], len(str(cell)))
# ========== 步骤 2: 格式化每一行 ==========
formatted_rows = []
for row in data_rows:
formatted_cells = []
for i, cell in enumerate(row):
cell_str = str(cell)
if i == 0 or i == 1:
# 序号列和符号列 - 左对齐
formatted_cells.append(cell_str.ljust(max_widths[i]))
else:
# 数值列 - 右对齐
formatted_cells.append(cell_str.rjust(max_widths[i]))
# 用空格连接所有单元格
formatted_line = ' '.join(formatted_cells)
formatted_rows.append(formatted_line)
# ========== 步骤 3: 拼接成最终文本 ==========
return '\n'.join(formatted_rows)
```
### 使用示例
```python
# 准备数据
data_rows = [
["1.", "BTC", "$1.23B", "$45,000", "+5.23%"],
["2.", "ETH", "$890.5M", "$2,500", "+3.12%"],
["10.", "DOGE", "$123.4M", "$0.0789", "-1.45%"]
]
# 调用对齐函数
aligned_text = dynamic_align_format(data_rows)
# 输出到 Telegram
text = f"""📊 排行榜
```
{aligned_text}
```
💡 说明文字"""
```
---
## 格式化系统
### 1. 交易量智能缩写
```python
def format_volume(volume: float) -> str:
"""智能格式化交易量"""
if volume >= 1e9:
return f"${volume/1e9:.2f}B" # 十亿 → $1.23B
elif volume >= 1e6:
return f"${volume/1e6:.2f}M" # 百万 → $890.5M
elif volume >= 1e3:
return f"${volume/1e3:.2f}K" # 千 → $123.4K
else:
return f"${volume:.2f}" # 小数 → $45.67
```
**示例:**
```python
format_volume(1234567890) # → "$1.23B"
format_volume(890500000) # → "$890.5M"
format_volume(123400) # → "$123.4K"
```
### 2. 价格智能精度
```python
def format_price(price: float) -> str:
"""智能格式化价格 - 根据大小自动调整小数位"""
if price >= 1000:
return f"${price:,.0f}" # 千元以上 → $45,000
elif price >= 1:
return f"${price:.3f}" # 1-1000 → $2.500
elif price >= 0.01:
return f"${price:.4f}" # 0.01-1 → $0.0789
else:
return f"${price:.6f}" # <0.01 $0.000123
```
### 3. 涨跌幅格式化
```python
def format_change(change_percent: float) -> str:
"""格式化涨跌幅 - 正数添加+号"""
if change_percent >= 0:
return f"+{change_percent:.2f}%"
else:
return f"{change_percent:.2f}%"
```
**示例:**
```python
format_change(5.234) # → "+5.23%"
format_change(-1.456) # → "-1.46%"
format_change(0) # → "+0.00%"
```
### 4. 资金流向智能显示
```python
def format_flow(net_flow: float) -> str:
"""格式化资金净流向"""
sign = "+" if net_flow >= 0 else ""
abs_flow = abs(net_flow)
if abs_flow >= 1e9:
return f"{sign}{net_flow/1e9:.2f}B"
elif abs_flow >= 1e6:
return f"{sign}{net_flow/1e6:.2f}M"
elif abs_flow >= 1e3:
return f"{sign}{net_flow/1e3:.2f}K"
else:
return f"{sign}{net_flow:.0f}"
```
---
## 应用示例
### 完整排行榜实现
```python
def get_volume_ranking(data, limit=10):
"""获取交易量排行榜"""
# 1. 数据处理和排序
sorted_data = sorted(data, key=lambda x: x['volume'], reverse=True)[:limit]
# 2. 准备数据行
data_rows = []
for i, item in enumerate(sorted_data, 1):
symbol = item['symbol']
volume = item['volume']
price = item['price']
change = item['change_percent']
# 格式化各列
volume_str = format_volume(volume)
price_str = format_price(price)
change_str = format_change(change)
# 添加到数据行
data_rows.append([
f"{i}.", # 序号
symbol, # 币种
volume_str, # 交易量
price_str, # 价格
change_str # 涨跌幅
])
# 3. 动态对齐格式化
aligned_data = dynamic_align_format(data_rows)
# 4. 构建最终消息
text = f"""🎪 热币排行 - 交易量榜 🎪
⏰ 更新 {datetime.now().strftime('%Y-%m-%d %H:%M')}
📊 排序 24小时交易量(USDT) / 降序
排名/币种/24h交易量/价格/24h涨跌
```
{aligned_data}
```
💡 交易量反映市场活跃度和流动性"""
return text
```
### 输出效果
```
🎪 热币排行 - 交易量榜 🎪
⏰ 更新 2025-10-29 14:30
📊 排序 24小时交易量(USDT) / 降序
排名/币种/24h交易量/价格/24h涨跌
1. BTC $1.23B $45,000 +5.23%
2. ETH $890.5M $2,500 +3.12%
3. SOL $567.8M $101 +8.45%
4. BNB $432.1M $315 +2.67%
5. XRP $345.6M $0.589 -1.23%
💡 交易量反映市场活跃度和流动性
```
---
## 最佳实践
### 1. 数据准备规范
```python
# ✅ 推荐:使用列表嵌套结构
data_rows = [
["1.", "BTC", "$1.23B", "$45,000", "+5.23%"],
["2.", "ETH", "$890.5M", "$2,500", "+3.12%"]
]
# ❌ 不推荐:使用字典(需要额外转换)
data_rows = [
{"rank": 1, "symbol": "BTC", ...},
]
```
### 2. 格式化顺序
```python
# ✅ 推荐:先格式化,再对齐
for i, item in enumerate(data, 1):
volume_str = format_volume(item['volume']) # 格式化
price_str = format_price(item['price']) # 格式化
change_str = format_change(item['change']) # 格式化
data_rows.append([f"{i}.", symbol, volume_str, price_str, change_str])
aligned_data = dynamic_align_format(data_rows) # 对齐
```
### 3. Telegram 消息嵌入
```python
# ✅ 推荐:使用代码块包裹对齐数据
text = f"""📊 排行榜标题
⏰ 更新时间 {time}
```
{aligned_data}
```
💡 说明文字"""
# ❌ 不推荐直接输出Telegram会自动换行破坏对齐
text = f"""📊 排行榜标题
{aligned_data}
💡 说明文字"""
```
### 4. 空数据处理
```python
# ✅ 推荐:在函数开头检查
def dynamic_align_format(data_rows):
if not data_rows:
return "暂无数据"
# ... 正常处理逻辑 ...
```
### 5. 性能优化
```python
# ✅ 推荐:限制数据量
sorted_data = sorted(data, key=lambda x: x['volume'], reverse=True)[:limit]
aligned_data = dynamic_align_format(data_rows)
# ❌ 不推荐:处理全量后截取(浪费资源)
aligned_data = dynamic_align_format(all_data_rows)
final_data = aligned_data.split('\n')[:limit]
```
### 6. 中文字符支持(可选)
```python
def get_display_width(text):
"""计算文本显示宽度(中文=2英文=1"""
width = 0
for char in text:
if ord(char) > 127: # 非ASCII字符
width += 2
else:
width += 1
return width
# 在 dynamic_align_format 中使用
max_widths[i] = max(max_widths[i], get_display_width(str(cell)))
```
---
## 设计优势
### 与硬编码方式对比
| 特性 | 传统硬编码 | 动态对齐 |
|------|-----------|---------|
| 列宽适配 | 手动指定 | 自动计算 |
| 维护成本 | 高(需多处修改) | 低(一次编写) |
| 对齐精度 | 易出偏差 | 字符级精确 |
| 扩展性 | 需重构 | 自动支持任意列 |
| 性能 | O(n) | O(n×m) |
### 技术亮点
- **自适应宽度**: 无论数据如何变化,始终完美对齐
- **智能对齐规则**: 符合人类阅读习惯(文本左,数字右)
- **等宽字体完美支持**: 空格填充确保对齐效果
- **高复用性**: 一个函数适用所有排行榜场景
---
## 快速参考
### 函数签名
```python
dynamic_align_format(data_rows: list[list]) -> str
format_volume(volume: float) -> str
format_price(price: float) -> str
format_change(change_percent: float) -> str
format_flow(net_flow: float) -> str
```
### 时间复杂度
- 宽度计算: O(n × m)
- 格式化输出: O(n × m)
- 总复杂度: O(n × m) - 线性时间,高效实用
### 性能基准
- 处理 100 行 × 5 列: ~1ms
- 处理 1000 行 × 5 列: ~5-10ms
- 内存占用: 最小
---
**这份指南提供了 Telegram Bot 专业数据展示的完整解决方案!**

108
skills/timescaledb/SKILL.md Normal file
View File

@ -0,0 +1,108 @@
---
name: timescaledb
description: TimescaleDB - PostgreSQL extension for high-performance time-series and event data analytics, hypertables, continuous aggregates, compression, and real-time analytics
---
# Timescaledb Skill
Comprehensive assistance with timescaledb development, generated from official documentation.
## When to Use This Skill
This skill should be triggered when:
- Working with timescaledb
- Asking about timescaledb features or APIs
- Implementing timescaledb solutions
- Debugging timescaledb code
- Learning timescaledb best practices
## Quick Reference
### Common Patterns
*Quick reference patterns will be added as you use the skill.*
### Example Code Patterns
**Example 1** (bash):
```bash
rails new my_app -d=postgresql
cd my_app
```
**Example 2** (ruby):
```ruby
gem 'timescaledb'
```
**Example 3** (shell):
```shell
kubectl create namespace timescale
```
**Example 4** (shell):
```shell
kubectl config set-context --current --namespace=timescale
```
**Example 5** (sql):
```sql
DROP EXTENSION timescaledb;
```
## Reference Files
This skill includes comprehensive documentation in `references/`:
- **api.md** - Api documentation
- **compression.md** - Compression documentation
- **continuous_aggregates.md** - Continuous Aggregates documentation
- **getting_started.md** - Getting Started documentation
- **hyperfunctions.md** - Hyperfunctions documentation
- **hypertables.md** - Hypertables documentation
- **installation.md** - Installation documentation
- **other.md** - Other documentation
- **performance.md** - Performance documentation
- **time_buckets.md** - Time Buckets documentation
- **tutorials.md** - Tutorials documentation
Use `view` to read specific reference files when detailed information is needed.
## Working with This Skill
### For Beginners
Start with the getting_started or tutorials reference files for foundational concepts.
### For Specific Features
Use the appropriate category reference file (api, guides, etc.) for detailed information.
### For Code Examples
The quick reference section above contains common patterns extracted from the official docs.
## Resources
### references/
Organized documentation extracted from official sources. These files contain:
- Detailed explanations
- Code examples with language annotations
- Links to original documentation
- Table of contents for quick navigation
### scripts/
Add helper scripts here for common automation tasks.
### assets/
Add templates, boilerplate, or example projects here.
## Notes
- This skill was automatically generated from official documentation
- Reference files preserve the structure and examples from source docs
- Code examples include language detection for better syntax highlighting
- Quick reference patterns are extracted from common usage examples in the docs
## Updating
To refresh this skill with updated documentation:
1. Re-run the scraper with the same configuration
2. The skill will be rebuilt with the latest information

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,47 @@
# Timescaledb Documentation Index
## Categories
### Api
**File:** `api.md`
**Pages:** 100
### Compression
**File:** `compression.md`
**Pages:** 19
### Continuous Aggregates
**File:** `continuous_aggregates.md`
**Pages:** 21
### Getting Started
**File:** `getting_started.md`
**Pages:** 3
### Hyperfunctions
**File:** `hyperfunctions.md`
**Pages:** 34
### Hypertables
**File:** `hypertables.md`
**Pages:** 103
### Installation
**File:** `installation.md`
**Pages:** 37
### Other
**File:** `other.md`
**Pages:** 248
### Performance
**File:** `performance.md`
**Pages:** 2
### Time Buckets
**File:** `time_buckets.md`
**Pages:** 16
### Tutorials
**File:** `tutorials.md`
**Pages:** 12

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,381 @@
# Tiger DataDocumentation
Over 3 million Tiger Datadatabases power customer-facing applications. Speed without sacrifice for real-time analytics, time series, and vector workloads. Creators of TimescaleDB.
Tiger Cloud is the modern Postgres data platform for all your applications. It enhances Postgres to handle time series, events, real-time analytics, and vector search—all in a single database alongside transactional workloads.
You get one system that handles live data ingestion, late and out-of-order updates, and low latency queries, with the performance, reliability, and scalability your app needs. Ideal for IoT, crypto, finance, SaaS, and a myriad other domains, Tiger Cloud allows you to build data-heavy, mission-critical apps while retaining the familiarity and reliability of PostgreSQL.
This repository contains the complete documentation for Tiger Dataproducts available at https://docs.tigerdata.com/.
## Getting Started
- [Get started overview](https://docs.tigerdata.com/getting-started/latest/): Introduction to Tiger Dataproducts and services
- [Create a Tiger Cloud service](https://docs.tigerdata.com/getting-started/latest/services/): Learn about Tiger Cloud capabilities and create your first service
- [Run queries from Tiger Cloud Console](https://docs.tigerdata.com/getting-started/latest/run-queries-from-console/): Use the SQL editor and SQL Assistant in Tiger Cloud
- [Try key Tiger Datafeatures](https://docs.tigerdata.com/getting-started/latest/try-key-features-timescale-products/): Explore hypertables, time buckets, compression, and continuous aggregates
- [Start coding with TigerData](https://docs.tigerdata.com/getting-started/latest/start-coding-with-timescale/): Connect and code with your preferred programming language
## Core Features and Functionality
### Hypertables
- [About hypertables](https://docs.tigerdata.com/use-timescale/latest/hypertables/about-hypertables/): Core concept for time-series optimization
- [Create and manage hypertables](https://docs.tigerdata.com/use-timescale/latest/hypertables/hypertable-crud/): CRUD operations on hypertables
- [Improve query performance](https://docs.tigerdata.com/use-timescale/latest/hypertables/improve-query-performance/): Performance optimization techniques
- [Unique indexes on hypertables](https://docs.tigerdata.com/use-timescale/latest/hypertables/hypertables-and-unique-indexes/): Handling unique constraints
### Hypercore (Columnar Storage)
- [Hypercore overview](https://docs.tigerdata.com/use-timescale/latest/hypercore/): Advanced columnar storage for real-time analytics
- [Real-time analytics in Hypercore](https://docs.tigerdata.com/use-timescale/latest/hypercore/real-time-analytics-in-hypercore/): High-performance analytics capabilities
- [Compression methods](https://docs.tigerdata.com/use-timescale/latest/hypercore/compression-methods/): Advanced compression techniques
- [Secondary indexes](https://docs.tigerdata.com/use-timescale/latest/hypercore/secondary-indexes/): Indexing strategies for columnar data
- [Modify data in Hypercore](https://docs.tigerdata.com/use-timescale/latest/hypercore/modify-data-in-hypercore/): Data modification operations
### Continuous Aggregates
- [About continuous aggregates](https://docs.tigerdata.com/use-timescale/latest/continuous-aggregates/about-continuous-aggregates/): Materialized views for time-series data
- [Create continuous aggregates](https://docs.tigerdata.com/use-timescale/latest/continuous-aggregates/create-a-continuous-aggregate/): Implementation guide
- [Real-time aggregates](https://docs.tigerdata.com/use-timescale/latest/continuous-aggregates/real-time-aggregates/): Real-time query capabilities
- [Hierarchical continuous aggregates](https://docs.tigerdata.com/use-timescale/latest/continuous-aggregates/hierarchical-continuous-aggregates/): Multi-level aggregation
- [Refresh policies](https://docs.tigerdata.com/use-timescale/latest/continuous-aggregates/refresh-policies/): Automated refresh management
- [Compression on continuous aggregates](https://docs.tigerdata.com/use-timescale/latest/continuous-aggregates/compression-on-continuous-aggregates/): Storage optimization
### Hyperfunctions
- [About hyperfunctions](https://docs.tigerdata.com/use-timescale/latest/hyperfunctions/about-hyperfunctions/): Advanced analytical functions
- [Function pipelines](https://docs.tigerdata.com/use-timescale/latest/hyperfunctions/function-pipelines/): Chaining analytical operations
- [Statistical aggregates](https://docs.tigerdata.com/use-timescale/latest/hyperfunctions/stats-aggs/): Statistical analysis functions
- [Time-weighted averages](https://docs.tigerdata.com/use-timescale/latest/hyperfunctions/time-weighted-averages/): Time-series averaging
- [Gapfilling and interpolation](https://docs.tigerdata.com/use-timescale/latest/hyperfunctions/gapfilling-interpolation/): Handle missing data
- [Counter aggregation](https://docs.tigerdata.com/use-timescale/latest/hyperfunctions/counter-aggregation/): Monitor counter metrics
- [Approximate count distincts](https://docs.tigerdata.com/use-timescale/latest/hyperfunctions/approx-count-distincts/): Efficient distinct counting
- [Percentile approximation](https://docs.tigerdata.com/use-timescale/latest/hyperfunctions/percentile-approx/): Statistical percentile calculations
## Data Operations
### Writing Data
- [About writing data](https://docs.tigerdata.com/use-timescale/latest/write-data/about-writing-data/): Overview of data ingestion
- [Insert data](https://docs.tigerdata.com/use-timescale/latest/write-data/insert/): Insert operations and best practices
- [Update data](https://docs.tigerdata.com/use-timescale/latest/write-data/update/): Update existing records
- [Upsert data](https://docs.tigerdata.com/use-timescale/latest/write-data/upsert/): Insert or update patterns
- [Delete data](https://docs.tigerdata.com/use-timescale/latest/write-data/delete/): Data deletion strategies
### Querying Data
- [About querying data](https://docs.tigerdata.com/use-timescale/latest/query-data/about-query-data/): Query fundamentals
- [SELECT queries](https://docs.tigerdata.com/use-timescale/latest/query-data/select/): Basic and advanced SELECT operations
- [Advanced analytic queries](https://docs.tigerdata.com/use-timescale/latest/query-data/advanced-analytic-queries/): Complex analytical queries
- [SkipScan for DISTINCT](https://docs.tigerdata.com/use-timescale/latest/query-data/skipscan/): Optimized DISTINCT operations
### Time Buckets
- [About time buckets](https://docs.tigerdata.com/use-timescale/latest/time-buckets/about-time-buckets/): Time-based data grouping
- [Use time buckets](https://docs.tigerdata.com/use-timescale/latest/time-buckets/use-time-buckets/): Implementation examples
### Data Ingestion
- [Import CSV data](https://docs.tigerdata.com/use-timescale/latest/ingest-data/import-csv/): CSV data import
- [Import from MySQL](https://docs.tigerdata.com/use-timescale/latest/ingest-data/import-mysql/): MySQL migration
- [Import Parquet files](https://docs.tigerdata.com/use-timescale/latest/ingest-data/import-parquet/): Parquet data ingestion
- [Ingest from Kafka](https://docs.tigerdata.com/use-timescale/latest/ingest-data/ingest-kafka/): Apache Kafka integration
- [Ingest with Telegraf](https://docs.tigerdata.com/use-timescale/latest/ingest-data/ingest-telegraf/): Telegraf data collection
## Data Management
### Compression
- [About compression](https://docs.tigerdata.com/use-timescale/latest/compression/about-compression/): Storage optimization overview
- [Compression design](https://docs.tigerdata.com/use-timescale/latest/compression/compression-design/): Design considerations
- [Manual compression](https://docs.tigerdata.com/use-timescale/latest/compression/manual-compression/): Manual compression operations
- [Compression policies](https://docs.tigerdata.com/use-timescale/latest/compression/compression-policy/): Automated compression
- [Modify compressed data](https://docs.tigerdata.com/use-timescale/latest/compression/modify-compressed-data/): Working with compressed data
- [Modify schemas](https://docs.tigerdata.com/use-timescale/latest/compression/modify-a-schema/): Schema changes on compressed tables
### Data Retention
- [About data retention](https://docs.tigerdata.com/use-timescale/latest/data-retention/about-data-retention/): Automated data lifecycle management
- [Create retention policies](https://docs.tigerdata.com/use-timescale/latest/data-retention/create-a-retention-policy/): Policy creation and management
- [Data retention with continuous aggregates](https://docs.tigerdata.com/use-timescale/latest/data-retention/data-retention-with-continuous-aggregates/): Retention for aggregated data
- [Manually drop chunks](https://docs.tigerdata.com/use-timescale/latest/data-retention/manually-drop-chunks/): Manual data removal
### Data Tiering
- [About data tiering](https://docs.tigerdata.com/use-timescale/latest/data-tiering/about-data-tiering/): Multi-tier storage strategy
- [Enable data tiering](https://docs.tigerdata.com/use-timescale/latest/data-tiering/enabling-data-tiering/): Setup and configuration
- [Query tiered data](https://docs.tigerdata.com/use-timescale/latest/data-tiering/querying-tiered-data/): Working with tiered storage
- [Tiered data with replicas and forks](https://docs.tigerdata.com/use-timescale/latest/data-tiering/tiered-data-replicas-forks/): Advanced tiering scenarios
### Jobs and Automation
- [Create and manage jobs](https://docs.tigerdata.com/use-timescale/latest/jobs/create-and-manage-jobs/): Background job management
- [Downsample and compress example](https://docs.tigerdata.com/use-timescale/latest/jobs/example-downsample-and-compress/): Automated data processing
- [Generic retention example](https://docs.tigerdata.com/use-timescale/latest/jobs/example-generic-retention/): Custom retention policies
- [Tiered storage example](https://docs.tigerdata.com/use-timescale/latest/jobs/example-tiered-storage/): Automated tiering
## Infrastructure and Operations
### Tiger Cloud Services
- [Service overview](https://docs.tigerdata.com/use-timescale/latest/services/service-overview/): Tiger Cloud service architecture
- [Service management](https://docs.tigerdata.com/use-timescale/latest/services/service-management/): Lifecycle management
- [Service explorer](https://docs.tigerdata.com/use-timescale/latest/services/service-explorer/): Service monitoring and insights
- [Change resources](https://docs.tigerdata.com/use-timescale/latest/services/change-resources/): Scale compute and storage
- [Connection pooling](https://docs.tigerdata.com/use-timescale/latest/services/connection-pooling/): Manage database connections
### Configuration
- [About configuration](https://docs.tigerdata.com/use-timescale/latest/configuration/about-configuration/): Configuration overview
- [Customize configuration](https://docs.tigerdata.com/use-timescale/latest/configuration/customize-configuration/): Custom settings
- [Advanced parameters](https://docs.tigerdata.com/use-timescale/latest/configuration/advanced-parameters/): Advanced tuning options
### High Availability
- [High availability overview](https://docs.tigerdata.com/use-timescale/latest/ha-replicas/high-availability/): HA architecture and setup
- [Read scaling](https://docs.tigerdata.com/use-timescale/latest/ha-replicas/read-scaling/): Read replica configuration
### Backup and Restore
- [Backup and restore overview](https://docs.tigerdata.com/use-timescale/latest/backup-restore/backup-restore-cloud/): Cloud backup strategies
- [Point-in-time recovery](https://docs.tigerdata.com/use-timescale/latest/backup-restore/point-in-time-recovery/): PITR capabilities
### Security
- [Security overview](https://docs.tigerdata.com/use-timescale/latest/security/overview/): Security architecture
- [Member management](https://docs.tigerdata.com/use-timescale/latest/security/members/): User and role management
- [Multi-factor authentication](https://docs.tigerdata.com/use-timescale/latest/security/multi-factor-authentication/): MFA setup
- [SAML authentication](https://docs.tigerdata.com/use-timescale/latest/security/saml/): SSO integration
- [Client credentials](https://docs.tigerdata.com/use-timescale/latest/security/client-credentials/): Application authentication
- [Read-only role](https://docs.tigerdata.com/use-timescale/latest/security/read-only-role/): Restricted access roles
- [Strict SSL](https://docs.tigerdata.com/use-timescale/latest/security/strict-ssl/): SSL configuration
- [VPC peering](https://docs.tigerdata.com/use-timescale/latest/security/vpc/): Private network connectivity
- [Transit Gateway](https://docs.tigerdata.com/use-timescale/latest/security/transit-gateway/): Multi-cloud connectivity
- [IP allow list](https://docs.tigerdata.com/use-timescale/latest/security/ip-allow-list/): Network access control
### Schema Management
- [About schemas](https://docs.tigerdata.com/use-timescale/latest/schema-management/about-schemas/): Schema design principles
- [About indexing](https://docs.tigerdata.com/use-timescale/latest/schema-management/about-indexing/): Index strategies
- [About constraints](https://docs.tigerdata.com/use-timescale/latest/schema-management/about-constraints/): Constraint management
- [About tablespaces](https://docs.tigerdata.com/use-timescale/latest/schema-management/about-tablespaces/): Storage management
- [Alter operations](https://docs.tigerdata.com/use-timescale/latest/schema-management/alter/): Schema modifications
- [Indexing](https://docs.tigerdata.com/use-timescale/latest/schema-management/indexing/): Index creation and management
- [JSON support](https://docs.tigerdata.com/use-timescale/latest/schema-management/json/): Working with JSON data
- [Triggers](https://docs.tigerdata.com/use-timescale/latest/schema-management/triggers/): Database triggers
- [Foreign data wrappers](https://docs.tigerdata.com/use-timescale/latest/schema-management/foreign-data-wrappers/): External data integration
### Extensions
- [pgvector](https://docs.tigerdata.com/use-timescale/latest/extensions/pgvector/): Vector similarity search
- [PostGIS](https://docs.tigerdata.com/use-timescale/latest/extensions/postgis/): Geospatial data support
- [pgcrypto](https://docs.tigerdata.com/use-timescale/latest/extensions/pgcrypto/): Cryptographic functions
### Monitoring and Metrics
- [Monitoring overview](https://docs.tigerdata.com/use-timescale/latest/metrics-logging/monitoring/): System monitoring
- [AWS CloudWatch](https://docs.tigerdata.com/use-timescale/latest/metrics-logging/aws-cloudwatch/): CloudWatch integration
- [Datadog](https://docs.tigerdata.com/use-timescale/latest/metrics-logging/datadog/): Datadog monitoring
- [Prometheus metrics](https://docs.tigerdata.com/use-timescale/latest/metrics-logging/metrics-to-prometheus/): Prometheus integration
## Integrate AI with Tiger Data
- [AI overview](https://docs.tigerdata.com/ai/latest/): Integrate AI with your Tiger Data products
- [Integrate Tiger Cloud with your AI Assistant](https://docs.tigerdata.com/ai/latest/mcp-server/): Manage your services and optimize your schema and queries with your AI Assistant
- [Aggregate organizational data with AI agents](https://docs.tigerdata.com/ai/latest/tiger-eon/): Unify company knowledge with slack-native AI agents
- [Integrate a slack-native AI agent](https://docs.tigerdata.com/ai/latest/tiger-agents-for-work/): Configure a Slack-native AI agent to do what you want
- [Key vector database concepts](https://docs.tigerdata.com/ai/latest/key-vector-database-concepts-for-understanding-pgvector/): Key concepts for working with pgvector data in Postgres
- [SQL interface for pgvector](https://docs.tigerdata.com/ai/latest/sql-interface-for-pgvector-and-timescale-vector/): SQL interface for pgai, pgvector and pgvectorscale in Postgres
## Tutorials and Examples
- [Tutorials overview](https://docs.tigerdata.com/tutorials/latest/): Hands-on tutorials and examples
- [Community cookbook](https://docs.tigerdata.com/tutorials/latest/cookbook/): Code examples and recipes
- [Real-time analytics for energy consumption](https://docs.tigerdata.com/tutorials/latest/real-time-analytics-energy-consumption/): Energy data analysis
- [Real-time analytics for transport](https://docs.tigerdata.com/tutorials/latest/real-time-analytics-transport/): Transportation data analysis
- [Simulate IoT sensor data](https://docs.tigerdata.com/tutorials/latest/simulate-iot-sensor-data/): IoT data simulation
- [Ingest real-time websocket data](https://docs.tigerdata.com/tutorials/latest/ingest-real-time-websocket-data/): WebSocket data streaming
### Dataset Tutorials
- [Bitcoin blockchain analysis](https://docs.tigerdata.com/tutorials/latest/blockchain-analyze/): Analyze blockchain transactions with Hypercore
- [Financial tick data analysis](https://docs.tigerdata.com/tutorials/latest/financial-tick-data/): High-frequency financial data
- [Financial real-time ingestion](https://docs.tigerdata.com/tutorials/latest/financial-ingest-real-time/): Real-time financial data streaming
- [NYC taxi data analysis](https://docs.tigerdata.com/tutorials/latest/nyc-taxi-cab/): Time-series analysis with NYC taxi data
- [NYC taxi geospatial analysis](https://docs.tigerdata.com/tutorials/latest/nyc-taxi-geospatial/): Geospatial data visualization
- [Energy consumption analysis](https://docs.tigerdata.com/tutorials/latest/energy-data/): Energy usage patterns and optimization
## Integrations
### Cloud Platforms
- [AWS integrations](https://docs.tigerdata.com/integrations/latest/aws/): Amazon Web Services integration
- [AWS Lambda](https://docs.tigerdata.com/integrations/latest/aws-lambda/): Serverless functions
- [Amazon SageMaker](https://docs.tigerdata.com/integrations/latest/amazon-sagemaker/): Machine learning platform
- [Google Cloud](https://docs.tigerdata.com/integrations/latest/google-cloud/): Google Cloud Platform integration
- [Microsoft Azure](https://docs.tigerdata.com/integrations/latest/microsoft-azure/): Microsoft Azure integration
### Data Integration
- [Apache Kafka](https://docs.tigerdata.com/integrations/latest/apache-kafka/): Kafka streaming integration
- [Apache Airflow](https://docs.tigerdata.com/integrations/latest/apache-airflow/): Workflow orchestration
- [Debezium](https://docs.tigerdata.com/integrations/latest/debezium/): Change data capture
- [Decodable](https://docs.tigerdata.com/integrations/latest/decodable/): Real-time stream processing
- [Fivetran](https://docs.tigerdata.com/integrations/latest/fivetran/): Data pipeline automation
- [PostgreSQL](https://docs.tigerdata.com/integrations/latest/postgresql/): PostgreSQL compatibility
### Visualization and Analytics
- [Grafana](https://docs.tigerdata.com/integrations/latest/grafana/): Monitoring and visualization
- [Tableau](https://docs.tigerdata.com/integrations/latest/tableau/): Business intelligence
- [Power BI](https://docs.tigerdata.com/integrations/latest/power-bi/): Microsoft business analytics
### Development Tools
- [psql](https://docs.tigerdata.com/integrations/latest/psql/): PostgreSQL command line
- [pgAdmin](https://docs.tigerdata.com/integrations/latest/pgadmin/): PostgreSQL administration
- [DBeaver](https://docs.tigerdata.com/integrations/latest/dbeaver/): Database management tool
- [Azure Data Studio](https://docs.tigerdata.com/integrations/latest/azure-data-studio/): Microsoft database tool
- [qStudio](https://docs.tigerdata.com/integrations/latest/qstudio/): SQL analytics platform
### Monitoring and Observability
- [Prometheus](https://docs.tigerdata.com/integrations/latest/prometheus/): Monitoring and alerting
- [Datadog](https://docs.tigerdata.com/integrations/latest/datadog/): Infrastructure monitoring
- [CloudWatch](https://docs.tigerdata.com/integrations/latest/cloudwatch/): AWS monitoring service
### Infrastructure
- [Kubernetes](https://docs.tigerdata.com/integrations/latest/kubernetes/): Container orchestration
- [Terraform](https://docs.tigerdata.com/integrations/latest/terraform/): Infrastructure as code
- [Supabase](https://docs.tigerdata.com/integrations/latest/supabase/): Backend-as-a-service
- [Corporate Data Center](https://docs.tigerdata.com/integrations/latest/corporate-data-center/): On-premises connectivity
### Connection Details
- [Find connection details](https://docs.tigerdata.com/integrations/latest/find-connection-details/): Service connection information
- [Troubleshooting](https://docs.tigerdata.com/integrations/latest/troubleshooting/): Integration troubleshooting guide
## Migration and Sync
- [Migration overview](https://docs.tigerdata.com/migrate/latest/): Migration strategies and tools
- [pg_dump and restore](https://docs.tigerdata.com/migrate/latest/pg-dump-and-restore/): Traditional PostgreSQL migration
- [Live migration](https://docs.tigerdata.com/migrate/latest/live-migration/): Low-downtime migration for large databases
- [Live sync for PostgreSQL](https://docs.tigerdata.com/migrate/latest/livesync-for-postgresql/): Real-time sync from PostgreSQL
- [Live sync for S3](https://docs.tigerdata.com/migrate/latest/livesync-for-s3/): Sync data from S3 storage
- [Dual-write and backfill](https://docs.tigerdata.com/migrate/latest/dual-write-and-backfill/): Migration with zero downtime
- [Migration troubleshooting](https://docs.tigerdata.com/migrate/latest/troubleshooting/): Common migration issues
## Self-hosted TimescaleDB
### Installation
- [Self-hosted overview](https://docs.tigerdata.com/self-hosted/latest/): Installation options
- [Docker installation](https://docs.tigerdata.com/self-hosted/latest/install/installation-docker/): Docker-based deployment
- [Kubernetes installation](https://docs.tigerdata.com/self-hosted/latest/install/installation-kubernetes/): Kubernetes deployment
- [Linux installation](https://docs.tigerdata.com/self-hosted/latest/install/installation-linux/): Linux package installation
- [macOS installation](https://docs.tigerdata.com/self-hosted/latest/install/installation-macos/): macOS Homebrew/MacPorts
- [Windows installation](https://docs.tigerdata.com/self-hosted/latest/install/installation-windows/): Windows installation
- [Source installation](https://docs.tigerdata.com/self-hosted/latest/install/installation-source/): Build from source
### Configuration and Management
- [Configuration overview](https://docs.tigerdata.com/self-hosted/latest/configuration/about-configuration/): Configuration fundamentals
- [TimescaleDB configuration](https://docs.tigerdata.com/self-hosted/latest/configuration/timescaledb-config/): TimescaleDB-specific settings
- [PostgreSQL configuration](https://docs.tigerdata.com/self-hosted/latest/configuration/postgres-config/): PostgreSQL tuning
- [Docker configuration](https://docs.tigerdata.com/self-hosted/latest/configuration/docker-config/): Docker-specific configuration
- [timescaledb-tune](https://docs.tigerdata.com/self-hosted/latest/configuration/timescaledb-tune/): Automated tuning tool
- [Telemetry](https://docs.tigerdata.com/self-hosted/latest/configuration/telemetry/): Usage telemetry configuration
### Backup and Restore
- [Backup overview](https://docs.tigerdata.com/self-hosted/latest/backup-and-restore/): Self-hosted backup strategies
- [Logical backups](https://docs.tigerdata.com/self-hosted/latest/backup-and-restore/logical-backup/): pg_dump/pg_restore
- [Physical backups](https://docs.tigerdata.com/self-hosted/latest/backup-and-restore/physical/): WAL-E and pgBackRest
- [Docker and WAL-E](https://docs.tigerdata.com/self-hosted/latest/backup-and-restore/docker-and-wale/): Container backup solutions
### High Availability and Replication
- [About high availability](https://docs.tigerdata.com/self-hosted/latest/replication-and-ha/about-ha/): HA architecture
- [Configure replication](https://docs.tigerdata.com/self-hosted/latest/replication-and-ha/configure-replication/): Replication setup
### Migration
- [Entire database migration](https://docs.tigerdata.com/self-hosted/latest/migration/entire-database/): Full database migration
- [Schema then data migration](https://docs.tigerdata.com/self-hosted/latest/migration/schema-then-data/): Phased migration approach
- [Same database migration](https://docs.tigerdata.com/self-hosted/latest/migration/same-db/): In-place migration
- [Migrate from InfluxDB](https://docs.tigerdata.com/self-hosted/latest/migration/migrate-influxdb/): InfluxDB migration
### Upgrades and Maintenance
- [About upgrades](https://docs.tigerdata.com/self-hosted/latest/upgrades/about-upgrades/): Upgrade strategies
- [Major upgrades](https://docs.tigerdata.com/self-hosted/latest/upgrades/major-upgrade/): Major version upgrades
- [Minor upgrades](https://docs.tigerdata.com/self-hosted/latest/upgrades/minor-upgrade/): Minor version upgrades
- [Docker upgrades](https://docs.tigerdata.com/self-hosted/latest/upgrades/upgrade-docker/): Container upgrades
- [PostgreSQL upgrades](https://docs.tigerdata.com/self-hosted/latest/upgrades/upgrade-pg/): PostgreSQL version upgrades
- [Downgrade](https://docs.tigerdata.com/self-hosted/latest/upgrades/downgrade/): Version rollback
### Tooling
- [About timescaledb-tune](https://docs.tigerdata.com/self-hosted/latest/tooling/about-timescaledb-tune/): Performance tuning tool
- [Install toolkit](https://docs.tigerdata.com/self-hosted/latest/tooling/install-toolkit/): TimescaleDB toolkit installation
### Storage Management
- [Manage storage](https://docs.tigerdata.com/self-hosted/latest/manage-storage/): Storage and tablespace management
### Uninstallation
- [Uninstall TimescaleDB](https://docs.tigerdata.com/self-hosted/latest/uninstall/uninstall-timescaledb/): Clean removal
## Managed Service for TimescaleDB (MST)
### Getting Started
- [About MST](https://docs.tigerdata.com/mst/latest/about-mst/): Managed service overview
- [Install MST](https://docs.tigerdata.com/mst/latest/installation-mst/): Service setup and configuration
- [User management](https://docs.tigerdata.com/mst/latest/user-management/): User roles and permissions
- [Billing](https://docs.tigerdata.com/mst/latest/billing/): Pricing and billing information
### Data Operations
- [Ingest data](https://docs.tigerdata.com/mst/latest/ingest-data/): Data ingestion patterns
- [Migrate to MST](https://docs.tigerdata.com/mst/latest/migrate-to-mst/): Migration to managed service
### Infrastructure and Networking
- [Connection pools](https://docs.tigerdata.com/mst/latest/connection-pools/): Connection management
- [PostgreSQL read replicas](https://docs.tigerdata.com/mst/latest/postgresql-read-replica/): Read scaling
- [VPC peering overview](https://docs.tigerdata.com/mst/latest/vpc-peering/): Private network connectivity
- [AWS VPC peering](https://docs.tigerdata.com/mst/latest/vpc-peering/vpc-peering-aws/): Amazon VPC integration
- [AWS Transit Gateway](https://docs.tigerdata.com/mst/latest/vpc-peering/vpc-peering-aws-transit/): Multi-VPC connectivity
- [Azure VPC peering](https://docs.tigerdata.com/mst/latest/vpc-peering/vpc-peering-azure/): Microsoft Azure networking
- [GCP VPC peering](https://docs.tigerdata.com/mst/latest/vpc-peering/vpc-peering-gcp/): Google Cloud networking
### Operations and Monitoring
- [Extensions](https://docs.tigerdata.com/mst/latest/extensions/): Available PostgreSQL extensions
- [Security](https://docs.tigerdata.com/mst/latest/security/): Security configuration
- [Maintenance](https://docs.tigerdata.com/mst/latest/maintenance/): Maintenance windows and updates
- [Failover](https://docs.tigerdata.com/mst/latest/failover/): High availability failover
- [Manage backups](https://docs.tigerdata.com/mst/latest/manage-backups/): Backup management
- [View service logs](https://docs.tigerdata.com/mst/latest/viewing-service-logs/): Log access and analysis
### Tools and APIs
- [Aiven Client](https://docs.tigerdata.com/mst/latest/aiven-client/): Command-line management tool
- [REST API](https://docs.tigerdata.com/mst/latest/restapi/): Programmatic service management
- [Identify index issues](https://docs.tigerdata.com/mst/latest/identify-index-issues/): Performance optimization
### Integrations
- [MST integrations overview](https://docs.tigerdata.com/mst/latest/integrations/): Integration options
- [Grafana integration](https://docs.tigerdata.com/mst/latest/integrations/grafana-mst/): Visualization
- [Prometheus integration](https://docs.tigerdata.com/mst/latest/integrations/prometheus-mst/): Monitoring
- [Datadog metrics](https://docs.tigerdata.com/mst/latest/integrations/metrics-datadog/): Infrastructure monitoring
- [Logging integration](https://docs.tigerdata.com/mst/latest/integrations/logging/): Log management
## API Reference
### Core APIs
- [API overview](https://docs.tigerdata.com/api/latest/): Complete API reference
- [Hypertable management](https://docs.tigerdata.com/api/latest/hypertable/): Hypertable creation and management
- [Hypercore APIs](https://docs.tigerdata.com/api/latest/hypercore/): Columnar storage operations
- [Continuous aggregates](https://docs.tigerdata.com/api/latest/continuous-aggregates/): Materialized view management
- [Compression APIs](https://docs.tigerdata.com/api/latest/compression/): Data compression functions
- [Data retention](https://docs.tigerdata.com/api/latest/data-retention/): Retention policy management
- [Jobs and automation](https://docs.tigerdata.com/api/latest/jobs-automation/): Background job management
### Hyperfunctions
- [Hyperfunctions overview](https://docs.tigerdata.com/api/latest/hyperfunctions/): Advanced analytical functions
- [Statistical aggregates](https://docs.tigerdata.com/api/latest/stats-aggregates/): Statistical analysis
- [Frequency analysis](https://docs.tigerdata.com/api/latest/frequency-analysis/): Frequency and histogram functions
- [Time-weighted averages](https://docs.tigerdata.com/api/latest/time-weighted-averages/): Time-series averaging
- [Gapfilling and interpolation](https://docs.tigerdata.com/api/latest/gapfilling-interpolation/): Missing data handling
- [Counter aggregates](https://docs.tigerdata.com/api/latest/counter-aggregates/): Counter metrics
- [Gauge aggregates](https://docs.tigerdata.com/api/latest/gauge-aggregates/): Gauge metrics
- [State aggregates](https://docs.tigerdata.com/api/latest/state-aggregates/): State tracking
### Configuration and Administration
- [Configuration APIs](https://docs.tigerdata.com/api/latest/configuration/): Database configuration
- [Administration functions](https://docs.tigerdata.com/api/latest/administration/): Administrative operations
- [Informational views](https://docs.tigerdata.com/api/latest/informational-views/): System information views
## About TigerData
- [About overview](https://docs.tigerdata.com/about/latest/): Company and product information
- [Pricing and account management](https://docs.tigerdata.com/about/latest/pricing-and-account-management/): Pricing plans and billing
- [TimescaleDB editions](https://docs.tigerdata.com/about/latest/timescaledb-editions/): Product tiers and features
- [Changelog](https://docs.tigerdata.com/about/latest/changelog/): Latest product updates
- [Release notes](https://docs.tigerdata.com/about/latest/release-notes/): Version release information
- [Whitepaper](https://docs.tigerdata.com/about/latest/whitepaper/): Technical architecture paper
- [Contribute to TigerData](https://docs.tigerdata.com/about/latest/contribute-to-timescale/): Community contribution guide
## Contributing
To contribute to this documentation:
1. Fork or clone the repository
2. Create a branch from `latest`
3. Make your changes following the style guide in CONTRIBUTING.md
4. Submit a pull request back to `latest`
5. Sign the Contributor License Agreement (CLA) if this is your first contribution
The documentation is built using Gatsby and automatically generates preview links for pull requests.

Some files were not shown because too many files have changed in this diff Show More