Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
refactor: remove trading server and related configurations
nirholas2bea9438ece9
diff --git a/package.json b/package.jsonindex a435f64ee..53da74cf5 100644--- a/package.json+++ b/package.json@@ -121,6 +121,7 @@"changelog:gaps": "node scripts/changelog-gaps.mjs","changelog:push": "node scripts/changelog-telegram.mjs","changelog:push:x": "node scripts/changelog-x.mjs",+ "tweet": "node scripts/post-tweet.mjs","audit:deploy": "node scripts/audit-deploy-artifacts.mjs","guard:esbuild": "node scripts/guard-esbuild-bundles.mjs","guard:esbuild:all": "node scripts/guard-esbuild-bundles.mjs --all",diff --git a/pages/reasoning-ledger.html b/pages/reasoning-ledger.htmlindex 4be02b58f..c5fda2b43 100644--- a/pages/reasoning-ledger.html+++ b/pages/reasoning-ledger.html@@ -17,7 +17,7 @@property="og:description"content="An auditable, on-chain-anchored record of an agent's decisions, predictions, and real outcomes. Being wrong is visible — honesty is the trust signal."data-i18n-attr="content:reasoning_ledger.meta_og_description"/>- <meta property="og:image" content="https://three.ws/og-image.png" />+ <meta property="og:image" content="https://three.ws/api/page-og?s=agent-tools&t=Reasoning+Ledger&d=An+agent%27s+every+consequential+decision+%28what+it+decided%2C+why%2C+what+it+predicted%2C+and+what+actually+happened%29+in+a+tamper-evident%2C+on-chain-anchored%2C+independen&p=%2Fledger" /><meta property="og:image:width" content="1200" /><meta property="og:image:height" content="630" /><meta name="twitter:card" content="summary_large_image" />@@ -35,7 +35,13 @@<link rel="stylesheet" href="/footer.css" /><meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" /><link rel="canonical" href="https://three.ws/ledger" />- </head>++ <meta property="og:locale" content="en_US">+ <meta property="og:image:alt" content="Reasoning Ledger — three.ws">+ <meta name="twitter:description" content="An agent's every consequential decision (what it decided, why, what it predicted, and what actually happened) in a tamper-evident, on-chain-anchored, independently verifiable ledger. Open any agent's at /ledger/<agentId>. Being wrong is visible; honesty is the trust signal.">+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=agent-tools&t=Reasoning+Ledger&d=An+agent%27s+every+consequential+decision+%28what+it+decided%2C+why%2C+what+it+predicted%2C+and+what+actually+happened%29+in+a+tamper-evident%2C+on-chain-anchored%2C+independen&p=%2Fledger">+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Reasoning Ledger","description":"An agent's every consequential decision (what it decided, why, what it predicted, and what actually happened) in a tamper-evident, on-chain-anchored, independently verifiable ledger. Open any agent's at /ledger/\u003cagentId>. Being wrong is visible; honesty is the trust signal.","url":"https://three.ws/ledger","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=agent-tools&t=Reasoning+Ledger&d=An+agent%27s+every+consequential+decision+%28what+it+decided%2C+why%2C+what+it+predicted%2C+and+what+actually+happened%29+in+a+tamper-evident%2C+on-chain-anchored%2C+independen&p=%2Fledger"}]}</script>+</head><body><header><div id="nav-container"></div></header><script src="/nav.js"></script>diff --git a/public/legal/index.html b/public/legal/index.htmlindex f128979bb..cafee9ad4 100644--- a/public/legal/index.html+++ b/public/legal/index.html@@ -73,13 +73,13 @@<meta property="og:title" content="Legal · three.ws" data-i18n-attr="content:legal_index.meta_og_title"><meta property="og:description" content="Every three.ws policy in one place, plus where to report copyright, abuse, or privacy issues." data-i18n-attr="content:legal_index.meta_og_description"><meta property="og:url" content="https://three.ws/legal">- <meta property="og:image" content="https://three.ws/api/page-og?s=legal&t=Legal&d=Every+three.ws+policy+in+one+place.&p=%2Flegal">+ <meta property="og:image" content="https://three.ws/api/page-og?s=legal&t=Legal&d=Every+three.ws+policy+in+one+place%2C+plus+which+address+to+use+to+report+copyright%2C+abuse%2C+or+privacy+issues.&p=%2Flegal"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630"><meta name="twitter:card" content="summary_large_image"><meta name="twitter:title" content="Legal · three.ws" data-i18n-attr="content:legal_index.meta_twitter_title"><meta name="twitter:description" content="Every three.ws policy in one place, plus where to report copyright, abuse, or privacy issues." data-i18n-attr="content:legal_index.meta_twitter_description">- <meta name="twitter:image" content="https://three.ws/api/page-og?s=legal&t=Legal&d=Every+three.ws+policy+in+one+place.&p=%2Flegal">+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=legal&t=Legal&d=Every+three.ws+policy+in+one+place%2C+plus+which+address+to+use+to+report+copyright%2C+abuse%2C+or+privacy+issues.&p=%2Flegal"><script type="application/ld+json">{"@context":"https://schema.org","@type":"CollectionPage","name":"Legal","description":"Every three.ws policy in one place.","url":"https://three.ws/legal","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script><meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex b3f3a7841..821e1f6ef 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -52,6 +52,25 @@.sm-badge-auth { background: rgba(255, 200, 80, .15); color: #ffcf66; }.sm-badge-internal { background: rgba(120,200,255,.12); color: #9ad4ff; }</style>++ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">+ <meta property="og:type" content="website">+ <meta property="og:site_name" content="three.ws">+ <meta property="og:locale" content="en_US">+ <meta property="og:title" content="Sitemap · three.ws">+ <meta property="og:description" content="Human-readable index of every page on three.ws.">+ <meta property="og:url" content="https://three.ws/sitemap">+ <meta property="og:image" content="https://three.ws/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap">+ <meta property="og:image:width" content="1200">+ <meta property="og:image:height" content="630">+ <meta property="og:image:type" content="image/png">+ <meta property="og:image:alt" content="Sitemap — three.ws">+ <meta name="twitter:card" content="summary_large_image">+ <meta name="twitter:site" content="@trythreews">+ <meta name="twitter:title" content="Sitemap · three.ws">+ <meta name="twitter:description" content="Human-readable index of every page on three.ws.">+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap">+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Sitemap","description":"Human-readable index of every page on three.ws.","url":"https://three.ws/sitemap","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap"}]}</script></head><body><header><div id="nav-container"></div></header>diff --git a/robinhood/robinhood-crypto-mcp/.gitignore b/robinhood/robinhood-crypto-mcp/.gitignoredeleted file mode 100644index 9014a85ae..000000000--- a/robinhood/robinhood-crypto-mcp/.gitignore+++ /dev/null@@ -1,5 +0,0 @@-node_modules/-dist/-*.log-.env-.env.localdiff --git a/robinhood/robinhood-crypto-mcp/LICENSE b/robinhood/robinhood-crypto-mcp/LICENSEdeleted file mode 100644index dff21b7f4..000000000--- a/robinhood/robinhood-crypto-mcp/LICENSE+++ /dev/null@@ -1,20 +0,0 @@-Copyright 2026 nirholas--All rights reserved.--This software is proprietary and may not be used, copied, modified, distributed,-translated, or made available to any third party without the express written-permission of the copyright owner.--No rights are granted by implication, estoppel, or otherwise. Use of this-software is subject to the terms of a separate license agreement with the-copyright owner.--THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,-FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT.--IN NO EVENT SHALL THE COPYRIGHT OWNER BE LIABLE FOR ANY CLAIM, DAMAGES, OR-OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE,-ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER-DEALINGS IN THE SOFTWARE.diff --git a/robinhood/robinhood-crypto-mcp/docs/openapi-extracted.json b/robinhood/robinhood-crypto-mcp/docs/openapi-extracted.jsondeleted file mode 100644index 0350e7df3..000000000--- a/robinhood/robinhood-crypto-mcp/docs/openapi-extracted.json+++ /dev/null@@ -1,2902 +0,0 @@-{- "openapi": "3.0.1",- "info": {- "title": "Robinhood Crypto Trading API",- "version": "",- "x-logo": {- "url": "https://cdn.robinhood.com/app_assets/crypto/logos/inherited-dimensions_RH_logo.png",- "altText": "Robinhood Logo"- },- "description": "# Introduction\n\n\nWelcome to Robinhood Crypto Trading API documentation for traders and developers! The API lets you view crypto market data, access your account information, and place crypto orders programmatically.\n\nTo get started, head to your [crypto account settings](https://robinhood.com/account/crypto) on web classic to create credentials. There are two versions of the Crypto Trading API, giving you the option to place crypto orders with fee tiers (v2) or without fee tiers (v1). All read-only API actions are available on both versions. For more information about API version differences, fee tiers, and answers to common questions, visit our [Help Center](https://robinhood.com/us/en/support/articles/crypto-api). You can also view the [Fee Schedule](https://cdn.robinhood.com/assets/robinhood/legal/rhc-fee-schedule.pdf) for the latest rates.\n\nThe Robinhood Crypto Trading API is available to customers in the United States only. Use of the Robinhood Crypto Trading API is subject to the [Robinhood Crypto Customer Agreement](https://cdn.robinhood.com/assets/robinhood/legal/Robinhood%20Crypto%20Customer%20Agreement.pdf) as well as all other terms and disclosures made available on [Robinhood Crypto's about page](https://robinhood.com/us/en/about/crypto).\n\n\n# Authentication\n\nTo get started with the Robinhood Crypto Trading API, you need to create a key, signature, and headers. Authenticated requests must include all three `x-api-key`, `x-signature`, and `x-timestamp` HTTP headers.\n\n\n## Creating an API key\n\nHead to your [crypto account settings](https://robinhood.com/account/crypto) on web classic to create credentials. After creating credentials, you will receive the API key associated with the credential. You can modify, disable, and delete credentials you created at any time.\n\nYour API key will be used as the `x-api-key` header you will need to pass during authentication when calling our API endpoints. Additionally, you will need the public key generated in the [Creating a key pair](#section/Authentication/Creating-a-key-pair) section to create your API credentials.\n\n\n## Creating a key pair\n\n\n#### Below are example scripts on how to generate the public and private key pair. You'll need the public key for creating an API credential and the private key for authenticating requests. Remember to never share your private key with anyone. Robinhood will never ask you to share it with us.\n\nWe highly recommend saving your private and public keys in an encrypted format to ensure the highest level of security. Encrypting your keys will protect them from unauthorized access or theft. Avoid saving them in plain text or any easily accessible location. Instead, consider using strong encryption algorithms or tools specifically designed for key storage. Remember to choose a strong passphrase for encryption and store it separately from your keys. By taking these precautions, you can significantly reduce the risk of compromising your keys and safeguard your sensitive information.\n\n ### Python\n\nNote that you'll need to have `pynacl` installed to run the Python script. You can install them with the following pip command in your terminal.\n```console\npip install pynacl\n```\n\n```python\nimport nacl.signing\nimport base64\n\n# Generate an Ed25519 keypair\nprivate_key = nacl.signing.SigningKey.generate()\npublic_key = private_key.verify_key\n\n# Convert keys to base64 strings\nprivate_key_base64 = base64.b64encode(private_key.encode()).decode()\npublic_key_base64 = base64.b64encode(public_key.encode()).decode()\n\n# Print the keys in base64 format\nprint(\"Private Key (Base64):\")\nprint(private_key_base64)\n\nprint(\"Public Key (Base64):\")\nprint(public_key_base64)\n```\n\n\n## Headers and Signature\n\n<SecurityDefinitions />\n\n\n# Making your first API call\n\nDeveloping your own application to place trades with your Robinhood account is quick and simple. Once you've finished [authentication](https://docs.robinhood.com/crypto/trading/#section/Authentication), start here with the code you'll need to access the API and make supported API calls. These are essentially the building blocks of code for each API call, which you can easily build on based on your preferred strategies.\n\n1. Create a script file\n\n```console\nmkdir robinhood-api-trading && cd robinhood-api-trading\ntouch robinhood_api_trading.py\ntouch robinhood_api_trading_v2.py\n```\n\n2. Install PyNaCl library\n\n```console\npip install pynacl\n```\n\n3. To use v1 endpoints, copy the script below into the newly created `robinhood_api_trading.py` file. Make sure to add your API key and secret key into the `API_KEY` and `BASE64_PRIVATE_KEY` variables.\n\n```python\nimport base64\nimport datetime\nimport json\nfrom typing import Any, Dict, Optional\nimport uuid\nimport requests\nfrom nacl.signing import SigningKey\n\nAPI_KEY = \"ADD YOUR API KEY HERE\"\nBASE64_PRIVATE_KEY = \"ADD YOUR PRIVATE KEY HERE\"\n\nclass CryptoAPITrading:\n def __init__(self):\n self.api_key = API_KEY\n private_key_seed = base64.b64decode(BASE64_PRIVATE_KEY)\n self.private_key = SigningKey(private_key_seed)\n self.base_url = \"https://trading.robinhood.com\"\n\n @staticmethod\n def _get_current_timestamp() -> int:\n return int(datetime.datetime.now(tz=datetime.timezone.utc).timestamp())\n\n @staticmethod\n def get_query_params(key: str, *args: Optional[str]) -> str:\n if not args:\n return \"\"\n\n params = []\n for arg in args:\n params.append(f\"{key}={arg}\")\n\n return \"?\" + \"&\".join(params)\n\n def make_api_request(self, method: str, path: str, body: str = \"\") -> Any:\n timestamp = self._get_current_timestamp()\n headers = self.get_authorization_header(method, path, body, timestamp)\n url = self.base_url + path\n\n try:\n response = {}\n if method == \"GET\":\n response = requests.get(url, headers=headers, timeout=10)\n elif method == \"POST\":\n response = requests.post(url, headers=headers, json=json.loads(body), timeout=10)\n return response.json()\n except requests.RequestException as e:\n print(f\"Error making API request: {e}\")\n return None\n\n def get_authorization_header(\n self, method: str, path: str, body: str, timestamp: int\n ) -> Dict[str, str]:\n message_to_sign = f\"{self.api_key}{timestamp}{path}{method}{body}\"\n signed = self.private_key.sign(message_to_sign.encode(\"utf-8\"))\n\n return {\n \"x-api-key\": self.api_key,\n \"x-signature\": base64.b64encode(signed.signature).decode(\"utf-8\"),\n \"x-timestamp\": str(timestamp),\n }\n\n def get_account(self) -> Any:\n path = \"/api/v1/crypto/trading/accounts/\"\n return self.make_api_request(\"GET\", path)\n\n # The symbols argument must be formatted in trading pairs, e.g \"BTC-USD\", \"ETH-USD\". If no symbols are provided,\n # all supported symbols will be returned\n def get_trading_pairs(self, *symbols: Optional[str]) -> Any:\n query_params = self.get_query_params(\"symbol\", *symbols)\n path = f\"/api/v1/crypto/trading/trading_pairs/{query_params}\"\n return self.make_api_request(\"GET\", path)\n\n # The asset_codes argument must be formatted as the short form name for a crypto, e.g \"BTC\", \"ETH\". If no asset\n # codes are provided, all crypto holdings will be returned\n def get_holdings(self, *asset_codes: Optional[str]) -> Any:\n query_params = self.get_query_params(\"asset_code\", *asset_codes)\n path = f\"/api/v1/crypto/trading/holdings/{query_params}\"\n return self.make_api_request(\"GET\", path)\n\n # The symbols argument must be formatted in trading pairs, e.g \"BTC-USD\", \"ETH-USD\". If no symbols are provided,\n # the best bid and ask for all supported symbols will be returned\n def get_best_bid_ask(self, *symbols: Optional[str]) -> Any:\n query_params = self.get_query_params(\"symbol\", *symbols)\n path = f\"/api/v1/crypto/marketdata/best_bid_ask/{query_params}\"\n return self.make_api_request(\"GET\", path)\n\n # The symbol argument must be formatted in a trading pair, e.g \"BTC-USD\", \"ETH-USD\"\n # The side argument must be \"bid\", \"ask\", or \"both\".\n # Multiple quantities can be specified in the quantity argument, e.g. \"0.1,1,1.999\".\n def get_estimated_price(self, symbol: str, side: str, quantity: str) -> Any:\n path = f\"/api/v1/crypto/marketdata/estimated_price/?symbol={symbol}&side={side}&quantity={quantity}\"\n return self.make_api_request(\"GET\", path)\n\n def place_order(\n self,\n client_order_id: str,\n side: str,\n order_type: str,\n symbol: str,\n order_config: Dict[str, str],\n ) -> Any:\n body = {\n \"client_order_id\": client_order_id,\n \"side\": side,\n \"type\": order_type,\n \"symbol\": symbol,\n f\"{order_type}_order_config\": order_config,\n }\n path = \"/api/v1/crypto/trading/orders/\"\n return self.make_api_request(\"POST\", path, json.dumps(body))\n\n def cancel_order(self, order_id: str) -> Any:\n path = f\"/api/v1/crypto/trading/orders/{order_id}/cancel/\"\n return self.make_api_request(\"POST\", path)\n\n def get_order(self, order_id: str) -> Any:\n path = f\"/api/v1/crypto/trading/orders/{order_id}/\"\n return self.make_api_request(\"GET\", path)\n\n def get_orders(self) -> Any:\n path = \"/api/v1/crypto/trading/orders/\"\n return self.make_api_request(\"GET\", path)\n\n\ndef main():\n api_trading_client = CryptoAPITrading()\n print(api_trading_client.get_account())\n\n \"\"\"\n BUILD YOUR TRADING STRATEGY HERE\n\n order = api_trading_client.place_order(\n str(uuid.uuid4()),\n \"buy\",\n \"market\",\n \"BTC-USD\",\n {\"asset_quantity\": \"0.0001\"}\n )\n \"\"\"\n\n\nif __name__ == \"__main__\":\n main()\n```\n\n4. To use v2 endpoints, copy the script below into the newly created `robinhood_api_trading_v2.py` file. Make sure to add your API key and secret key into the `API_KEY` and `BASE64_PRIVATE_KEY` variables.\n\n```python\nimport base64\nimport datetime\nimport json\nfrom typing import Any, Dict, Optional\nimport uuid\nimport requests\nfrom nacl.signing import SigningKey\n\nAPI_KEY = \"ADD YOUR API KEY HERE\"\nBASE64_PRIVATE_KEY = \"ADD YOUR PRIVATE KEY HERE\"\n\n\nclass CryptoAPITradingV2:\n def __init__(self):\n self.api_key = API_KEY\n private_key_seed = base64.b64decode(BASE64_PRIVATE_KEY)\n self.private_key = SigningKey(private_key_seed)\n self.base_url = \"https://trading.robinhood.com\"\n\n @staticmethod\n def _get_current_timestamp() -> int:\n return int(datetime.datetime.now(tz=datetime.timezone.utc).timestamp())\n\n @staticmethod\n def get_query_params(params_dict: Dict[str, Any]) -> str:\n \"\"\"\n Build query parameter string from a dictionary.\n - Single values: {\"key1\": \"value1\", \"key2\": \"value2\"}\n - Multiple values for same key: {\"symbol\": [\"BTC-USD\", \"ETH-USD\"]}\n \"\"\"\n if not params_dict:\n return \"\"\n \n params = []\n for key, value in params_dict.items():\n if value is None:\n continue\n if isinstance(value, list):\n # Handle multiple values for the same key\n for v in value:\n params.append(f\"{key}={v}\")\n else:\n params.append(f\"{key}={value}\")\n \n return \"?\" + \"&\".join(params) if params else \"\"\n\n def make_api_request(self, method: str, path: str, body: str = \"\") -> Any:\n timestamp = self._get_current_timestamp()\n headers = self.get_authorization_header(method, path, body, timestamp)\n url = self.base_url + path\n\n try:\n response = {}\n if method == \"GET\":\n response = requests.get(url, headers=headers, timeout=10)\n elif method == \"POST\":\n response = requests.post(url, headers=headers, json=json.loads(body) if body else None, timeout=10)\n\n # Check for non-success status codes\n if response.status_code >= 400:\n print(f\"HTTP Error {response.status_code}: {response.reason}\")\n try:\n return response.json()\n except json.JSONDecodeError:\n return {\"error\": response.text or response.reason, \"status_code\": response.status_code}\n\n return response.json()\n except requests.RequestException as e:\n print(f\"Error making API request: {e}\")\n return None\n\n def get_authorization_header(\n self, method: str, path: str, body: str, timestamp: int\n ) -> Dict[str, str]:\n message_to_sign = f\"{self.api_key}{timestamp}{path}{method}{body}\"\n signed = self.private_key.sign(message_to_sign.encode(\"utf-8\"))\n\n return {\n \"x-api-key\": self.api_key,\n \"x-signature\": base64.b64encode(signed.signature).decode(\"utf-8\"),\n \"x-timestamp\": str(timestamp),\n }\n\n def get_accounts(self) -> Any:\n path = \"/api/v2/crypto/trading/accounts/\"\n return self.make_api_request(\"GET\", path)\n\n # The symbols argument must be formatted in trading pairs, e.g \"BTC-USD\", \"ETH-USD\". If no symbols are provided,\n # all supported symbols will be returned\n def get_trading_pairs(self, *symbols: Optional[str]) -> list:\n params = {\"symbol\": list(symbols)} if symbols else {}\n query_params = self.get_query_params(params)\n path = f\"/api/v2/crypto/trading/trading_pairs/{query_params}\"\n \n all_results = []\n response = self.make_api_request(\"GET\", path)\n \n while response:\n results = response.get(\"results\", [])\n all_results.extend(results)\n \n next_url = response.get(\"next\")\n if not next_url:\n break\n \n next_path = next_url.replace(self.base_url, \"\")\n response = self.make_api_request(\"GET\", next_path)\n \n return all_results\n\n # The asset_codes argument must be formatted as the short form name for a crypto, e.g \"BTC\", \"ETH\". If no asset\n # codes are provided, all crypto holdings will be returned\n def get_holdings(self, account_number: str, *asset_codes: Optional[str]) -> Any:\n params = {\"account_number\": account_number}\n if asset_codes:\n params[\"asset_code\"] = list(asset_codes)\n query_params = self.get_query_params(params)\n path = f\"/api/v2/crypto/trading/holdings/{query_params}\"\n return self.make_api_request(\"GET\", path)\n\n # The symbols argument must be formatted in trading pairs, e.g \"BTC-USD\", \"ETH-USD\".\n def get_best_bid_ask(self, *symbols: str) -> Any:\n params = {\"symbol\": list(symbols)} if symbols else {}\n query_params = self.get_query_params(params)\n path = f\"/api/v2/crypto/marketdata/best_bid_ask/{query_params}\"\n return self.make_api_request(\"GET\", path)\n\n # The symbol argument must be formatted in a trading pair, e.g \"BTC-USD\", \"ETH-USD\"\n # The side argument must be \"bid\", \"ask\", or \"both\".\n # Multiple quantities can be specified in the quantity argument, e.g. \"0.1,1,1.999\".\n def get_estimated_price(self, symbol: str, side: str, quantity: str) -> Any:\n params = {\"symbol\": symbol, \"side\": side, \"quantity\": quantity}\n query_params = self.get_query_params(params)\n path = f\"/api/v2/crypto/trading/estimated_price/{query_params}\"\n return self.make_api_request(\"GET\", path)\n\n def place_order(\n self,\n account_number: str,\n client_order_id: str,\n side: str,\n order_type: str,\n symbol: str,\n order_config: Dict[str, str],\n ) -> Any:\n body = {\n \"client_order_id\": client_order_id,\n \"side\": side,\n \"type\": order_type,\n \"symbol\": symbol,\n f\"{order_type}_order_config\": order_config,\n }\n params = {\"account_number\": account_number}\n query_params = self.get_query_params(params)\n path = f\"/api/v2/crypto/trading/orders/{query_params}\"\n return self.make_api_request(\"POST\", path, json.dumps(body))\n\n def cancel_order(self, order_id: str) -> Any:\n path = f\"/api/v2/crypto/trading/orders/{order_id}/cancel/\"\n return self.make_api_request(\"POST\", path)\n\n def get_order(self, account_number: str, order_id: str) -> Any:\n params = {\"account_number\": account_number}\n query_params = self.get_query_params(params)\n path = f\"/api/v2/crypto/trading/orders/{order_id}/{query_params}\"\n return self.make_api_request(\"GET\", path)\n\n def get_orders(self, account_number: str) -> Any:\n params = {\n \"account_number\": account_number,\n \"created_at_start\": \"2023-01-01T20:57:50Z\"\n }\n query_params = self.get_query_params(params)\n path = f\"/api/v2/crypto/trading/orders/{query_params}\"\n return self.make_api_request(\"GET\", path)\n\n\ndef main():\n api_trading_client = CryptoAPITradingV2()\n print(api_trading_client.get_trading_pairs())\n # print(api_trading_client.get_trading_pairs(\"BTC-USD\", \"ETH-USD\"))\n # print(api_trading_client.get_best_bid_ask(\"BTC-USD\")) #\"BTC-USD\", \"ETH-USD\"\n # print(api_trading_client.get_estimated_price(symbol=\"BTC-USD\", side=\"both\", quantity=\"0.01\"))\n\n # accounts = api_trading_client.get_accounts()\n # print(accounts)\n # account_number = accounts[\"results\"][0][\"account_number\"]\n # print(f\"account_number: {account_number}\")\n # print(api_trading_client.get_orders(account_number))\n # print(api_trading_client.get_holdings(account_number))\n # print(api_trading_client.get_holdings(account_number, \"BTC\", \"ETH\"))\n\n \"\"\"\n BUILD YOUR TRADING STRATEGY HERE\n\n order = api_trading_client.place_order(\n account_number,\n str(uuid.uuid4()),\n \"buy\",\n \"market\",\n \"BTC-USD\",\n {\"asset_quantity\": \"0.000001\"}\n )\n \"\"\"\n\n\nif __name__ == \"__main__\":\n main()\n```\n\n5. Run your script from the command line\n\n```console\n# to run the Python script using the v1 API endpoints:\npython robinhood_api_trading.py\n# to run the Python script using the v2 API endpoints:\npython robinhood_api_trading_v2.py\n```\n\n\n# Pagination\n\n\n Endpoints that return a list of results allow you to paginate to have more control over how many and which results to display.\n\n\n### Pagination Parameters\n\n| Parameter | Description |\n|-|-|\n| cursor | The cursor is a unique identifier for each page in a list of results. The cursor is used to paginate through the pages of results. |\n| limit | The limit is the number of items to return in a single page. Some of our endpoints support this query parameter. You can view support by checking the query parameters in the documentation of each endpoint. |\n\n\n### Pagination Response\n\n\n| Field | Description |\n|-|-|\n| next | The API request endpoint that includes the next cursor query parameter to use for pagination. |\n| previous | The API request endpoint that includes the previous cursor query parameter to use for pagination. |\n| results | The list of response items for the current cursor.\n\n\n# Rate Limiting\n\n\n### Rate Limits\n* Requests per minute per user account: 100\n* Requests per minute per user account in bursts: 300\n\n\nRate limiting is applied using a token bucket implementation. The burst size or `capacity` is the number of tokens you can use to call an endpoint. This capacity is initialized at the maximum capacity and will be refilled using a `refill amount` at a timed interval called `refill interval` until the max capacity is once again reached.\n\n\n### Rate Limiting Terms\n\n\n| Term | Description |\n|-|-|\n| Max capacity | The maximum amount of tokens allowed. Will no longer continue refilling if this amount is reached. |\n| Remaining amount | The number of tokens remaining that can be consumed to call an endpoint. |\n| Refill amount | The number of tokens that are refilled at each refill interval. |\n| Refill interval | The timed interval at which the tokens are refilled.\n\n The actual values of the configuration will fluctuate depending on the availability of our service and our current expected volume at the time of service. Rate limits are applied per endpoint and may differ among each endpoint depending on their expected use case.\n\n\n #### Example rate limiting configuration:\n\n\n| Term | Value |\n|-|-|\n| Max capacity | 5 |\n| Remaining amount | 2 |\n| Refill amount | 1 |\n| Refill interval | 1 second |\n\n\n| Action | Time (in seconds) | Remaining amount | Description |\n|-|-|-|-|\n| Initialize | 0 | 5 | Initial state of the token bucket. |\n| Endpoint call 1 | 0.5 | 4 | One token consumed for calling endpoint 1. |\n| Endpoint call 2 | 0.7 | 3 | One token consumed for calling endpoint 2. |\n| Refill | 1 | 4 | One token refilled at refill interval. |\n| Refill | 2 | 5 | One token refilled at refill interval. |\n| No refill | 3 | 5 | No refill since max capacity has been reached and no endpoints were called. |\n| Endpoint call 3 | 3.5 | 4 | One token consumed for calling endpoint 3.\n\n\n# Error Responses\n\n\n### Error response format\n\n#### Type\n The `type` field in the error response will be mapped to the following:\n | Error type | Status codes |\n|-|-|\n| validation_error | 400 |\n| client_error | 4XX, excluding 400 |\n| server_error | 5XX |\n\n\n#### Errors\nThe `errors` field will contain a list of error details, each item will contain a nested `attr` and `detail` field.\n| Field | Description |\n|-|-|\n| attr | Error types of `validation_error` will specify the field name or `non_field_errors` if the error cannot be attributed to a field. Will be `null` for error types of either `client_error` and `server_error`. |\n| detail | Will contain a human readable string describing the error. |\n\n\n\n### Example Error Response\nHere's a sample error response where the `client_order_id` field in the payload was a value that was not expected when calling the ***Add Crypto Order*** endpoint. The `detail` field for each error in the `errors` list will help understand why the `validation_error` was thrown. The `attr` field will indicate which field name in the request body or query parameter the error was thrown for if applicable.\n```javascript\n{\n \"type\": \"validation_error\"\n \"errors\": [\n {\n \"detail\": \"Must be a valid UUID.\",\n \"attr\": \"client_order_id\"\n }\n ]\n}\n```\n\n\n### Common Error Status Codes\n | Status Code | Error |\n|-|-|\n| 400 | Bad request |\n| 401 | Unauthorized |\n| 403 | Forbidden |\n| 404 | Not found |\n| 405 | Method not allowed |\n| 406 | Not acceptable |\n| 415 | Unsupported media type |\n| 429 | Too many requests |\n| 500 | Internal server error |\n| 503 | Service unavailable |"- },- "servers": [- {- "url": "https://trading.robinhood.com/"- }- ],- "security": [- {- "API Key": [],- "API Signature": [],- "Timestamp": []- }- ],- "paths": {- "/api/v1/crypto/trading/accounts/": {- "security": [- {- "API Key": [],- "API Signature": [],- "Timestamp": []- }- ],- "get": {- "tags": [- "Account"- ],- "summary": "Get Crypto Trading Account Details",- "description": "Fetches the Robinhood Crypto account details for the current user.",- "operationId": "api_v1_crypto_trading_account_Details",- "x-codeSamples": [- {- "lang": "cURL",- "source": "curl -X \"GET\" \"https://trading.robinhood.com/api/v1/crypto/trading/accounts/\" \\\n -H 'x-api-key: <YOUR-API-KEY>' \\\n -H 'x-timestamp: <timestamp unix>' \\\n -H 'x-signature: <YOUR-MSG-SIGNATURE>' \\\n -H 'Content-Type: application/json; charset=utf-8'\n"- }- ],- "responses": {- "200": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/Account"- }- }- }- }- }- }- },- "/api/v1/crypto/trading/trading_pairs/": {- "security": [- {- "API Key": [],- "API Signature": [],- "Timestamp": []- }- ],- "get": {- "tags": [- "Trading"- ],- "summary": "Get Crypto Trading Pairs",- "description": "Fetch a list of trading pairs.",- "operationId": "api_v1_crypto_trading_trading_pairs",- "parameters": [- {- "name": "symbol",- "description": "List of trading pair symbol(s) to retrieve data for.\n\nMultiple symbols can be provided by using the \"symbol\" parameter with different values. Ensure that the symbol(s) are provided in all uppercase.\n\nFor example, **?symbol=BTC-USD&symbol=ETH-USD**",- "example": "BTC-USD",- "in": "query",- "schema": {- "type": "string"- }- },- {- "name": "limit",- "description": "Limit the number of results per page size",- "in": "query",- "required": false,- "schema": {- "type": "integer"- }- },- {- "name": "cursor",- "in": "query",- "schema": {- "type": "string"- }- }- ],- "x-codeSamples": [- {- "lang": "cURL",- "source": "curl -X \"GET\" \"https://trading.robinhood.com/api/v1/crypto/trading/trading_pairs/?symbol=BTC-USD\" \\\n -H 'x-api-key: <YOUR-API-KEY>' \\\n -H 'x-timestamp: <timestamp unix>' \\\n -H 'x-signature: <YOUR-MSG-SIGNATURE>' \\\n -H 'Content-Type: application/json; charset=utf-8'\n"- }- ],- "responses": {- "200": {- "description": "",- "content": {- "application/json": {- "schema": {- "required": [- "results"- ],- "type": "object",- "properties": {- "next": {- "type": "string",- "format": "uri",- "nullable": true,- "example": "https://trading.robinhood.com/api/v1/crypto/trading/trading_pairs/?cursor={CURSOR_ID}"- },- "previous": {- "type": "string",- "format": "uri",- "nullable": true,- "example": "https://trading.robinhood.com/api/v1/crypto/trading/trading_pairs/?cursor={CURSOR_ID}"- },- "results": {- "type": "array",- "items": {- "$ref": "#/components/schemas/TradingPair"- }- }- }- }- }- }- },- "400": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- }- }- }- },- "404": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- },- "example": {- "type": "client_error",- "errors": [- {- "detail": "string",- "attr": null- }- ]- }- }- }- }- }- }- },- "/api/v1/crypto/trading/holdings/": {- "security": [- {- "API Key": [],- "API Signature": [],- "Timestamp": []- }- ],- "get": {- "tags": [- "Trading"- ],- "summary": "Get Crypto Holdings",- "description": "Fetch a list of holdings for the current user.",- "operationId": "api_v1_crypto_trading_holdings",- "parameters": [- {- "name": "asset_code",- "description": "The asset code(s) to retrieve data for.\n\nMultiple asset codes can be provided by using the \"asset_code\" parameter with different values. Ensure that the asset codes are provided in all uppercase.\n\nFor example, **?asset_code=BTC&asset_code=ETH**",- "example": "BTC",- "in": "query",- "required": false,- "schema": {- "type": "string"- }- },- {- "name": "limit",- "description": "Limit the number of results per page size",- "in": "query",- "required": false,- "schema": {- "type": "integer"- }- },- {- "name": "cursor",- "in": "query",- "required": false,- "schema": {- "type": "string"- }- }- ],- "x-codeSamples": [- {- "lang": "cURL",- "source": "curl -X \"GET\" \"https://trading.robinhood.com/api/v1/crypto/trading/holdings/?asset_code=BTC\" \\\n -H 'x-api-key: <YOUR-API-KEY>' \\\n -H 'x-timestamp: <timestamp unix>' \\\n -H 'x-signature: <YOUR-MSG-SIGNATURE>' \\\n -H 'Content-Type: application/json; charset=utf-8'\n"- }- ],- "responses": {- "200": {- "description": "",- "content": {- "application/json": {- "schema": {- "required": [- "results"- ],- "type": "object",- "properties": {- "next": {- "type": "string",- "format": "uri",- "nullable": true,- "example": "https://trading.robinhood.com/api/v1/crypto/trading/holdings?cursor={CURSOR_ID}"- },- "previous": {- "type": "string",- "format": "uri",- "nullable": true,- "example": "https://trading.robinhood.com/api/v1/crypto/trading/holdings?cursor={CURSOR_ID}"- },- "results": {- "type": "array",- "items": {- "$ref": "#/components/schemas/Holdings"- }- }- }- }- }- }- },- "400": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- }- }- }- },- "404": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- },- "example": {- "type": "client_error",- "errors": [- {- "detail": "string",- "attr": null- }- ]- }- }- }- }- }- }- },- "/api/v1/crypto/trading/orders/": {- "security": [- {- "API Key": [],- "API Signature": [],- "Timestamp": []- }- ],- "get": {- "tags": [- "Trading"- ],- "summary": "Get Crypto Orders",- "description": "Fetch a list of orders for the current user.",- "operationId": "api_v1_crypto_trading_orders",- "parameters": [- {- "name": "created_at_start",- "description": "Filter by created at start time range (greater than or equal to) in ISO 8601 format",- "example": "2023-10-31T20:57:50Z",- "in": "query",- "required": false,- "schema": {- "type": "string"- }- },- {- "name": "created_at_end",- "description": "Filter by created at end time range (less than or equal to) in ISO 8601 format",- "example": "2023-10-31T20:57:50Z",- "in": "query",- "required": false,- "schema": {- "type": "string"- }- },- {- "name": "symbol",- "description": "Currency pair symbol. Ensure that the symbol is provided in all uppercase.",- "example": "BTC-USD",- "in": "query",- "required": false,- "schema": {- "type": "string"- }- },- {- "name": "id",- "description": "Order ID, unique per order",- "in": "query",- "required": false,- "schema": {- "type": "string",- "format": "uuid"- }- },- {- "name": "side",- "description": "Buy or sell",- "in": "query",- "required": false,- "schema": {- "type": "string",- "enum": [- "buy",- "sell"- ]- }- },- {- "name": "state",- "description": "State of the order",- "in": "query",- "required": false,- "schema": {- "type": "string",- "enum": [- "open",- "canceled",- "partially_filled",- "filled",- "failed"- ]- }- },- {- "name": "type",- "description": "Type of order",- "in": "query",- "required": false,- "schema": {- "type": "string",- "enum": [- "limit",- "market",- "stop_limit",- "stop_loss"- ]- }- },- {- "name": "updated_at_start",- "description": "Filter by updated at start time range (greater than or equal to) in ISO 8601 format",- "example": "2023-10-31T20:57:50Z",- "in": "query",- "required": false,- "schema": {- "type": "string"- }- },- {- "name": "updated_at_end",- "description": "Filter by updated at end time range (less than or equal to) in ISO 8601 format",- "example": "2023-10-31T20:57:50Z",- "in": "query",- "required": false,- "schema": {- "type": "string"- }- },- {- "name": "cursor",- "in": "query",- "required": false,- "schema": {- "type": "string"- }- },- {- "name": "limit",- "description": "Limit the number of results per page size",- "in": "query",- "required": false,- "schema": {- "type": "integer"- }- }- ],- "x-codeSamples": [- {- "lang": "cURL",- "source": "curl -X \"GET\" \"https://trading.robinhood.com/api/v1/crypto/trading/orders/\" \\\n -H 'x-api-key: <YOUR-API-KEY>' \\\n -H 'x-timestamp: <timestamp unix>' \\\n -H 'x-signature: <YOUR-MSG-SIGNATURE>' \\\n -H 'Content-Type: application/json; charset=utf-8'\n"- }- ],- "responses": {- "200": {- "description": "",- "content": {- "application/json": {- "schema": {- "required": [- "results"- ],- "type": "object",- "properties": {- "next": {- "type": "string",- "format": "uri",- "nullable": true,- "example": "https://trading.robinhood.com/api/v1/crypto/trading/orders/?cursor={CURSOR_ID}"- },- "previous": {- "type": "string",- "format": "uri",- "nullable": true,- "example": "https://trading.robinhood.com/api/v1/crypto/trading/orders/?cursor={CURSOR_ID}"- },- "results": {- "type": "array",- "items": {- "$ref": "#/components/schemas/OrderResponse"- }- }- }- }- }- }- },- "400": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- }- }- }- },- "404": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- },- "example": {- "type": "client_error",- "errors": [- {- "detail": "string",- "attr": null- }- ]- }- }- }- }- }- },- "post": {- "tags": [- "Trading"- ],- "summary": "Place New Crypto Order",- "description": "Places a new crypto trading order with an order type. \n\n **Note**: Depending on the type used in the request body, you must include the respective order configuration in the request body.\n\nFor order configurations that support both `asset_quantity` or `quote_amount`, only one can be present in the request body.",- "operationId": "api_v1_post_crypto_trading_order",- "requestBody": {- "required": true,- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/AddOrder"- }- }- }- },- "x-codeSamples": [- {- "lang": "cURL",- "source": "curl -X \"POST\" \"https://trading.robinhood.com/api/v1/crypto/trading/orders/\" \\\n -H 'x-api-key: <YOUR-API-KEY>' \\\n -H 'x-timestamp: <timestamp unix>' \\\n -H 'x-signature: <YOUR-MSG-SIGNATURE>' \\\n -H 'Content-Type: application/json; charset=utf-8' \\\n --data-raw '{\"client_order_id\":\"131de903-5a9c-4260-abc1-28d562a5dcf0\",\"side\":\"buy\",\"type\":\"market\",\"symbol\":\"BTC-USD\",\"market_order_config\":{\"asset_quantity\":\"0.1\"}}' \n"- }- ],- "responses": {- "201": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/OrderResponse"- }- }- }- },- "400": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- }- }- }- }- }- }- },- "/api/v1/crypto/trading/orders/{id}/cancel/": {- "security": [- {- "API Key": [],- "API Signature": [],- "Timestamp": []- }- ],- "post": {- "tags": [- "Trading"- ],- "summary": "Cancel Open Crypto Order",- "description": "Cancels an open crypto trading order.",- "operationId": "api_v1_post_crypto_trading_cancel_order",- "parameters": [- {- "name": "id",- "in": "path",- "description": "Order ID, unique per order",- "required": true,- "schema": {- "type": "string",- "format": "uuid"- }- }- ],- "x-codeSamples": [- {- "lang": "cURL",- "source": "curl -X \"POST\" \"https://trading.robinhood.com/api/v1/crypto/trading/orders/{id}/cancel/\" \\\n -H 'x-api-key: <YOUR-API-KEY>' \\\n -H 'x-timestamp: <timestamp unix>' \\\n -H 'x-signature: <YOUR-MSG-SIGNATURE>' \\\n -H 'Content-Type: application/json; charset=utf-8' \n"- }- ],- "responses": {- "200": {- "description": "",- "content": {- "text/plain": {- "schema": {- "type": "string",- "description": "Success string with order id"- },- "example": "Cancel request was submitted for order {id}"- }- }- },- "400": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- }- }- }- },- "404": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- },- "example": {- "type": "client_error",- "errors": [- {- "detail": "string",- "attr": null- }- ]- }- }- }- }- }- }- },- "/api/v1/crypto/marketdata/best_bid_ask/": {- "security": [- {- "API Key": [],- "API Signature": [],- "Timestamp": []- }- ],- "get": {- "tags": [- "Market Data"- ],- "summary": "Get Best Price",- "description": "Fetch a single bid and ask price per symbol, representing the best available price across our partner market makers. This price does not take into account the order size, and may not be the final execution price.\n\nThe bid and ask prices include a spread. The buy spread is the percent difference between the ask and the mid price. The sell spread is the percent difference between the bid and the mid price.\n\nNote that in the v2 endpoint, **Place crypto orders with fee tiers**, partner exchanges provide prices instead of market makers, with orders routed accordingly. For more information on routing, visit our [<u>Help Center</u>](https://robinhood.com/us/en/support/articles/crypto-order-routing/).",- "operationId": "api_v1_crypto_marketdata_best_bid_ask",- "parameters": [- {- "name": "symbol",- "in": "query",- "description": "List of trading pair symbol(s) to retrieve data for.\n\nMultiple symbols can be provided by using the \"symbol\" parameter with different values. Ensure that the symbol(s) are provided in all uppercase.\n\nFor example, **?symbol=BTC-USD&symbol=ETH-USD**",- "example": "BTC-USD",- "schema": {- "type": "string"- }- }- ],- "x-codeSamples": [- {- "lang": "cURL",- "source": "curl -X \"GET\" \"https://trading.robinhood.com/api/v1/crypto/marketdata/best_bid_ask/?symbol=BTC-USD\" \\\n -H 'x-api-key: <YOUR-API-KEY>' \\\n -H 'x-timestamp: <timestamp unix>' \\\n -H 'x-signature: <YOUR-MSG-SIGNATURE>' \\\n -H 'Content-Type: application/json; charset=utf-8' \n"- }- ],- "responses": {- "200": {- "description": "",- "content": {- "application/json": {- "schema": {- "required": [- "results"- ],- "type": "object",- "properties": {- "results": {- "type": "array",- "items": {- "$ref": "#/components/schemas/BidAskPrice"- }- }- }- }- }- }- },- "400": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- }- }- }- }- }- }- },- "/api/v1/crypto/marketdata/estimated_price/": {- "security": [- {- "API Key": [],- "API Signature": [],- "Timestamp": []- }- ],- "get": {- "tags": [- "Market Data"- ],- "summary": "Get Estimated Price",- "description": "This endpoint returns the estimated total cost or credit for a particular symbol, book side, and asset quantity. You can include a list of quantities in a single request to retrieve the price for various hypothetical order sizes. \n\nThe estimated price represents the expected execution price if you were to subsequently place an order. To estimate the cost for a Buy order, request an Ask quote. If you are preparing to place a Sell order, request a Bid quote. The execution price may vary due to market volatility and once executed the transaction may not be undone.\n\nThe bid and ask prices are the best prices our market makers provide for an order, inclusive of a spread. The buy spread is the percent difference between the ask and the mid price. The sell spread is the percent difference between the bid and the mid price.",- "operationId": "api_v1_crypto_marketdata_estimated_price",- "parameters": [- {- "name": "symbol",- "in": "query",- "description": "A string matching a valid currency pair, for example BTC-USD. Ensure that the symbol is provided in all uppercase.\n\nOnly USD symbols are accepted.",- "example": "BTC-USD",- "required": true,- "schema": {- "type": "string"- }- },- {- "name": "side",- "in": "query",- "description": "Order side. e.g. bid, ask, or both.",- "example": "bid",- "required": true,- "schema": {- "type": "string",- "enum": [- "bid",- "ask",- "both"- ]- }- },- {- "name": "quantity",- "in": "query",- "description": "Quantity must be between `min_order_size` and `max_order_size` as defined in our `Get Crypto Trading Pairs` endpoint.\n\n A max of 10 quantities can be specified for each request.",- "example": "0.1,1,1.999",- "required": true,- "schema": {- "type": "string"- }- }- ],- "x-codeSamples": [- {- "lang": "cURL",- "source": "curl -X \"GET\" \"https://trading.robinhood.com/marketdata/api/v1/estimated_price/?symbol=BTC-USD&side=ask&quantity=0.1,1,1.999\" \\\n -H 'x-api-key: <YOUR-API-KEY>' \\\n -H 'x-timestamp: <timestamp unix>' \\\n -H 'x-signature: <YOUR-MSG-SIGNATURE>' \\\n -H 'Content-Type: application/json; charset=utf-8' \n"- }- ],- "responses": {- "200": {- "description": "",- "content": {- "application/json": {- "schema": {- "required": [- "results"- ],- "type": "object",- "properties": {- "results": {- "type": "array",- "items": {- "$ref": "#/components/schemas/EstimatedPrice"- }- }- }- }- }- }- },- "400": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- }- }- }- }- }- }- },- "/api/v2/crypto/trading/accounts/": {- "security": [- {- "API Key": [],- "API Signature": [],- "Timestamp": []- }- ],- "get": {- "tags": [- "V2 Account"- ],- "summary": "Get Accounts",- "description": "Retrieve a paginated list of crypto trading accounts for the authenticated user. Returns account details including buying power, status, and fee tier information.",- "operationId": "api_v2_crypto_trading_accounts",- "parameters": [- {- "name": "cursor",- "description": "Optional cursor for pagination. Use the value from `next` or `previous` in the response to navigate through pages.",- "in": "query",- "schema": {- "type": "string"- }- },- {- "name": "limit",- "description": "Optional page size limit. Specifies the number of accounts to return per page. Maximum value is determined by system configuration.",- "in": "query",- "schema": {- "type": "integer"- }- }- ],- "responses": {- "200": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/V2AccountsResponse"- }- }- }- },- "400": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- },- "example": {- "type": "client_error",- "errors": [- {- "detail": "string",- "attr": null- }- ]- }- }- }- },- "401": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- },- "example": {- "type": "client_error",- "errors": [- {- "detail": "string",- "attr": null- }- ]- }- }- }- },- "403": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- },- "example": {- "type": "client_error",- "errors": [- {- "detail": "string",- "attr": null- }- ]- }- }- }- }- }- }- },- "/api/v2/crypto/trading/trading_pairs/": {- "security": [- {- "API Key": [],- "API Signature": [],- "Timestamp": []- }- ],- "get": {- "tags": [- "V2 Trading"- ],- "summary": "Get Trading Pairs",- "description": "Fetch a paginated list of available trading pairs for crypto trading. Returns trading pair details including price increments, order size limits, and tradability status. Trading pairs can be filtered by symbol.",- "operationId": "api_v2_crypto_trading_trading_pairs",- "parameters": [- {- "name": "symbol",- "description": "Optional. Filter by trading pair symbol(s). Example: `symbol=BTC-USD`. Multiple symbols can be provided by using the \"symbol\" parameter with different values. Ensure that the symbol(s) are provided in all uppercase.\n\nFor example, `?symbol=BTC-USD&symbol=ETH-USD`.\n\nIf the \"symbol\" parameter is not provided, this endpoint will return all tradable currency pairs.",- "example": "BTC-USD",- "in": "query",- "schema": {- "type": "string"- }- },- {- "name": "cursor",- "description": "Optional cursor for pagination. Use the value from `next` or `previous` in the response to navigate through pages.",- "in": "query",- "schema": {- "type": "string"- }- },- {- "name": "limit",- "description": "Optional page size limit. Specifies the number of results to return per page. Maximum value is determined by system configuration.",- "in": "query",- "schema": {- "type": "integer"- }- }- ],- "responses": {- "200": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/V2TradingPairsResponse"- }- }- }- },- "401": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- },- "example": {- "type": "client_error",- "errors": [- {- "detail": "string",- "attr": null- }- ]- }- }- }- },- "403": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- },- "example": {- "type": "client_error",- "errors": [- {- "detail": "string",- "attr": null- }- ]- }- }- }- },- "404": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- },- "example": {- "type": "client_error",- "errors": [- {- "detail": "string",- "attr": null- }- ]- }- }- }- }- }- }- },- "/api/v2/crypto/trading/holdings/": {- "security": [- {- "API Key": [],- "API Signature": [],- "Timestamp": []- }- ],- "get": {- "tags": [- "V2 Trading"- ],- "summary": "Get Holdings",- "description": "Retrieve a paginated list of crypto holdings for a specific account. Returns the total quantity and available quantity for each asset held in the account. The `account_number` query parameter is required.",- "operationId": "api_v2_crypto_trading_holdings",- "parameters": [- {- "name": "account_number",- "description": "**Required.** The account number to retrieve holdings for. This parameter must be provided.",- "in": "query",- "required": true,- "schema": {- "type": "string"- }- },- {- "name": "asset_code",- "description": "Optional. Filter holdings by specific asset code (e.g., \"BTC\").",- "example": "BTC",- "in": "query",- "schema": {- "type": "string"- }- },- {- "name": "cursor",- "description": "Optional cursor for pagination. Use the value from `next` or `previous` in the response to navigate through pages.",- "in": "query",- "schema": {- "type": "string"- }- },- {- "name": "limit",- "description": "Optional page size limit. Specifies the number of results to return per page. Maximum value is determined by system configuration.",- "in": "query",- "schema": {- "type": "integer"- }- }- ],- "responses": {- "200": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/V2HoldingsResponse"- }- }- }- },- "400": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- },- "example": {- "type": "client_error",- "errors": [- {- "detail": "string",- "attr": null- }- ]- }- }- }- },- "401": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- },- "example": {- "type": "client_error",- "errors": [- {- "detail": "string",- "attr": null- }- ]- }- }- }- },- "403": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- },- "example": {- "type": "client_error",- "errors": [- {- "detail": "string",- "attr": null- }- ]- }- }- }- }- }- }- },- "/api/v2/crypto/marketdata/best_bid_ask/": {- "security": [- {- "API Key": [],- "API Signature": [],- "Timestamp": []- }- ],- "get": {- "tags": [- "V2 Market Data"- ],- "summary": "Get Best Price",- "description": "Fetch a single bid and ask price per symbol, representing the best available price across our partner exchanges. This price does not take into account the order size or fee, and may not be the final execution price.",- "operationId": "api_v2_crypto_marketdata_best_bid_ask",- "parameters": [- {- "name": "symbol",- "description": "List of trading pair symbol(s) to retrieve data for.\n\nMultiple symbols can be provided by using the \"symbol\" parameter with different values. Ensure that the symbol(s) are provided in all uppercase. Only USD symbols that have `is_api_tradable=true` as defined in our Get Crypto Trading Pairs endpoint are accepted.\n\nFor example, `?symbol=BTC-USD&symbol=ETH-USD`",- "example": "BTC-USD",- "in": "query",- "required": true,- "schema": {- "type": "string"- }- }- ],- "responses": {- "200": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/V2BestBidAskResponse"- }- }- }- },- "400": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- },- "example": {- "type": "validation_error",- "errors": [- {- "detail": "string",- "attr": "string"- }- ]- }- }- }- },- "403": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- },- "example": {- "type": "client_error",- "errors": [- {- "detail": "string",- "attr": null- }- ]- }- }- }- }- }- }- },- "/api/v2/crypto/trading/estimated_price/": {- "security": [- {- "API Key": [],- "API Signature": [],- "Timestamp": []- }- ],- "get": {- "tags": [- "V2 Market Data"- ],- "summary": "Get Estimated Price",- "description": "This endpoint returns the estimated total cost or credit for a particular symbol, book side, asset quantity, and fee. You can include a list of quantities in a single request to retrieve the price for various hypothetical order sizes.\n\nThe estimated price represents the expected execution price if you were to subsequently place an order. The execution price may vary due to market volatility and once executed the transaction may not be undone.\n\nThe bid and ask prices are the best prices our partner exchanges provide for an order, excluding the fee.",- "operationId": "api_v2_crypto_marketdata_estimated_price",- "parameters": [- {- "name": "symbol",- "description": "A string matching a valid currency pair, for example `BTC-USD`. Ensure that the symbol is provided in all uppercase. Only USD symbols that have `is_api_tradable=true` as defined in our Get Crypto Trading Pairs endpoint are accepted.",- "example": "BTC-USD",- "in": "query",- "required": true,- "schema": {- "type": "string"- }- },- {- "name": "side",- "description": "Order side: `bid`, `ask`, or `both`.",- "example": "bid",- "in": "query",- "required": true,- "schema": {- "type": "string",- "enum": [- "bid",- "ask",- "both"- ]- }- },- {- "name": "quantity",- "description": "Quantity must be smaller than `max_order_size` as defined in our Get Crypto Trading Pairs endpoint. Multiple quantities can be comma-separated. A max of 10 quantities can be specified for each request.",- "example": "0.1,1,1.999",- "in": "query",- "required": true,- "schema": {- "type": "string"- }- }- ],- "responses": {- "200": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/V2EstimatedPriceResponse"- }- }- }- },- "400": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- },- "example": {- "type": "validation_error",- "errors": [- {- "detail": "string",- "attr": "string"- }- ]- }- }- }- },- "401": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- },- "example": {- "type": "client_error",- "errors": [- {- "detail": "string",- "attr": null- }- ]- }- }- }- },- "403": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- },- "example": {- "type": "client_error",- "errors": [- {- "detail": "string",- "attr": null- }- ]- }- }- }- }- }- }- },- "/api/v2/crypto/trading/orders/": {- "security": [- {- "API Key": [],- "API Signature": [],- "Timestamp": []- }- ],- "get": {- "tags": [- "V2 Trading"- ],- "summary": "Get Orders",- "description": "Fetch a list of orders for the current user in a specific account.",- "operationId": "api_v2_crypto_trading_orders_get",- "parameters": [- {- "name": "account_number",- "description": "Required. The number of the crypto account to retrieve orders from.",- "in": "query",- "required": true,- "schema": {- "type": "string"- }- },- {- "name": "cursor",- "description": "Optional cursor for pagination.",- "in": "query",- "schema": {- "type": "string"- }- },- {- "name": "created_at_start",- "description": "Filter orders created on or after this timestamp (ISO 8601 format).",- "in": "query",- "schema": {- "type": "string",- "format": "date-time"- }- },- {- "name": "created_at_end",- "description": "Filter orders created on or before this timestamp (ISO 8601 format).",- "in": "query",- "schema": {- "type": "string",- "format": "date-time"- }- },- {- "name": "updated_at_start",- "description": "Filter orders updated on or after this timestamp (ISO 8601 format).",- "in": "query",- "schema": {- "type": "string",- "format": "date-time"- }- },- {- "name": "updated_at_end",- "description": "Filter orders updated on or before this timestamp (ISO 8601 format).",- "in": "query",- "schema": {- "type": "string",- "format": "date-time"- }- },- {- "name": "symbol",- "description": "Filter orders by trading pair symbol.",- "in": "query",- "schema": {- "type": "string"- }- },- {- "name": "side",- "description": "Filter orders by side.",- "in": "query",- "schema": {- "type": "string",- "enum": [- "buy",- "sell"- ]- }- },- {- "name": "type",- "description": "Filter orders by type.",- "in": "query",- "schema": {- "type": "string",- "enum": [- "market",- "limit",- "stop_loss",- "stop_limit"- ]- }- },- {- "name": "state",- "description": "Filter orders by state.",- "in": "query",- "schema": {- "type": "string",- "enum": [- "open",- "canceled",- "filled",- "failed",- "pending"- ]- }- }- ],- "responses": {- "200": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/V2OrdersResponse"- }- }- }- },- "400": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- },- "example": {- "type": "client_error",- "errors": [- {- "detail": "string",- "attr": null- }- ]- }- }- }- },- "401": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- },- "example": {- "type": "client_error",- "errors": [- {- "detail": "string",- "attr": null- }- ]- }- }- }- },- "403": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- },- "example": {- "type": "client_error",- "errors": [- {- "detail": "string",- "attr": null- }- ]- }- }- }- },- "404": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- },- "example": {- "type": "client_error",- "errors": [- {- "detail": "string",- "attr": null- }- ]- }- }- }- }- }- },- "post": {- "tags": [- "V2 Trading"- ],- "summary": "Place New Crypto Order",- "description": "Place a new crypto trading order with an order type. This endpoint only supports placing orders on USD symbols that have `is_api_tradable=true` as defined in our Get Crypto Trading Pairs endpoint.\n\n**Note:** Depending on the type used in the request body, you must include the respective order configuration in the request body.\n\nFor order configurations that support both `asset_quantity` or `quote_amount`, only one can be present in the request body.",- "operationId": "api_v2_crypto_trading_orders_post",- "parameters": [- {- "name": "account_number",- "description": "Required. The number of the crypto account to place orders from.",- "in": "query",- "required": true,- "schema": {- "type": "string"- }- }- ],- "requestBody": {- "required": true,- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/AddOrderV2"- }- }- }- },- "responses": {- "201": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/V2CryptoOrder"- }- }- }- },- "400": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- },- "example": {- "type": "client_error",- "errors": [- {- "detail": "string",- "attr": null- }- ]- }- }- }- },- "401": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- },- "example": {- "type": "client_error",- "errors": [- {- "detail": "string",- "attr": null- }- ]- }- }- }- },- "403": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- },- "example": {- "type": "client_error",- "errors": [- {- "detail": "string",- "attr": null- }- ]- }- }- }- },- "404": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- },- "example": {- "type": "client_error",- "errors": [- {- "detail": "string",- "attr": null- }- ]- }- }- }- }- }- }- },- "/api/v2/crypto/trading/orders/{id}/cancel/": {- "security": [- {- "API Key": [],- "API Signature": [],- "Timestamp": []- }- ],- "post": {- "tags": [- "V2 Trading"- ],- "summary": "Cancel Open Crypto Order",- "description": "Cancels an open crypto trading order.",- "operationId": "api_v2_crypto_trading_cancel_order",- "parameters": [- {- "name": "id",- "description": "The ID of the order to cancel.",- "in": "path",- "required": true,- "schema": {- "type": "string",- "format": "uuid"- }- }- ],- "responses": {- "200": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/V2CryptoOrder"- }- }- }- },- "400": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- },- "example": {- "type": "validation_error",- "errors": [- {- "detail": "string",- "attr": "string"- }- ]- }- }- }- },- "403": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- },- "example": {- "type": "client_error",- "errors": [- {- "detail": "string",- "attr": null- }- ]- }- }- }- }- }- }- }- },- "tags": [- {- "name": "V2 Account",- "x-displayName": "Account"- },- {- "name": "V2 Market Data",- "x-displayName": "Market Data"- },- {- "name": "V2 Trading",- "x-displayName": "Trading"- }- ],- "components": {- "requestParameters": {- "TimeInForce": {- "description": "The time in force of the order.\n\n- **Good til canceled (gtc):** The order remains open until it's filled or the user cancels it.\n\n- **Good for day (gfd):** The order remains open until the end of the day or when the user cancels it.\n\n- **Good for week (gfw):** The order remains open until the end of the week or when the user cancels it.\n\n- **Good for month (gfm):** The order remains open until the end of the month or when the user cancels it.",- "type": "string",- "enum": [- "gtc",- "gfd",- "gfw",- "gfm"- ]- }- },- "schemas": {- "Account": {- "type": "object",- "properties": {- "account_number": {- "title": "Account number",- "description": "The account number of the crypto account",- "type": "string",- "readOnly": true- },- "status": {- "title": "Status",- "description": "User account status for trading",- "type": "string",- "enum": [- "active",- "deactivated",- "sell_only"- ]- },- "buying_power": {- "title": "Buying power",- "description": "User buying power amount in fiat currency",- "type": "string",- "readOnly": true- },- "buying_power_currency": {- "title": "Buying power currency",- "description": "Example: USD",- "type": "string",- "readOnly": true- }- }- },- "V2Account": {- "type": "object",- "properties": {- "account_number": {- "title": "Account number",- "description": "The unique account number identifier.",- "type": "string"- },- "status": {- "title": "Status",- "description": "The current status of the account.",- "type": "string",- "enum": [- "active",- "deactivated",- "sell_only"- ]- },- "buying_power": {- "title": "Buying power",- "description": "The available buying power in the account.",- "type": "string"- },- "buying_power_currency": {- "title": "Buying power currency",- "description": "The currency of the buying power (e.g., \"USD\").",- "type": "string"- },- "account_type": {- "title": "Account type",- "description": "The type of account (e.g., individual).",- "type": "string"- },- "is_api_tradable": {- "title": "Is API tradable",- "description": "Indicates whether the account can be used for API trading. True for the default account.",- "type": "boolean"- },- "fee_tier_status": {- "title": "Fee tier status",- "description": "Optional. Fee tier information for the account, if available. See object fields below.",- "allOf": [- {- "$ref": "#/components/schemas/FeeTierStatus"- }- ]- }- }- },- "FeeTierStatus": {- "type": "object",- "properties": {- "fee_ratio": {- "title": "Fee ratio",- "description": "The current fee ratio applied to the value executed for each order.",- "type": "number",- "format": "double"- },- "thirty_day_volume": {- "title": "Thirty day volume",- "description": "Trailing 30-day trading volume of crypto fee tier orders.",- "type": "number",- "format": "double"- },- "next_fee_tier_ratio": {- "title": "Next fee tier ratio",- "description": "Optional. The fee ratio for the next tier. Null if already at the highest tier (lowest fee).",- "type": "number",- "format": "double",- "nullable": true- },- "next_fee_tier_threshold": {- "title": "Next fee tier threshold",- "description": "Optional. The trading volume required to reach the next fee tier. Null if already at the highest tier (lowest fee).",- "type": "number",- "format": "double",- "nullable": true- }- }- },- "V2AccountsResponse": {- "type": "object",- "properties": {- "next": {- "title": "Next",- "description": "URI for the next page of results. Null if there are no more pages.",- "type": "string",- "nullable": true- },- "previous": {- "title": "Previous",- "description": "URI for the previous page of results. Null if on the first page.",- "type": "string",- "nullable": true- },- "results": {- "title": "Results",- "description": "Array of account objects with the following fields:",- "type": "array",- "items": {- "$ref": "#/components/schemas/V2Account"- }- }- }- },- "V2TradingPair": {- "type": "object",- "properties": {- "symbol": {- "title": "Symbol",- "description": "The trading pair symbol (e.g., \"BTC-USD\").",- "type": "string"- },- "asset_code": {- "title": "Asset code",- "description": "The code for the asset currency (e.g., \"BTC\").",- "type": "string"- },- "quote_code": {- "title": "Quote code",- "description": "The code for the quote currency (e.g., \"USD\").",- "type": "string"- },- "asset_increment": {- "title": "Asset increment",- "description": "The minimum quantity increment for placing orders in the asset currency. Up to 18 decimal places.",- "type": "string"- },- "quote_increment": {- "title": "Quote increment",- "description": "The minimum price increment for placing orders in the quote currency. Up to 18 decimal places.",- "type": "string"- },- "max_order_size": {- "title": "Max order size",- "description": "The maximum order size allowed for this trading pair in asset currency. Up to 16 decimal places.",- "type": "string"- },- "min_order_amount": {- "title": "Min order amount",- "description": "The minimum order amount in quote currency (e.g., USD) required for fee tier orders.",- "type": "string"- },- "status": {- "title": "Status",- "description": "The tradability status of the trading pair.",- "type": "string"- },- "is_api_tradable": {- "title": "Is API tradable",- "description": "Indicates whether the trading pair is supported on API trading v2 endpoints (**Place crypto orders with fee tiers**).",- "type": "boolean"- }- }- },- "V2TradingPairsResponse": {- "type": "object",- "properties": {- "next": {- "title": "Next",- "description": "URI for the next page of results. Null if there are no more pages.",- "type": "string",- "nullable": true- },- "previous": {- "title": "Previous",- "description": "URI for the previous page of results. Null if on the first page.",- "type": "string",- "nullable": true- },- "results": {- "title": "Results",- "description": "Array of trading pair objects.",- "type": "array",- "items": {- "$ref": "#/components/schemas/V2TradingPair"- }- }- }- },- "V2Holding": {- "type": "object",- "properties": {- "account_number": {- "title": "Account number",- "description": "The account number that holds this asset.",- "type": "string"- },- "asset_code": {- "title": "Asset code",- "description": "The code for the crypto asset (e.g., \"BTC\", \"ETH\").",- "type": "string"- },- "total_quantity": {- "title": "Total quantity",- "description": "The total quantity of the asset held in the account, including any amounts that are not available for trading.",- "type": "string"- },- "quantity_available_for_trading": {- "title": "Quantity available for trading",- "description": "The quantity of the asset that is currently available for trading (not locked in pending orders or other operations).",- "type": "string"- }- }- },- "V2HoldingsResponse": {- "type": "object",- "properties": {- "next": {- "title": "Next",- "description": "URI for the next page of results. Null if there are no more pages.",- "type": "string",- "nullable": true- },- "previous": {- "title": "Previous",- "description": "URI for the previous page of results. Null if on the first page.",- "type": "string",- "nullable": true- },- "results": {- "title": "Results",- "description": "Array of holding objects.",- "type": "array",- "items": {- "$ref": "#/components/schemas/V2Holding"- }- }- }- },- "V2BestBidAsk": {- "type": "object",- "properties": {- "symbol": {- "title": "Symbol",- "description": "Currency pair symbol.",- "type": "string"- },- "bid": {- "title": "Bid",- "description": "The best price our partner exchanges provide for a sell order.",- "type": "number",- "format": "double"- },- "ask": {- "title": "Ask",- "description": "The best price our partner exchanges provide for a buy order.",- "type": "number",- "format": "double"- }- }- },- "V2BestBidAskResponse": {- "type": "object",- "properties": {- "results": {- "title": "Results",- "description": "Array of bid/ask price objects.",- "type": "array",- "items": {- "$ref": "#/components/schemas/V2BestBidAsk"- }- }- }- },- "V2EstimatedPrice": {- "type": "object",- "properties": {- "symbol": {- "title": "Symbol",- "description": "The trading pair symbol.",- "type": "string"- },- "side": {- "title": "Side",- "description": "Order quote side (bid or ask).",- "type": "string",- "enum": [- "bid",- "ask"- ]- },- "quantity": {- "title": "Quantity",- "description": "Quantity of base currency.",- "type": "number",- "format": "double"- },- "timestamp": {- "title": "Timestamp",- "description": "The time when the price was retrieved from our system.",- "type": "string",- "format": "date-time"- },- "bid": {- "title": "Bid",- "description": "The best price our partner exchanges provide for a sell order.",- "type": "number",- "format": "double"- },- "ask": {- "title": "Ask",- "description": "The best price our partner exchanges provide for a buy order.",- "type": "number",- "format": "double"- },- "fee_ratio": {- "title": "Fee ratio",- "description": "The fee ratio applied to the value executed for each order. For example, 0.0085 corresponds to a 0.85% trading fee.",- "type": "number",- "format": "double"- },- "est_fee": {- "title": "Estimated fee",- "description": "The estimated transaction fee in quote currency (e.g., USD). Calculated as fee_ratio * (price * quantity).",- "type": "number",- "format": "double"- },- "est_total_cost": {- "title": "Estimated total cost",- "description": "The estimated total cost in quote currency for a buy order, including the fee. Calculated as quantity * ask + est_fee.",- "type": "number",- "format": "double"- },- "est_total_credit": {- "title": "Estimated total credit",- "description": "The estimated total credit in quote currency for a sell order, after deducting the fee. Calculated as quantity * bid - est_fee.",- "type": "number",- "format": "double"- }- }- },- "V2EstimatedPriceResponse": {- "type": "object",- "properties": {- "results": {- "title": "Results",- "description": "Array of estimated price objects.",- "type": "array",- "items": {- "$ref": "#/components/schemas/V2EstimatedPrice"- }- }- }- },- "V2CryptoOrder": {- "type": "object",- "description": "V2 Crypto order with fee tier information. Includes all V1 order fields plus fee_charged and estimated_fee_remaining.",- "allOf": [- {- "$ref": "#/components/schemas/OrderResponse"- },- {- "type": "object",- "properties": {- "fee_charged": {- "title": "Fee charged",- "description": "The total fee amount that was charged for this order based on executed fills.",- "type": "number",- "format": "double"- },- "estimated_fee_remaining": {- "title": "Estimated fee remaining",- "description": "The estimated fee amount that will be charged on the remaining unfilled quantity of the order. The amount depends on the execution price and may vary due to market volatility.",- "type": "number",- "format": "double"- }- }- }- ]- },- "V2OrdersResponse": {- "type": "object",- "properties": {- "next": {- "title": "Next",- "description": "URI for the next page of results. Null if there are no more pages.",- "type": "string",- "nullable": true- },- "previous": {- "title": "Previous",- "description": "URI for the previous page of results. Null if on the first page.",- "type": "string",- "nullable": true- },- "results": {- "title": "Results",- "description": "Array of order objects with fee information.",- "type": "array",- "items": {- "$ref": "#/components/schemas/V2CryptoOrder"- }- }- }- },- "BidAskPrice": {- "type": "object",- "properties": {- "symbol": {- "title": "Symbol",- "description": "Currency pair symbol",- "type": "string"- },- "price": {- "title": "Price",- "description": "Midpoint of `bid_inclusive_of_sell_spread` and `ask_inclusive_of_buy_spread`",- "type": "number",- "format": "double"- },- "bid_inclusive_of_sell_spread": {- "title": "Bid inclusive of sell spread",- "description": "The best price our market makers provide for a sell order inclusive of the sell spread",- "type": "number",- "format": "double"- },- "sell_spread": {- "title": "Sell spread",- "description": "The percent difference between the bid and the mid price, included in `bid_inclusive_of_sell_spread`",- "type": "number",- "format": "double"- },- "ask_inclusive_of_buy_spread": {- "title": "Ask inclusive of buy spread",- "description": "The best price our market makers provide for a buy order inclusive of the buy spread",- "type": "number",- "format": "double"- },- "buy_spread": {- "title": "Buy spread",- "description": "The percent difference between the ask and the mid price, included in `ask_inclusive_of_buy_spread`",- "type": "number",- "format": "double"- },- "timestamp": {- "title": "Timestamp",- "description": "The time when the price was retrieved from our system",- "type": "string"- }- }- },- "EstimatedPrice": {- "type": "object",- "properties": {- "symbol": {- "title": "Symbol",- "description": "Currency pair symbol",- "type": "string"- },- "side": {- "title": "Side",- "description": "Order quote side",- "type": "string",- "enum": [- "bid",- "ask"- ]- },- "price": {- "title": "Price",- "description": "Midpoint of `bid_inclusive_of_sell_spread` and `ask_inclusive_of_buy_spread`",- "type": "number",- "format": "double"- },- "quantity": {- "title": "Quantity",- "description": "Quantity of base currency",- "type": "number",- "format": "double"- },- "bid_inclusive_of_sell_spread": {- "title": "Bid inclusive of sell spread",- "description": " The best price our market makers provide for a sell order inclusive of the sell spread",- "type": "number",- "format": "double"- },- "sell_spread": {- "title": "Sell spread",- "description": "The percent difference between the bid and the mid price, included in `bid_inclusive_of_sell_spread`",- "type": "number",- "format": "double"- },- "ask_inclusive_of_buy_spread": {- "title": "Ask inclusive of buy spread",- "description": "The best price our market makers provide for a buy order inclusive of the buy spread",- "type": "number",- "format": "double"- },- "buy_spread": {- "title": "Buy spread",- "description": "The percent difference between the ask and the mid price, included in `ask_inclusive_of_buy_spread`",- "type": "number",- "format": "double"- },- "timestamp": {- "title": "Timestamp",- "description": "The time when the price was retrieved from our system",- "type": "string"- }- }- },- "Holdings": {- "type": "object",- "properties": {- "account_number": {- "title": "The account number of the crypto account",- "type": "string"- },- "asset_code": {- "title": "Asset currency code",- "type": "string"- },- "total_quantity": {- "title": "Total coin quantity user holds",- "type": "number",- "format": "double"- },- "quantity_available_for_trading": {- "title": "Available coin quantity user can trade (sell)",- "type": "number",- "format": "double"- }- }- },- "TradingPair": {- "type": "object",- "properties": {- "asset_code": {- "title": "Asset currency code",- "description": "Example: BTC",- "type": "string"- },- "quote_code": {- "title": "Quote currency code",- "description": "Example: USD",- "type": "string"- },- "quote_increment": {- "title": "Quote increment",- "description": "The precision of the currency price increment.",- "type": "string"- },- "asset_increment": {- "title": "Asset increment",- "description": "The precision of the order of the currency quantity increment.",- "type": "string"- },- "max_order_size": {- "title": "Maximum order size",- "description": "The largest quantity a user can place for the coin per order.",- "type": "string"- },- "min_order_size": {- "title": "Minimum order size",- "description": "The smallest quantity a user has to place for the coin per order.",- "type": "string"- },- "status": {- "title": "Status",- "description": "The status of the currency pair.",- "type": "string",- "enum": [- "tradable",- "untradable",- "sellonly"- ]- },- "symbol": {- "title": "Symbol for this currency pair",- "description": "Example: BTC-USD",- "type": "string"- }- }- },- "OrderResponse": {- "type": "object",- "properties": {- "id": {- "title": "Order ID",- "description": "Unique per order",- "type": "string",- "format": "uuid"- },- "account_number": {- "title": "Account number",- "description": "The account number of the crypto account",- "type": "string"- },- "symbol": {- "title": "Symbol",- "description": "Currency pair symbol",- "type": "string"- },- "client_order_id": {- "title": "Client order ID",- "description": "User input order id for idempotency validation",- "type": "string",- "format": "uuid"- },- "side": {- "title": "Side",- "description": "Buy or sell",- "type": "string",- "enum": [- "buy",- "sell"- ]- },- "executions": {- "items": {- "$ref": "#/components/schemas/OrderExecution"- },- "readOnly": true,- "type": "array"- },- "type": {- "description": "Type of order",- "type": "string",- "enum": [- "limit",- "market",- "stop_limit",- "stop_loss"- ]- },- "state": {- "description": "State of the order",- "type": "string",- "enum": [- "open",- "canceled",- "partially_filled",- "filled",- "failed"- ]- },- "average_price": {- "description": "Average price of all executions",- "type": "number",- "format": "double",- "nullable": true- },- "filled_asset_quantity": {- "description": "Portion of total amount that have been filled",- "type": "number",- "format": "double"- },- "created_at": {- "description": "The timestamp of when the order was created",- "type": "string"- },- "updated_at": {- "description": "The timestamp of when the order was updated",- "type": "string"- },- "market_order_config": {- "description": "Order configuration for market orders",- "type": "object",- "properties": {- "asset_quantity": {- "description": "The quantity of base currency bought or sold",- "type": "number",- "format": "double"- }- }- },- "limit_order_config": {- "description": "Order configuration for limit orders",- "type": "object",- "properties": {- "quote_amount": {- "description": "The amount of quote currency bought or sold",- "type": "number",- "format": "double"- },- "asset_quantity": {- "description": "The quantity of base currency bought or sold",- "type": "number",- "format": "double"- },- "limit_price": {- "description": "The limit price of the order bought or sold",- "type": "number",- "format": "double"- }- }- },- "stop_loss_order_config": {- "description": "Order configuration for stop loss orders",- "type": "object",- "properties": {- "quote_amount": {- "description": "The amount of quote currency bought or sold",- "type": "number",- "format": "double"- },- "asset_quantity": {- "description": "The quantity of base currency bought or sold",- "type": "number",- "format": "double"- },- "stop_price": {- "description": "The stop price of the order bought or sold",- "type": "number",- "format": "double"- },- "time_in_force": {- "$ref": "#/components/requestParameters/TimeInForce"- }- }- },- "stop_limit_order_config": {- "description": "Order configuration for stop limit orders",- "type": "object",- "properties": {- "quote_amount": {- "description": "The amount of quote currency bought or sold",- "type": "number",- "format": "double"- },- "asset_quantity": {- "description": "The quantity of base currency bought or sold",- "type": "number",- "format": "double"- },- "limit_price": {- "description": "The limit price of the order bought or sold",- "type": "number",- "format": "double"- },- "stop_price": {- "description": "The stop price of the order bought or sold",- "type": "number",- "format": "double"- },- "time_in_force": {- "$ref": "#/components/requestParameters/TimeInForce"- }- }- }- }- },- "ErrorResponse": {- "type": "object",- "properties": {- "type": {- "type": "string",- "description": "The error type of the response",- "enum": [- "validation_error",- "client_error",- "server_error"- ]- },- "errors": {- "type": "array",- "description": "List of errors",- "items": {- "type": "object",- "properties": {- "detail": {- "type": "string",- "description": "The error message detail for the error item"- },- "attr": {- "type": "string",- "description": "The attribute name of the error item, typically the field name of the request body or query parameter.",- "nullable": true- }- }- }- }- }- },- "AddOrder": {- "type": "object",- "required": [- "symbol",- "client_order_id",- "side",- "type"- ],- "properties": {- "symbol": {- "title": "Symbol",- "description": "Example: **BTC-USD**\n\nCurrency pair symbol. Ensure that the symbol is provided in all uppercase.",- "type": "string"- },- "client_order_id": {- "title": "Client order ID",- "description": "User input order id for idempotency validation",- "type": "string",- "format": "uuid"- },- "side": {- "title": "Side",- "description": "Buy or sell",- "type": "string",- "enum": [- "buy",- "sell"- ]- },- "type": {- "description": "Type of order",- "type": "string",- "enum": [- "limit",- "market",- "stop_limit",- "stop_loss"- ]- },- "market_order_config": {- "description": "Market order configuration \n\n***Required for market orders**",- "type": "object",- "properties": {- "asset_quantity": {- "description": "The quantity of base currency bought or sold",- "type": "number",- "format": "double"- }- }- },- "limit_order_config": {- "description": "Limit order configuration \n\n***Required for limit orders**",- "type": "object",- "properties": {- "quote_amount": {- "description": "The amount of quote currency bought or sold",- "type": "number",- "format": "double"- },- "asset_quantity": {- "description": "The quantity of base currency bought or sold",- "type": "number",- "format": "double"- },- "limit_price": {- "description": "The limit price of the order bought or sold",- "type": "number",- "format": "double"- }- }- },- "stop_loss_order_config": {- "description": "Stop loss order configuration \n\n***Required for stop loss orders**",- "type": "object",- "properties": {- "quote_amount": {- "description": "The amount of quote currency bought or sold",- "type": "number",- "format": "double"- },- "asset_quantity": {- "description": "The quantity of base currency bought or sold",- "type": "number",- "format": "double"- },- "stop_price": {- "description": "The stop price of the order bought or sold",- "type": "number",- "format": "double"- },- "time_in_force": {- "$ref": "#/components/requestParameters/TimeInForce"- }- }- },- "stop_limit_order_config": {- "description": "Stop limit order configuration \n\n***Required for stop limit orders**",- "type": "object",- "properties": {- "quote_amount": {- "description": "The amount of quote currency bought or sold",- "type": "number",- "format": "double"- },- "asset_quantity": {- "description": "The quantity of base currency bought or sold",- "type": "number",- "format": "double"- },- "limit_price": {- "description": "The limit price of the order bought or sold",- "type": "number",- "format": "double"- },- "stop_price": {- "description": "The stop price of the order bought or sold",- "type": "number",- "format": "double"- },- "time_in_force": {- "$ref": "#/components/requestParameters/TimeInForce"- }- }- }- }- },- "AddOrderV2": {- "type": "object",- "required": [- "symbol",- "client_order_id",- "side",- "type"- ],- "properties": {- "symbol": {- "title": "Symbol",- "description": "Example: **BTC-USD**\n\nCurrency pair symbol. Ensure that the symbol is provided in all uppercase.",- "type": "string"- },- "client_order_id": {- "title": "Client order ID",- "description": "User input order id for idempotency validation",- "type": "string",- "format": "uuid"- },- "side": {- "title": "Side",- "description": "Buy or sell",- "type": "string",- "enum": [- "buy",- "sell"- ]- },- "type": {- "description": "Type of order",- "type": "string",- "enum": [- "limit",- "market",- "stop_limit",- "stop_loss"- ]- },- "market_order_config": {- "description": "Market order configuration \n\n***Required for market orders**",- "type": "object",- "properties": {- "asset_quantity": {- "description": "The quantity of base currency bought or sold",- "type": "number",- "format": "double"- }- }- },- "limit_order_config": {- "description": "Limit order configuration \n\n***Required for limit orders**",- "type": "object",- "properties": {- "quote_amount": {- "description": "The amount of quote currency bought or sold",- "type": "number",- "format": "double"- },- "asset_quantity": {- "description": "The quantity of base currency bought or sold",- "type": "number",- "format": "double"- },- "limit_price": {- "description": "The limit price of the order bought or sold",- "type": "number",- "format": "double"- },- "time_in_force": {- "$ref": "#/components/requestParameters/TimeInForce"- }- }- },- "stop_loss_order_config": {- "description": "Stop loss order configuration \n\n***Required for stop loss orders**",- "type": "object",- "properties": {- "quote_amount": {- "description": "The amount of quote currency bought or sold",- "type": "number",- "format": "double"- },- "asset_quantity": {- "description": "The quantity of base currency bought or sold",- "type": "number",- "format": "double"- },- "stop_price": {- "description": "The stop price of the order bought or sold",- "type": "number",- "format": "double"- },- "time_in_force": {- "$ref": "#/components/requestParameters/TimeInForce"- }- }- },- "stop_limit_order_config": {- "description": "Stop limit order configuration \n\n***Required for stop limit orders**",- "type": "object",- "properties": {- "quote_amount": {- "description": "The amount of quote currency bought or sold",- "type": "number",- "format": "double"- },- "asset_quantity": {- "description": "The quantity of base currency bought or sold",- "type": "number",- "format": "double"- },- "limit_price": {- "description": "The limit price of the order bought or sold",- "type": "number",- "format": "double"- },- "stop_price": {- "description": "The stop price of the order bought or sold",- "type": "number",- "format": "double"- },- "time_in_force": {- "$ref": "#/components/requestParameters/TimeInForce"- }- }- }- }- },- "QuoteBook": {- "type": "object",- "properties": {- "symbol": {- "title": "Symbol",- "description": "Currency pair symbol",- "type": "string"- },- "bids": {- "title": "Bids",- "description": "List of price / quantity tuples, sorted by decreasing price. Represents our available liquidity for sell orders.",- "type": "array",- "items": {- "$ref": "#/components/schemas/QuoteBookItem"- }- },- "asks": {- "title": "Asks",- "description": "List of price / quantity tuples, sorted by increasing price. Represents our available liquidity for buy orders.",- "type": "array",- "items": {- "$ref": "#/components/schemas/QuoteBookItem"- }- },- "timestamp": {- "title": "Timestamp",- "description": "The timestamp of when the price was retrieved from our system",- "type": "string"- }- }- },- "QuoteBookItem": {- "type": "object",- "properties": {- "price": {- "title": "Price",- "description": "The price of the order",- "type": "number",- "format": "double"- },- "quantity": {- "title": "Quantity",- "description": "The quantity of the order",- "type": "number",- "format": "double"- }- }- },- "OrderExecution": {- "properties": {- "effective_price": {- "format": "decimal",- "title": "Effective price",- "type": "string"- },- "quantity": {- "format": "decimal",- "title": "Quantity",- "type": "string"- },- "timestamp": {- "format": "date-time",- "title": "Timestamp",- "type": "string"- }- },- "required": [- "effective_price",- "quantity",- "timestamp"- ],- "type": "object"- }- },- "securitySchemes": {- "API Key": {- "type": "apiKey",- "description": "The \"`x-api-key`\" header should contain your API key. This API key is obtained from your [crypto account settings](https://robinhood.com/account/crypto) when enrolling in the Robinhood Crypto Trading API program.\n\n****API keys issued after August 13, 2024 will be formatted as \"`rh-api-[uuid]`.\" Functionality will remain the same, and older keys will keep the original formatting (no \"`rh-api`\" prepend).***",- "name": "x-api-key",- "in": "header"- },- "API Signature": {- "type": "apiKey",- "description": "Authenticated requests should be signed with the \"`x-signature`\" header, using a signature generated with the following: private key, API key, timestamp, path, method, and body.\n Here’s how the message signature should be defined:\n```console\nmessage = f\"{api_key}{current_timestamp}{path}{method}{body}\"\n```\n****Note that for requests without a body, the body can be omitted from the message signature.***\n\n### Example Signature\n\nThe following is an example of a signature that corresponds to a cancel order request. You may use the example values below to ensure your code implementation is generating the same (`x-signature`) header signature value. The code snippet is for generating the signature in Python.\n\n| Field | Value |\n|-|-|\n| Private Key | xQnTJVeQLmw1/Mg2YimEViSpw/SdJcgNXZ5kQkAXNPU= |\n| Public Key | jPItx4TLjcnSUnmnXQQyAKL4eJj3+oWNNMmmm2vATqk= |\n| API Key | rh-api-6148effc-c0b1-486c-8940-a1d099456be6 |\n| Method | POST |\n| Path | /api/v1/crypto/trading/orders/ |\n| Body | {\"client_order_id\":\"131de903-5a9c-4260-abc1-28d562a5dcf0\",\"side\":\"buy\",\"type\":\"market\",\"symbol\":\"BTC-USD\",\"market_order_config\":{\"asset_quantity\":\"0.1\"}} |\n| Timestamp | 1698708981 |\n| __API Signature Header__ | __q/nEtxp/P2Or3hph3KejBqnw5o9qeuQ+hYRnB56FaHbjDsNUY9KhB1asMxohDnzdVFSD7StaTqjSd9U9HvaRAw==__ |\n\n### Code Example\n\n#### Python\n```python\nimport nacl.signing\nimport base64\nimport time\n\n# Replace these with your base64-encoded keys\nprivate_key_base64 = \"xQnTJVeQLmw1/Mg2YimEViSpw/SdJcgNXZ5kQkAXNPU=\"\npublic_key_base64 = \"jPItx4TLjcnSUnmnXQQyAKL4eJj3+oWNNMmmm2vATqk=\"\n\napi_key = \"rh-api-6148effc-c0b1-486c-8940-a1d099456be6\"\n\n# Get the current Unix timestamp in seconds\n# You can get the current_timestamp with the following code:\n# current_timestamp = int(time.time())\n# This value is hardcoded for demonstration purposes to match the example in the documentation\ncurrent_timestamp = \"1698708981\"\n\npath = f\"/api/v1/crypto/trading/orders/\"\n\nmethod = \"POST\"\n\nbody = {\n \"client_order_id\": \"131de903-5a9c-4260-abc1-28d562a5dcf0\",\n \"side\": \"buy\",\n \"symbol\": \"BTC-USD\",\n \"type\": \"market\",\n \"market_order_config\": {\n \"asset_quantity\": \"0.1\"\n },\n}\n\n# Convert base64 strings to seed (for private key) and bytes (for public key)\nprivate_key_seed = base64.b64decode(private_key_base64)\npublic_key_bytes = base64.b64decode(public_key_base64)\n\n# Create private key (from seed) and public key (from bytes)\nprivate_key = nacl.signing.SigningKey(private_key_seed)\npublic_key = nacl.signing.VerifyKey(public_key_bytes)\n\n# Create the message to sign\nmessage = f\"{api_key}{current_timestamp}{path}{method}{body}\"\n\n# Sign the message\nsigned = private_key.sign(message.encode(\"utf-8\"))\n\nbase64_signature = base64.b64encode(signed.signature).decode(\"utf-8\")\nprint(base64_signature)\n\n# Verify the signature\npublic_key.verify(signed.message, signed.signature)\n\n\n```",- "name": "x-signature",- "in": "header"- },- "Timestamp": {- "type": "apiKey",- "description": "The \"`x-timestamp`\" header should contain the timestamp of the request.\n\n**To protect the security and integrity of your API interactions, timestamps are only valid for 30 seconds after they’re generated, and an expired timestamp will be rejected. Therefore, ensure that your requests are made promptly after generating the timestamp.**\n\nBelow is an example in Python on how to generate the timestamp. \n\n```python\nimport time\n\ncurrent_timestamp = int(time.time())\nprint(current_timestamp)\n```",- "name": "x-timestamp",- "in": "header"- }- }- },- "x-tagGroups": [- {- "name": "V2 Endpoints (with Fee Tiers)",- "tags": [- "V2 Account",- "V2 Market Data",- "V2 Trading"- ]- },- {- "name": "V1 Endpoints (without Fee Tiers)",- "tags": [- "Account",- "Market Data",- "Trading"- ]- }- ]-}\ No newline at end of filediff --git a/robinhood/robinhood-crypto-mcp/package.json b/robinhood/robinhood-crypto-mcp/package.jsondeleted file mode 100644index b4aad8da9..000000000--- a/robinhood/robinhood-crypto-mcp/package.json+++ /dev/null@@ -1,77 +0,0 @@-{- "name": "robinhood-crypto-mcp",- "mcpName": "io.github.nirholas/robinhood-crypto-mcp",- "version": "0.1.0",- "description": "Model Context Protocol servers for the official Robinhood Crypto Trading API: a read-only server (quotes, holdings, orders, account) and an explicitly opt-in trading server with hard spend caps and a confirm gate. Ed25519 request signing verified against Robinhood's own key material.",- "keywords": [- "mcp",- "model-context-protocol",- "robinhood",- "robinhood-crypto",- "crypto-trading-api",- "trading",- "ed25519",- "ai-agents",- "claude",- "cursor"- ],- "license": "SEE LICENSE IN LICENSE",- "author": "nirholas (https://x.com/nichxbt)",- "repository": {- "type": "git",- "url": "git+https://github.com/nirholas/robinhood-crypto-mcp.git"- },- "homepage": "https://github.com/nirholas/robinhood-crypto-mcp#readme",- "bugs": {- "url": "https://github.com/nirholas/robinhood-crypto-mcp/issues"- },- "type": "module",- "engines": {- "node": ">=20"- },- "bin": {- "robinhood-crypto-mcp": "./dist/data-server.js",- "robinhood-crypto-mcp-trading": "./dist/trading-server.js",- "robinhood-crypto-keygen": "./dist/keygen.js"- },- "main": "./dist/index.js",- "types": "./dist/index.d.ts",- "exports": {- ".": {- "types": "./dist/index.d.ts",- "import": "./dist/index.js"- },- "./data-server": "./dist/data-server.js",- "./trading-server": "./dist/trading-server.js",- "./package.json": "./package.json"- },- "files": [- "dist",- "server.json",- "README.md",- "LICENSE"- ],- "sideEffects": false,- "scripts": {- "build": "tsup",- "typecheck": "tsc --noEmit",- "dev:data": "tsx src/data-server.ts",- "dev:trading": "tsx src/trading-server.ts",- "keygen": "tsx src/keygen.ts",- "start": "node dist/data-server.js",- "test": "vitest run",- "test:live": "vitest run -c vitest.live.config.ts --testTimeout 120000",- "prepublishOnly": "npm run build && npm test"- },- "dependencies": {- "@modelcontextprotocol/sdk": "^1.29.0",- "zod": "^3.25.76"- },- "devDependencies": {- "@types/node": "^24.0.0",- "tsup": "^8.5.0",- "tsx": "^4.23.0",- "typescript": "^5.9.0",- "vitest": "^3.2.0"- }-}diff --git a/robinhood/robinhood-crypto-mcp/src/data-server.ts b/robinhood/robinhood-crypto-mcp/src/data-server.tsdeleted file mode 100644index af9b6d9c6..000000000--- a/robinhood/robinhood-crypto-mcp/src/data-server.ts+++ /dev/null@@ -1,44 +0,0 @@-#!/usr/bin/env node-/**- * Read-only MCP server for the Robinhood Crypto Trading API.- *- * Exposes quotes, holdings, account details, and order history. It registers- * no tool that can move money, so it is safe to attach to a general-purpose- * assistant. Order placement lives in `robinhood-crypto-mcp-trading`.- */--import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';-import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';-import { RobinhoodCryptoClient } from './shared/client.js';-import { loadCredentials } from './shared/config.js';-import { registerDataTools } from './register-data.js';-import { VERSION } from './version.js';-import { isMain } from './shared/is-main.js';--export function createDataServer(): McpServer {- const credentials = loadCredentials();- const client = new RobinhoodCryptoClient(credentials);-- const server = new McpServer({- name: 'robinhood-crypto-mcp',- version: VERSION,- });-- registerDataTools(server, client, credentials);- return server;-}--export async function main(): Promise<void> {- try {- const server = createDataServer();- await server.connect(new StdioServerTransport());- } catch (error) {- // stderr only: stdout is the MCP transport and must stay clean JSON-RPC.- console.error(`[robinhood-crypto-mcp] ${error instanceof Error ? error.message : error}`);- process.exit(1);- }-}--if (isMain(import.meta.url)) {- void main();-}diff --git a/robinhood/robinhood-crypto-mcp/src/index.ts b/robinhood/robinhood-crypto-mcp/src/index.tsdeleted file mode 100644index ac3fc260a..000000000--- a/robinhood/robinhood-crypto-mcp/src/index.ts+++ /dev/null@@ -1,38 +0,0 @@-/**- * Library entry point.- *- * The signed client is usable on its own, without MCP, for anyone who wants a- * correct Robinhood Crypto Trading API client in Node.- */--export { RobinhoodCryptoClient, RobinhoodApiError } from './shared/client.js';-export {- buildAuthHeaders,- buildSignatureMessage,- privateKeyFromBase64Seed,- publicKeyBase64,- publicKeyFromBase64,- currentTimestampSeconds,- InvalidPrivateKeyError,- TIMESTAMP_VALIDITY_SECONDS,-} from './shared/signer.js';-export {- loadCredentials,- configuredPublicKey,- MissingCredentialsError,- DEFAULT_BASE_URL,- type Credentials,- type ApiVersion,-} from './shared/config.js';-export { endpointsFor, requiresAccountNumber, type EndpointSet } from './shared/endpoints.js';-export {- loadTradingGuards,- assertOrderAllowed,- estimateNotionalUsd,- GuardViolationError,- TradingDisabledError,- type TradingGuards,-} from './shared/guards.js';-export { createDataServer } from './data-server.js';-export { createTradingServer } from './trading-server.js';-export { VERSION } from './version.js';diff --git a/robinhood/robinhood-crypto-mcp/src/keygen.ts b/robinhood/robinhood-crypto-mcp/src/keygen.tsdeleted file mode 100644index 5fdbda76a..000000000--- a/robinhood/robinhood-crypto-mcp/src/keygen.ts+++ /dev/null@@ -1,54 +0,0 @@-#!/usr/bin/env node-/**- * Generate an Ed25519 keypair in the exact format Robinhood expects.- *- * Enrollment is a two-sided exchange that trips people up: you generate the- * keypair locally, hand Robinhood the *public* key, and keep the *private*- * key. Robinhood then issues an API key. Getting the halves backwards, or- * pasting a 64-byte expanded key, is the most common cause of 401s.- */--import { generateKeyPairSync } from 'node:crypto';-import { isMain } from './shared/is-main.js';--export interface GeneratedKeypair {- privateKeyBase64: string;- publicKeyBase64: string;-}--/**- * Generate a keypair, returning both halves base64-encoded.- *- * The private key is emitted as the raw 32-byte seed (extracted from its- * PKCS#8 wrapper), which is the form Robinhood's API expects.- */-export function generateKeypair(): GeneratedKeypair {- const { privateKey, publicKey } = generateKeyPairSync('ed25519');-- const pkcs8 = privateKey.export({ format: 'der', type: 'pkcs8' });- const spki = publicKey.export({ format: 'der', type: 'spki' });-- // The raw 32-byte key is the tail of each DER document (RFC 8410).- return {- privateKeyBase64: pkcs8.subarray(pkcs8.length - 32).toString('base64'),- publicKeyBase64: spki.subarray(spki.length - 32).toString('base64'),- };-}--export function main(): void {- const { privateKeyBase64, publicKeyBase64 } = generateKeypair();-- // stdout stays parseable for scripting; guidance goes to stderr.- console.error('Robinhood Crypto API keypair\n');- console.error('1. Register the PUBLIC key at https://robinhood.com/account/crypto');- console.error(' (web classic only — not the mobile app, not the new web UI).');- console.error('2. Robinhood issues an API key. Set it as ROBINHOOD_CRYPTO_API_KEY.');- console.error('3. Set the PRIVATE key below as ROBINHOOD_CRYPTO_PRIVATE_KEY.');- console.error(' Treat it like a password: it authorizes trades. Never commit it.\n');-- console.log(JSON.stringify({ publicKeyBase64, privateKeyBase64 }, null, 2));-}--if (isMain(import.meta.url)) {- main();-}diff --git a/robinhood/robinhood-crypto-mcp/src/register-data.ts b/robinhood/robinhood-crypto-mcp/src/register-data.tsdeleted file mode 100644index 4124bd6ad..000000000--- a/robinhood/robinhood-crypto-mcp/src/register-data.ts+++ /dev/null@@ -1,248 +0,0 @@-/**- * Read-only tools. Registered on both servers — the trading server is a- * superset, so an agent never needs two connections to do useful work.- */--import { z } from 'zod';-import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';-import type { RobinhoodCryptoClient } from './shared/client.js';-import { endpointsFor, requiresAccountNumber } from './shared/endpoints.js';-import { configuredPublicKey, type Credentials } from './shared/config.js';-import { toolResult, toolError } from './shared/format.js';--const symbolSchema = z- .string()- .regex(/^[A-Za-z0-9]+-[A-Za-z0-9]+$/, 'Symbol must be a trading pair like BTC-USD.')- .transform((s) => s.toUpperCase());--export function registerDataTools(- server: McpServer,- client: RobinhoodCryptoClient,- credentials: Credentials,-): void {- const endpoints = endpointsFor(credentials.apiVersion);- const needsAccount = requiresAccountNumber(credentials.apiVersion);-- /**- * v2 requires an account_number on several endpoints. Resolve it once and- * reuse, so callers never have to supply it by hand.- */- let cachedAccountNumber: string | undefined;- async function accountNumber(): Promise<string | undefined> {- if (!needsAccount) return undefined;- if (cachedAccountNumber) return cachedAccountNumber;-- const accounts = await client.get<{ results?: Array<{ account_number?: string }> }>(- endpoints.accounts,- );- const resolved = accounts?.results?.[0]?.account_number;- if (!resolved) {- throw new Error(- 'Could not resolve an account_number from the v2 accounts endpoint, which v2 holdings and orders require.',- );- }- cachedAccountNumber = resolved;- return resolved;- }-- server.registerTool(- 'get_account',- {- title: 'Get account',- description:- 'Fetch the Robinhood crypto account: account number, status, and buying power. On API v2 this also includes fee-tier status. Use this to confirm credentials work and to check available buying power before sizing an order.',- inputSchema: {},- },- async () => {- try {- return toolResult(await client.get(endpoints.accounts));- } catch (error) {- return toolError(error);- }- },- );-- server.registerTool(- 'get_holdings',- {- title: 'Get holdings',- description:- 'List crypto holdings with total quantity and the quantity available for trading. Optionally filter to specific asset codes (the base asset, e.g. BTC, not the BTC-USD pair).',- inputSchema: {- asset_codes: z- .array(z.string().transform((s) => s.toUpperCase()))- .optional()- .describe('Filter to these asset codes, e.g. ["BTC", "ETH"]. Omit for all holdings.'),- },- },- async ({ asset_codes }) => {- try {- const { results, truncated } = await client.getAllPages(endpoints.holdings, {- query: {- ...(asset_codes?.length ? { asset_code: asset_codes } : {}),- ...(needsAccount ? { account_number: await accountNumber() } : {}),- },- });- return toolResult({ holdings: results, truncated });- } catch (error) {- return toolError(error);- }- },- );-- server.registerTool(- 'get_best_bid_ask',- {- title: 'Get best bid/ask',- description:- 'Current best bid and ask for one or more trading pairs. On API v1 the response includes the spread-inclusive prices actually used for execution (bid_inclusive_of_sell_spread / ask_inclusive_of_buy_spread) alongside the mid price. Use this to price an order before placing it.',- inputSchema: {- symbols: z- .array(symbolSchema)- .min(1)- .describe('Trading pairs to quote, e.g. ["BTC-USD", "ETH-USD"].'),- },- },- async ({ symbols }) => {- try {- return toolResult(await client.get(endpoints.bestBidAsk, { query: { symbol: symbols } }));- } catch (error) {- return toolError(error);- }- },- );-- server.registerTool(- 'get_estimated_price',- {- title: 'Get estimated price',- description:- 'Estimated execution price for a given quantity, which accounts for depth rather than quoting only the top of book. Use side "ask" when buying and "bid" when selling. On API v2 the response also carries fee estimates.',- inputSchema: {- symbol: symbolSchema.describe('Trading pair, e.g. BTC-USD.'),- side: z- .enum(['bid', 'ask', 'both'])- .describe('Use "ask" to estimate a buy, "bid" to estimate a sell.'),- quantities: z- .array(z.string())- .min(1)- .describe('Asset quantities to price, as decimal strings, e.g. ["0.1", "1.0"].'),- },- },- async ({ symbol, side, quantities }) => {- try {- return toolResult(- await client.get(endpoints.estimatedPrice, {- query: { symbol, side, quantity: quantities.join(',') },- }),- );- } catch (error) {- return toolError(error);- }- },- );-- server.registerTool(- 'get_trading_pairs',- {- title: 'Get trading pairs',- description:- 'List supported trading pairs with their minimum and maximum order sizes and price/quantity increments. Check these increments before placing an order: a quantity with too many decimals is rejected.',- inputSchema: {- symbols: z- .array(symbolSchema)- .optional()- .describe('Filter to these pairs. Omit to list every supported pair.'),- },- },- async ({ symbols }) => {- try {- const { results, truncated } = await client.getAllPages(endpoints.tradingPairs, {- query: symbols?.length ? { symbol: symbols } : {},- });- return toolResult({ trading_pairs: results, truncated });- } catch (error) {- return toolError(error);- }- },- );-- server.registerTool(- 'get_orders',- {- title: 'List orders',- description:- 'List orders, newest first, with optional filters by symbol, side, type, state, and creation/update time. Use this to review order history or to poll an order until it fills.',- inputSchema: {- symbol: symbolSchema.optional().describe('Filter to one trading pair.'),- side: z.enum(['buy', 'sell']).optional(),- type: z.enum(['market', 'limit', 'stop_loss', 'stop_limit']).optional(),- state: z- .enum(['open', 'canceled', 'partially_filled', 'filled', 'failed'])- .optional()- .describe('Order state. Note API v2 reports "pending" in place of "partially_filled".'),- created_at_start: z.string().optional().describe('ISO 8601 timestamp lower bound.'),- created_at_end: z.string().optional().describe('ISO 8601 timestamp upper bound.'),- limit: z.number().int().positive().max(200).optional().describe('Max results per page.'),- },- },- async (args) => {- try {- const { results, truncated } = await client.getAllPages(endpoints.orders, {- query: {- ...Object.fromEntries(Object.entries(args).filter(([, v]) => v !== undefined)),- ...(needsAccount ? { account_number: await accountNumber() } : {}),- },- });- return toolResult({ orders: results, truncated });- } catch (error) {- return toolError(error);- }- },- );-- server.registerTool(- 'get_order',- {- title: 'Get order',- description:- 'Fetch a single order by its Robinhood order id, including its executions (fill price and quantity). Use this after placing an order to confirm the fill.',- inputSchema: {- order_id: z.string().min(1).describe('The order id returned when the order was placed.'),- },- },- async ({ order_id }) => {- try {- return toolResult(- await client.get(endpoints.order(order_id), {- query: needsAccount ? { account_number: await accountNumber() } : {},- }),- );- } catch (error) {- return toolError(error);- }- },- );-- server.registerTool(- 'get_connection_info',- {- title: 'Get connection info',- description:- 'Report how this server is configured — API version, base URL, and the public key derived from the configured private key — without revealing any secret. Use this first when authentication fails: if the public key shown here does not match the one registered with Robinhood, the wrong private key is configured.',- inputSchema: {},- },- async () => {- try {- return toolResult({- api_version: credentials.apiVersion,- base_url: credentials.baseUrl,- derived_public_key: configuredPublicKey(credentials),- note: 'Compare derived_public_key against the public key registered at https://robinhood.com/account/crypto. The API key and private key are never returned.',- });- } catch (error) {- return toolError(error);- }- },- );-}diff --git a/robinhood/robinhood-crypto-mcp/src/register-trading.ts b/robinhood/robinhood-crypto-mcp/src/register-trading.tsdeleted file mode 100644index ca8267082..000000000--- a/robinhood/robinhood-crypto-mcp/src/register-trading.ts+++ /dev/null@@ -1,283 +0,0 @@-/**- * Order placement and cancellation.- *- * Every order here is real money against a real brokerage account — Robinhood- * publishes no sandbox. Two things stand between a model and a live order:- * the operator's `ROBINHOOD_CRYPTO_ENABLE_TRADING=1` opt-in, and a per-call- * `confirm` flag that defaults to a priced preview instead of execution.- */--import { randomUUID } from 'node:crypto';-import { z } from 'zod';-import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';-import type { RobinhoodCryptoClient } from './shared/client.js';-import { endpointsFor, requiresAccountNumber } from './shared/endpoints.js';-import type { Credentials } from './shared/config.js';-import { assertOrderAllowed, estimateNotionalUsd, type TradingGuards } from './shared/guards.js';-import { toolResult, toolError } from './shared/format.js';--const symbolSchema = z- .string()- .regex(/^[A-Za-z0-9]+-[A-Za-z0-9]+$/, 'Symbol must be a trading pair like BTC-USD.')- .transform((s) => s.toUpperCase());--const decimalString = z- .string()- .regex(/^\d+(\.\d+)?$/, 'Must be a positive decimal string, e.g. "0.001".');--export function registerTradingTools(- server: McpServer,- client: RobinhoodCryptoClient,- credentials: Credentials,- guards: TradingGuards,-): void {- const endpoints = endpointsFor(credentials.apiVersion);- const needsAccount = requiresAccountNumber(credentials.apiVersion);-- let cachedAccountNumber: string | undefined;- async function accountNumber(): Promise<string | undefined> {- if (!needsAccount) return undefined;- if (cachedAccountNumber) return cachedAccountNumber;- const accounts = await client.get<{ results?: Array<{ account_number?: string }> }>(- endpoints.accounts,- );- const resolved = accounts?.results?.[0]?.account_number;- if (!resolved) throw new Error('Could not resolve account_number, which API v2 requires.');- cachedAccountNumber = resolved;- return resolved;- }-- /** Best available reference price, used to size market orders for the cap. */- async function referencePrice(symbol: string, side: 'buy' | 'sell'): Promise<number | undefined> {- try {- const quote = await client.get<{ results?: Array<Record<string, unknown>> }>(- endpoints.bestBidAsk,- { query: { symbol: [symbol] } },- );- const row = quote?.results?.[0];- if (!row) return undefined;-- // Field names differ between v1 and v2; try the documented keys in order- // and fall back to the generic ones rather than assuming one shape.- const candidates =- side === 'buy'- ? ['ask_inclusive_of_buy_spread', 'ask', 'price']- : ['bid_inclusive_of_sell_spread', 'bid', 'price'];-- for (const key of candidates) {- const value = Number(row[key]);- if (Number.isFinite(value) && value > 0) return value;- }- return undefined;- } catch {- // A missing quote must not silently disable the spend cap; the caller- // treats `undefined` as "notional unknown" and refuses to proceed.- return undefined;- }- }-- server.registerTool(- 'place_order',- {- title: 'Place order',- description:- 'Place a crypto order. THIS SPENDS REAL MONEY — Robinhood has no sandbox. ' +- 'Defaults to a preview: without confirm=true it returns the exact request that would be sent, ' +- 'a priced estimate, and the guards it was checked against, and places nothing. ' +- 'Call once to preview, show the user the numbers, then call again with confirm=true. ' +- `Orders are capped at $${guards.maxOrderUsd} by ROBINHOOD_CRYPTO_MAX_ORDER_USD.`,- inputSchema: {- symbol: symbolSchema.describe('Trading pair, e.g. BTC-USD.'),- side: z.enum(['buy', 'sell']),- type: z.enum(['market', 'limit', 'stop_loss', 'stop_limit']),- asset_quantity: decimalString- .optional()- .describe('Size in the base asset, e.g. "0.001" BTC. Mutually exclusive with quote_amount.'),- quote_amount: decimalString- .optional()- .describe(- 'Size in the quote currency, e.g. "25.00" USD. Not supported for market orders.',- ),- limit_price: decimalString- .optional()- .describe('Required for limit and stop_limit orders.'),- stop_price: decimalString- .optional()- .describe('Required for stop_loss and stop_limit orders.'),- time_in_force: z- .enum(['gtc', 'day'])- .optional()- .default('gtc')- .describe('Applies to limit, stop_loss, and stop_limit orders.'),- confirm: z- .boolean()- .optional()- .default(false)- .describe('Must be true to actually place the order. False returns a preview.'),- client_order_id: z- .string()- .uuid()- .optional()- .describe(- 'Idempotency key. Generated if omitted. Reuse the same value when retrying one logical order.',- ),- },- },- async (args) => {- try {- const {- symbol,- side,- type,- asset_quantity,- quote_amount,- limit_price,- stop_price,- time_in_force,- confirm,- } = args;-- if (!asset_quantity && !quote_amount) {- throw new Error('Specify either asset_quantity or quote_amount.');- }- if (asset_quantity && quote_amount) {- throw new Error('Specify only one of asset_quantity or quote_amount, not both.');- }- if (type === 'market' && quote_amount) {- throw new Error(- 'Market orders must be sized with asset_quantity; Robinhood does not accept quote_amount for them.',- );- }- if ((type === 'limit' || type === 'stop_limit') && !limit_price) {- throw new Error(`A ${type} order requires limit_price.`);- }- if ((type === 'stop_loss' || type === 'stop_limit') && !stop_price) {- throw new Error(`A ${type} order requires stop_price.`);- }-- // Price the order so the spend cap is enforceable even for market orders.- const reference =- limit_price === undefined && asset_quantity !== undefined- ? await referencePrice(symbol, side)- : undefined;-- const notionalUsd = estimateNotionalUsd({- quoteAmount: quote_amount,- assetQuantity: asset_quantity,- limitPrice: limit_price,- referencePrice: reference,- });-- assertOrderAllowed({ symbol, side, notionalUsd }, guards);-- const config = buildOrderConfig({- type,- asset_quantity,- quote_amount,- limit_price,- stop_price,- time_in_force,- });-- const body = {- client_order_id: args.client_order_id ?? randomUUID(),- symbol,- side,- type,- ...config,- };-- if (!confirm) {- return toolResult({- preview: true,- placed: false,- message:- 'Nothing was placed. Review these numbers with the user, then call again with confirm=true.',- request: { method: 'POST', path: endpoints.orders, body },- estimate: {- notional_usd: notionalUsd,- reference_price: reference ?? null,- priced_from:- limit_price !== undefined- ? 'limit_price'- : quote_amount !== undefined- ? 'quote_amount'- : reference !== undefined- ? 'live best bid/ask'- : 'unavailable',- },- guards: {- max_order_usd: guards.maxOrderUsd,- symbol_allowlist: guards.symbolAllowlist,- buy_only: guards.buyOnly,- },- });- }-- const result = await client.post(endpoints.orders, {- body,- query: needsAccount ? { account_number: await accountNumber() } : {},- // Never retry a write: a retry after an ambiguous failure can double-fill.- maxRetries: 0,- });-- return toolResult({- placed: true,- estimated_notional_usd: notionalUsd,- order: result,- });- } catch (error) {- return toolError(error);- }- },- );-- server.registerTool(- 'cancel_order',- {- title: 'Cancel order',- description:- 'Request cancellation of an open order by id. Cancellation is best-effort: an order that has already filled cannot be canceled. Confirm the resulting state with get_order.',- inputSchema: {- order_id: z.string().min(1).describe('The order id to cancel.'),- },- },- async ({ order_id }) => {- try {- const result = await client.post(endpoints.cancelOrder(order_id), { maxRetries: 0 });- return toolResult({- cancel_requested: true,- order_id,- response: result ?? null,- note: 'Cancellation is best-effort. Call get_order to confirm the final state.',- });- } catch (error) {- return toolError(error);- }- },- );-}--/** Build the `*_order_config` object matching the order type. */-function buildOrderConfig(params: {- type: 'market' | 'limit' | 'stop_loss' | 'stop_limit';- asset_quantity?: string | undefined;- quote_amount?: string | undefined;- limit_price?: string | undefined;- stop_price?: string | undefined;- time_in_force?: 'gtc' | 'day' | undefined;-}): Record<string, unknown> {- const { type, asset_quantity, quote_amount, limit_price, stop_price, time_in_force } = params;- const size = asset_quantity !== undefined ? { asset_quantity } : { quote_amount };-- switch (type) {- case 'market':- return { market_order_config: { asset_quantity } };- case 'limit':- return { limit_order_config: { ...size, limit_price, time_in_force } };- case 'stop_loss':- return { stop_loss_order_config: { ...size, stop_price, time_in_force } };- case 'stop_limit':- return { stop_limit_order_config: { ...size, limit_price, stop_price, time_in_force } };- }-}diff --git a/robinhood/robinhood-crypto-mcp/src/shared/client.ts b/robinhood/robinhood-crypto-mcp/src/shared/client.tsdeleted file mode 100644index 968888ffd..000000000--- a/robinhood/robinhood-crypto-mcp/src/shared/client.ts+++ /dev/null@@ -1,297 +0,0 @@-/**- * HTTP client for the Robinhood Crypto Trading API.- *- * Responsibilities: sign every request, respect the documented rate limit,- * translate error envelopes into actionable messages, and follow cursors.- *- * Responses are returned as-is. Robinhood's published schemas and the two- * community clients disagree on several field names, so this client does not- * remap fields — a wrong mapping silently corrupts data, while a pass-through- * stays correct even when the upstream shape changes.- */--import { buildAuthHeaders } from './signer.js';-import { redact, RATE_LIMIT_BURST, RATE_LIMIT_PER_MINUTE, type Credentials } from './config.js';--export class RobinhoodApiError extends Error {- readonly status: number;- readonly errorType: string | undefined;- readonly details: Array<{ detail?: string; attr?: string | null }>;-- constructor(- message: string,- status: number,- errorType?: string,- details: Array<{ detail?: string; attr?: string | null }> = [],- ) {- super(message);- this.name = 'RobinhoodApiError';- this.status = status;- this.errorType = errorType;- this.details = details;- }-}--/**- * Token bucket matching Robinhood's documented 100 req/min with 300 burst.- * Robinhood states limits are per-endpoint and vary, so this is a floor that- * keeps a well-behaved client under the global ceiling, not an exact mirror.- */-class TokenBucket {- private tokens: number;- private lastRefill: number;-- constructor(- private readonly capacity: number,- private readonly refillPerMs: number,- ) {- this.tokens = capacity;- this.lastRefill = Date.now();- }-- /** Resolve once a token is available. */- async take(): Promise<void> {- for (;;) {- this.refill();- if (this.tokens >= 1) {- this.tokens -= 1;- return;- }- const waitMs = Math.ceil((1 - this.tokens) / this.refillPerMs);- await sleep(Math.min(Math.max(waitMs, 10), 5_000));- }- }-- private refill(): void {- const now = Date.now();- this.tokens = Math.min(this.capacity, this.tokens + (now - this.lastRefill) * this.refillPerMs);- this.lastRefill = now;- }-}--const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));--export interface RequestOptions {- /** Query parameters. Array values repeat the key, which is what Robinhood expects. */- query?: Record<string, string | string[] | number | undefined>;- /** JSON body for writes. Serialized once, then both signed and sent. */- body?: unknown;- /** Retries for transient failures (429 / 5xx). */- maxRetries?: number;-}--export class RobinhoodCryptoClient {- private readonly bucket = new TokenBucket(RATE_LIMIT_BURST, RATE_LIMIT_PER_MINUTE / 60_000);-- constructor(private readonly credentials: Credentials) {}-- get apiVersion(): string {- return this.credentials.apiVersion;- }-- async get<T = unknown>(path: string, options: RequestOptions = {}): Promise<T> {- return this.request<T>('GET', path, options);- }-- async post<T = unknown>(path: string, options: RequestOptions = {}): Promise<T> {- return this.request<T>('POST', path, options);- }-- async request<T = unknown>(- method: 'GET' | 'POST',- path: string,- options: RequestOptions = {},- ): Promise<T> {- const pathWithQuery = path + buildQueryString(options.query);-- // Serialize exactly once: the signature covers these precise bytes.- const body = options.body === undefined ? undefined : JSON.stringify(options.body);- const maxRetries = options.maxRetries ?? 2;-- let lastError: unknown;- for (let attempt = 0; attempt <= maxRetries; attempt++) {- await this.bucket.take();-- // Re-sign per attempt: signatures expire 30s after their timestamp.- const headers = buildAuthHeaders({- apiKey: this.credentials.apiKey,- privateKey: this.credentials.privateKey,- path: pathWithQuery,- method,- body,- });-- let response: Response;- try {- response = await fetch(`${this.credentials.baseUrl}${pathWithQuery}`, {- method,- headers: {- ...headers,- 'Content-Type': 'application/json; charset=utf-8',- Accept: 'application/json',- },- body,- signal: AbortSignal.timeout(30_000),- });- } catch (error) {- lastError = error;- if (attempt < maxRetries) {- await sleep(backoffMs(attempt));- continue;- }- throw new Error(- `Request to ${method} ${pathWithQuery} failed: ${redact(String(error), this.credentials)}`,- );- }-- if (response.ok) {- const text = await response.text();- if (!text) return undefined as T;- try {- return JSON.parse(text) as T;- } catch {- throw new Error(`Robinhood returned a non-JSON body for ${method} ${pathWithQuery}.`);- }- }-- const retryable = response.status === 429 || response.status >= 500;- if (retryable && attempt < maxRetries) {- const retryAfter = Number(response.headers.get('retry-after'));- await sleep(- Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter * 1_000 : backoffMs(attempt),- );- continue;- }-- throw await this.toApiError(response, method, pathWithQuery);- }-- throw lastError instanceof Error ? lastError : new Error(String(lastError));- }-- /**- * Walk a cursor-paginated collection and return every result.- *- * @param maxPages - Safety bound so a runaway cursor cannot spin forever.- */- async getAllPages<T = unknown>(- path: string,- options: RequestOptions = {},- maxPages = 20,- ): Promise<{ results: T[]; truncated: boolean }> {- const results: T[] = [];- let cursor: string | undefined;-- for (let page = 0; page < maxPages; page++) {- const query = { ...options.query, ...(cursor ? { cursor } : {}) };- const body = await this.get<{ results?: T[]; next?: string | null }>(path, {- ...options,- query,- });-- if (Array.isArray(body?.results)) results.push(...body.results);- else if (body !== undefined && !Array.isArray(body?.results)) {- // A non-paginated endpoint: return the single payload verbatim.- return { results: [body as T], truncated: false };- }-- const next = body?.next;- if (!next) return { results, truncated: false };-- const nextCursor = extractCursor(next);- if (!nextCursor || nextCursor === cursor) return { results, truncated: false };- cursor = nextCursor;- }-- return { results, truncated: true };- }-- private async toApiError(- response: Response,- method: string,- path: string,- ): Promise<RobinhoodApiError> {- const text = await response.text().catch(() => '');- let errorType: string | undefined;- let details: Array<{ detail?: string; attr?: string | null }> = [];-- try {- const parsed = JSON.parse(text) as {- type?: string;- errors?: Array<{ detail?: string; attr?: string | null }>;- };- errorType = parsed.type;- if (Array.isArray(parsed.errors)) details = parsed.errors;- } catch {- // Non-JSON error body: fall through to the status-based message.- }-- const detailText = details- .map((entry) => (entry.attr ? `${entry.attr}: ${entry.detail}` : entry.detail))- .filter(Boolean)- .join('; ');-- const message = [- `Robinhood API ${response.status} on ${method} ${path}`,- detailText || redact(text.slice(0, 400), this.credentials) || response.statusText,- guidanceFor(response.status),- ]- .filter(Boolean)- .join(' — ');-- return new RobinhoodApiError(- redact(message, this.credentials),- response.status,- errorType,- details,- );- }-}--function backoffMs(attempt: number): number {- return Math.min(1_000 * 2 ** attempt, 8_000);-}--/**- * Actionable guidance for the statuses that actually trip people up, rather- * than a bare status code.- */-function guidanceFor(status: number): string {- switch (status) {- case 401:- return 'Check ROBINHOOD_CRYPTO_API_KEY and that the private key matches the public key registered with Robinhood. Also verify your system clock: signatures expire 30 seconds after their timestamp.';- case 403:- return 'The API credential lacks the required permission. Re-check the scopes selected when the key was created (read vs. order placement), and any IP allowlist on the key.';- case 404:- return 'Check the path, including its trailing slash — Robinhood requires it.';- case 429:- return 'Rate limited (documented: 100 requests/minute, 300 burst).';- default:- return status >= 500 ? 'Robinhood-side error; retry shortly.' : '';- }-}--function buildQueryString(- query: Record<string, string | string[] | number | undefined> | undefined,-): string {- if (!query) return '';- const parts: string[] = [];- for (const [key, value] of Object.entries(query)) {- if (value === undefined) continue;- // Repeat the key for array values (?symbol=A&symbol=B) per the API docs.- for (const item of Array.isArray(value) ? value : [value]) {- if (item === undefined) continue;- parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(item))}`);- }- }- return parts.length ? `?${parts.join('&')}` : '';-}--/** Robinhood returns `next` as an absolute URL; we need just the cursor. */-function extractCursor(nextUrl: string): string | undefined {- try {- return new URL(nextUrl).searchParams.get('cursor') ?? undefined;- } catch {- return undefined;- }-}diff --git a/robinhood/robinhood-crypto-mcp/src/shared/config.ts b/robinhood/robinhood-crypto-mcp/src/shared/config.tsdeleted file mode 100644index 2d1c02c14..000000000--- a/robinhood/robinhood-crypto-mcp/src/shared/config.ts+++ /dev/null@@ -1,95 +0,0 @@-/**- * Environment configuration for both servers.- *- * Credentials are read from the environment only — never from arguments, and- * never echoed back through a tool result.- */--import { privateKeyFromBase64Seed, publicKeyBase64 } from './signer.js';-import type { KeyObject } from 'node:crypto';--export const DEFAULT_BASE_URL = 'https://trading.robinhood.com';--/** Robinhood documents 100 requests/minute per account, bursting to 300. */-export const RATE_LIMIT_PER_MINUTE = 100;-export const RATE_LIMIT_BURST = 300;--export type ApiVersion = 'v1' | 'v2';--export interface Credentials {- apiKey: string;- privateKey: KeyObject;- baseUrl: string;- apiVersion: ApiVersion;-}--export class MissingCredentialsError extends Error {- constructor(message: string) {- super(message);- this.name = 'MissingCredentialsError';- }-}--const CREDENTIAL_HELP = [- 'Set ROBINHOOD_CRYPTO_API_KEY and ROBINHOOD_CRYPTO_PRIVATE_KEY.',- 'Create a credential at https://robinhood.com/account/crypto (web classic only):',- 'generate an Ed25519 keypair locally, register the PUBLIC key with Robinhood,',- 'and keep the base64 private key (a 32-byte seed) for this server.',- 'Run `npx robinhood-crypto-mcp keygen` to generate a conforming keypair.',-].join(' ');--/**- * Load credentials from the environment.- *- * @throws {MissingCredentialsError} If either credential is absent.- */-export function loadCredentials(env: NodeJS.ProcessEnv = process.env): Credentials {- const apiKey = env.ROBINHOOD_CRYPTO_API_KEY?.trim();- const privateKeyRaw = env.ROBINHOOD_CRYPTO_PRIVATE_KEY?.trim();-- if (!apiKey || !privateKeyRaw) {- const missing = [- !apiKey && 'ROBINHOOD_CRYPTO_API_KEY',- !privateKeyRaw && 'ROBINHOOD_CRYPTO_PRIVATE_KEY',- ]- .filter(Boolean)- .join(' and ');- throw new MissingCredentialsError(`Missing ${missing}. ${CREDENTIAL_HELP}`);- }-- const apiVersion = parseApiVersion(env.ROBINHOOD_CRYPTO_API_VERSION);-- return {- apiKey,- privateKey: privateKeyFromBase64Seed(privateKeyRaw),- baseUrl: (env.ROBINHOOD_CRYPTO_BASE_URL?.trim() || DEFAULT_BASE_URL).replace(/\/+$/, ''),- apiVersion,- };-}--function parseApiVersion(raw: string | undefined): ApiVersion {- const value = raw?.trim().toLowerCase();- if (!value) return 'v1';- if (value === 'v1' || value === 'v2') return value;- throw new MissingCredentialsError(- `ROBINHOOD_CRYPTO_API_VERSION must be "v1" or "v2", got "${raw}".`,- );-}--/**- * The public key matching the configured private key, for verifying that the- * key registered with Robinhood is the one this server holds.- */-export function configuredPublicKey(credentials: Credentials): string {- return publicKeyBase64(credentials.privateKey);-}--/**- * Redact credential material from any string before it reaches a log line or- * a tool result. Error paths stringify request context, and that context can- * carry the API key.- */-export function redact(text: string, credentials?: Pick<Credentials, 'apiKey'>): string {- if (!credentials?.apiKey) return text;- return text.split(credentials.apiKey).join('[redacted-api-key]');-}diff --git a/robinhood/robinhood-crypto-mcp/src/shared/endpoints.ts b/robinhood/robinhood-crypto-mcp/src/shared/endpoints.tsdeleted file mode 100644index 0fbe7ddb9..000000000--- a/robinhood/robinhood-crypto-mcp/src/shared/endpoints.ts+++ /dev/null@@ -1,55 +0,0 @@-/**- * Path resolution for the two documented API versions.- *- * v2 adds fee-tier information to orders and accounts. It is not a drop-in- * replacement: several v2 endpoints require an `account_number` query- * parameter, and `estimated_price` moves from `/marketdata/` to `/trading/`.- * Those asymmetries are in Robinhood's own spec, not transcription errors.- *- * @see docs/openapi-extracted.json - the upstream OpenAPI document- */--import type { ApiVersion } from './config.js';--export interface EndpointSet {- accounts: string;- tradingPairs: string;- holdings: string;- orders: string;- order: (orderId: string) => string;- cancelOrder: (orderId: string) => string;- bestBidAsk: string;- estimatedPrice: string;-}--const V1: EndpointSet = {- accounts: '/api/v1/crypto/trading/accounts/',- tradingPairs: '/api/v1/crypto/trading/trading_pairs/',- holdings: '/api/v1/crypto/trading/holdings/',- orders: '/api/v1/crypto/trading/orders/',- order: (id) => `/api/v1/crypto/trading/orders/${encodeURIComponent(id)}/`,- cancelOrder: (id) => `/api/v1/crypto/trading/orders/${encodeURIComponent(id)}/cancel/`,- bestBidAsk: '/api/v1/crypto/marketdata/best_bid_ask/',- estimatedPrice: '/api/v1/crypto/marketdata/estimated_price/',-};--const V2: EndpointSet = {- accounts: '/api/v2/crypto/trading/accounts/',- tradingPairs: '/api/v2/crypto/trading/trading_pairs/',- holdings: '/api/v2/crypto/trading/holdings/',- orders: '/api/v2/crypto/trading/orders/',- order: (id) => `/api/v2/crypto/trading/orders/${encodeURIComponent(id)}/`,- cancelOrder: (id) => `/api/v2/crypto/trading/orders/${encodeURIComponent(id)}/cancel/`,- bestBidAsk: '/api/v2/crypto/marketdata/best_bid_ask/',- // Not a typo: v2 serves estimated price under /trading/, unlike v1.- estimatedPrice: '/api/v2/crypto/trading/estimated_price/',-};--export function endpointsFor(version: ApiVersion): EndpointSet {- return version === 'v2' ? V2 : V1;-}--/** Endpoints where v2 requires an `account_number` query parameter. */-export function requiresAccountNumber(version: ApiVersion): boolean {- return version === 'v2';-}diff --git a/robinhood/robinhood-crypto-mcp/src/shared/format.ts b/robinhood/robinhood-crypto-mcp/src/shared/format.tsdeleted file mode 100644index 61bcb893f..000000000--- a/robinhood/robinhood-crypto-mcp/src/shared/format.ts+++ /dev/null@@ -1,37 +0,0 @@-/** Shared tool-result helpers. */--import { RobinhoodApiError } from './client.js';-import { GuardViolationError } from './guards.js';--export interface ToolResponse {- content: Array<{ type: 'text'; text: string }>;- isError?: boolean;- [key: string]: unknown;-}--/** Serialize a successful tool result. */-export function toolResult(payload: unknown): ToolResponse {- return {- content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }],- };-}--/**- * Serialize a failure so the model can act on it.- *- * Guard violations and API errors carry remediation text already; anything- * else is surfaced verbatim rather than flattened to "an error occurred".- */-export function toolError(error: unknown): ToolResponse {- const message =- error instanceof RobinhoodApiError || error instanceof GuardViolationError- ? error.message- : error instanceof Error- ? error.message- : String(error);-- return {- content: [{ type: 'text', text: message }],- isError: true,- };-}diff --git a/robinhood/robinhood-crypto-mcp/src/shared/guards.ts b/robinhood/robinhood-crypto-mcp/src/shared/guards.tsdeleted file mode 100644index a82b28397..000000000--- a/robinhood/robinhood-crypto-mcp/src/shared/guards.ts+++ /dev/null@@ -1,154 +0,0 @@-/**- * Safety guards for the trading server.- *- * Robinhood has no sandbox: every order this server can place is real money in- * a real brokerage account. The guards below are deliberately strict and fail- * closed. They are enforced in the server, not in the prompt, because an- * instruction in a tool description is a suggestion and a thrown error is not.- */--export class TradingDisabledError extends Error {- constructor(message: string) {- super(message);- this.name = 'TradingDisabledError';- }-}--export class GuardViolationError extends Error {- constructor(message: string) {- super(message);- this.name = 'GuardViolationError';- }-}--export interface TradingGuards {- /** Hard ceiling on the notional value of any single order, in USD. */- maxOrderUsd: number;- /** When set, only these symbols may be traded. */- symbolAllowlist: string[] | null;- /** When true, sell orders are rejected. */- buyOnly: boolean;-}--export const DEFAULT_MAX_ORDER_USD = 100;--/**- * Load guards, and assert the operator explicitly opted into trading.- *- * @throws {TradingDisabledError} If `ROBINHOOD_CRYPTO_ENABLE_TRADING` is not `1`.- */-export function loadTradingGuards(env: NodeJS.ProcessEnv = process.env): TradingGuards {- if (env.ROBINHOOD_CRYPTO_ENABLE_TRADING?.trim() !== '1') {- throw new TradingDisabledError(- 'Trading is disabled. This server places real orders with real money and has no sandbox. ' +- 'Set ROBINHOOD_CRYPTO_ENABLE_TRADING=1 to enable it, and set ROBINHOOD_CRYPTO_MAX_ORDER_USD ' +- 'to a ceiling you are comfortable losing. Read-only tools are available without this flag ' +- 'via the `robinhood-crypto-mcp` data server.',- );- }-- const maxOrderUsd = parsePositiveNumber(- env.ROBINHOOD_CRYPTO_MAX_ORDER_USD,- DEFAULT_MAX_ORDER_USD,- 'ROBINHOOD_CRYPTO_MAX_ORDER_USD',- );-- const allowlistRaw = env.ROBINHOOD_CRYPTO_SYMBOL_ALLOWLIST?.trim();- const symbolAllowlist = allowlistRaw- ? allowlistRaw- .split(',')- .map((s) => s.trim().toUpperCase())- .filter(Boolean)- : null;-- return {- maxOrderUsd,- symbolAllowlist,- buyOnly: env.ROBINHOOD_CRYPTO_BUY_ONLY?.trim() === '1',- };-}--function parsePositiveNumber(raw: string | undefined, fallback: number, name: string): number {- if (raw === undefined || raw.trim() === '') return fallback;- const value = Number(raw);- if (!Number.isFinite(value) || value <= 0) {- throw new GuardViolationError(`${name} must be a positive number, got "${raw}".`);- }- return value;-}--export interface OrderIntent {- symbol: string;- side: 'buy' | 'sell';- /** Notional USD value, when it can be determined before submitting. */- notionalUsd: number | null;-}--/**- * Check an order against the configured guards.- *- * @throws {GuardViolationError} On the first violated guard.- */-export function assertOrderAllowed(intent: OrderIntent, guards: TradingGuards): void {- const symbol = intent.symbol.toUpperCase();-- if (guards.symbolAllowlist && !guards.symbolAllowlist.includes(symbol)) {- throw new GuardViolationError(- `Symbol ${symbol} is not in ROBINHOOD_CRYPTO_SYMBOL_ALLOWLIST (${guards.symbolAllowlist.join(', ')}).`,- );- }-- if (guards.buyOnly && intent.side === 'sell') {- throw new GuardViolationError('Sell orders are blocked by ROBINHOOD_CRYPTO_BUY_ONLY=1.');- }-- if (intent.notionalUsd === null) {- throw new GuardViolationError(- `Cannot determine the USD value of this ${symbol} order, so the ` +- `ROBINHOOD_CRYPTO_MAX_ORDER_USD ceiling ($${guards.maxOrderUsd}) cannot be enforced. ` +- 'Specify quote_amount, or use a limit order where quantity x limit_price is known.',- );- }-- if (intent.notionalUsd > guards.maxOrderUsd) {- throw new GuardViolationError(- `Order value $${intent.notionalUsd.toFixed(2)} exceeds the ` +- `ROBINHOOD_CRYPTO_MAX_ORDER_USD ceiling of $${guards.maxOrderUsd.toFixed(2)}. ` +- 'Reduce the size, or raise the ceiling deliberately.',- );- }-}--/**- * Estimate an order's USD notional from its own parameters.- *- * Returns `null` when the value is not knowable up front — a market order sized- * in asset quantity has no price until it fills. Callers must treat `null` as- * "unenforceable", never as zero.- */-export function estimateNotionalUsd(params: {- quoteAmount?: string | undefined;- assetQuantity?: string | undefined;- limitPrice?: string | undefined;- referencePrice?: number | undefined;-}): number | null {- const { quoteAmount, assetQuantity, limitPrice, referencePrice } = params;-- if (quoteAmount !== undefined) {- const value = Number(quoteAmount);- return Number.isFinite(value) ? value : null;- }-- if (assetQuantity !== undefined) {- const quantity = Number(assetQuantity);- if (!Number.isFinite(quantity)) return null;-- // A limit price bounds a buy exactly; a reference quote is the best- // available estimate for a market order.- const price = limitPrice !== undefined ? Number(limitPrice) : referencePrice;- if (price === undefined || !Number.isFinite(price)) return null;- return quantity * price;- }-- return null;-}diff --git a/robinhood/robinhood-crypto-mcp/src/shared/is-main.ts b/robinhood/robinhood-crypto-mcp/src/shared/is-main.tsdeleted file mode 100644index 98ff3424d..000000000--- a/robinhood/robinhood-crypto-mcp/src/shared/is-main.ts+++ /dev/null@@ -1,18 +0,0 @@-import { realpathSync } from 'node:fs';-import { fileURLToPath } from 'node:url';--/**- * True when this module is the process entry point.- *- * Compares realpaths so a symlinked bin (how npx and global installs expose- * it) still matches.- */-export function isMain(moduleUrl: string): boolean {- const entry = process.argv[1];- if (!entry) return false;- try {- return realpathSync(fileURLToPath(moduleUrl)) === realpathSync(entry);- } catch {- return false;- }-}diff --git a/robinhood/robinhood-crypto-mcp/src/shared/signer.ts b/robinhood/robinhood-crypto-mcp/src/shared/signer.tsdeleted file mode 100644index b062ede34..000000000--- a/robinhood/robinhood-crypto-mcp/src/shared/signer.ts+++ /dev/null@@ -1,159 +0,0 @@-/**- * Ed25519 request signing for the Robinhood Crypto Trading API.- *- * Robinhood authenticates every request with three headers — `x-api-key`,- * `x-timestamp`, and `x-signature` — where the signature is a detached Ed25519- * signature over:- *- * message = api_key + timestamp + path + method + body- *- * concatenated with no separators. The private key Robinhood issues is a- * base64-encoded 32-byte Ed25519 *seed*, not an expanded 64-byte keypair and- * not PKCS#8 — mixing those up is the most common integration failure.- *- * @see https://docs.robinhood.com/crypto/trading/- */--import { createPrivateKey, createPublicKey, sign, type KeyObject } from 'node:crypto';--/**- * DER prefix that wraps a raw 32-byte Ed25519 seed into a PKCS#8 document,- * which is the only private-key form `node:crypto` accepts (RFC 8410 §7).- */-const PKCS8_ED25519_PREFIX = Buffer.from('302e020100300506032b657004220420', 'hex');--/** DER prefix wrapping a raw 32-byte Ed25519 public key into SPKI form. */-const SPKI_ED25519_PREFIX = Buffer.from('302a300506032b6570032100', 'hex');--const ED25519_SEED_BYTES = 32;--export class InvalidPrivateKeyError extends Error {- constructor(message: string) {- super(message);- this.name = 'InvalidPrivateKeyError';- }-}--/**- * Turn Robinhood's base64 private key into a Node key object.- *- * @param base64Seed - The base64 private key exactly as issued by Robinhood.- * @throws {InvalidPrivateKeyError} If the value does not decode to 32 bytes.- */-export function privateKeyFromBase64Seed(base64Seed: string): KeyObject {- const trimmed = base64Seed.trim();- let seed: Buffer;- try {- seed = Buffer.from(trimmed, 'base64');- } catch {- throw new InvalidPrivateKeyError('Private key is not valid base64.');- }-- if (seed.length !== ED25519_SEED_BYTES) {- // The 64-byte case is worth calling out by name: several Ed25519 libraries- // export seed‖publicKey and users paste that in expecting it to work.- const hint =- seed.length === 64- ? ' This looks like an expanded 64-byte keypair (seed‖publicKey); Robinhood issues the 32-byte seed, which is its first half.'- : '';- throw new InvalidPrivateKeyError(- `Private key must decode to ${ED25519_SEED_BYTES} bytes, got ${seed.length}.${hint}`,- );- }-- return createPrivateKey({- key: Buffer.concat([PKCS8_ED25519_PREFIX, seed]),- format: 'der',- type: 'pkcs8',- });-}--/**- * Derive the base64 public key for a private key, which is what you register- * with Robinhood when creating an API credential. Lets a caller confirm a- * stored private key still corresponds to the enrolled public key.- */-export function publicKeyBase64(privateKey: KeyObject): string {- const spki = createPublicKey(privateKey).export({ format: 'der', type: 'spki' });- return spki.subarray(spki.length - ED25519_SEED_BYTES).toString('base64');-}--/** Build a raw Ed25519 public key object from Robinhood's base64 form. */-export function publicKeyFromBase64(base64Key: string): KeyObject {- const raw = Buffer.from(base64Key.trim(), 'base64');- if (raw.length !== ED25519_SEED_BYTES) {- throw new InvalidPrivateKeyError(- `Public key must decode to ${ED25519_SEED_BYTES} bytes, got ${raw.length}.`,- );- }- return createPublicKey({- key: Buffer.concat([SPKI_ED25519_PREFIX, raw]),- format: 'der',- type: 'spki',- });-}--/**- * Build the exact byte string Robinhood signs.- *- * `path` must include the query string, and `body` must be the exact serialized- * JSON that goes on the wire — serialize once, sign that string, send that same- * string. Re-serializing between signing and sending changes key order or- * whitespace and yields a well-formed request with an invalid signature.- */-export function buildSignatureMessage(params: {- apiKey: string;- timestamp: number;- path: string;- method: string;- body?: string;-}): string {- const { apiKey, timestamp, path, method, body = '' } = params;- return `${apiKey}${timestamp}${path}${method.toUpperCase()}${body}`;-}--export interface AuthHeaders {- 'x-api-key': string;- 'x-signature': string;- 'x-timestamp': string;-}--/**- * Produce the three authentication headers for a request.- *- * @param timestamp - Unix time in **seconds**. Robinhood rejects timestamps- * older than 30 seconds, so this must be seconds, not `Date.now()`.- */-export function buildAuthHeaders(params: {- apiKey: string;- privateKey: KeyObject;- path: string;- method: string;- body?: string;- timestamp?: number;-}): AuthHeaders {- const timestamp = params.timestamp ?? currentTimestampSeconds();- const message = buildSignatureMessage({- apiKey: params.apiKey,- timestamp,- path: params.path,- method: params.method,- body: params.body,- });-- const signature = sign(null, Buffer.from(message, 'utf8'), params.privateKey);-- return {- 'x-api-key': params.apiKey,- 'x-signature': signature.toString('base64'),- 'x-timestamp': String(timestamp),- };-}--/** Unix timestamp in seconds, the unit Robinhood expects. */-export function currentTimestampSeconds(): number {- return Math.floor(Date.now() / 1000);-}--/** Robinhood rejects a signature whose timestamp is older than this. */-export const TIMESTAMP_VALIDITY_SECONDS = 30;diff --git a/robinhood/robinhood-crypto-mcp/src/trading-server.ts b/robinhood/robinhood-crypto-mcp/src/trading-server.tsdeleted file mode 100644index 302785f5a..000000000--- a/robinhood/robinhood-crypto-mcp/src/trading-server.ts+++ /dev/null@@ -1,51 +0,0 @@-#!/usr/bin/env node-/**- * Trading MCP server for the Robinhood Crypto Trading API.- *- * A superset of the read-only server: every data tool plus `place_order` and- * `cancel_order`. Refuses to start unless ROBINHOOD_CRYPTO_ENABLE_TRADING=1,- * so it can never be launched by accident.- */--import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';-import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';-import { RobinhoodCryptoClient } from './shared/client.js';-import { loadCredentials } from './shared/config.js';-import { loadTradingGuards } from './shared/guards.js';-import { registerDataTools } from './register-data.js';-import { registerTradingTools } from './register-trading.js';-import { VERSION } from './version.js';-import { isMain } from './shared/is-main.js';--export function createTradingServer(): McpServer {- const credentials = loadCredentials();- // Throws unless the operator explicitly opted in.- const guards = loadTradingGuards();- const client = new RobinhoodCryptoClient(credentials);-- const server = new McpServer({- name: 'robinhood-crypto-mcp-trading',- version: VERSION,- });-- registerDataTools(server, client, credentials);- registerTradingTools(server, client, credentials, guards);- return server;-}--export async function main(): Promise<void> {- try {- const server = createTradingServer();- await server.connect(new StdioServerTransport());- console.error(- '[robinhood-crypto-mcp-trading] Trading enabled. Orders place real money against a live account.',- );- } catch (error) {- console.error(`[robinhood-crypto-mcp-trading] ${error instanceof Error ? error.message : error}`);- process.exit(1);- }-}--if (isMain(import.meta.url)) {- void main();-}diff --git a/robinhood/robinhood-crypto-mcp/src/version.ts b/robinhood/robinhood-crypto-mcp/src/version.tsdeleted file mode 100644index 462632a31..000000000--- a/robinhood/robinhood-crypto-mcp/src/version.ts+++ /dev/null@@ -1,2 +0,0 @@-/** Package version, surfaced in the MCP handshake. */-export const VERSION = '0.1.0';diff --git a/robinhood/robinhood-crypto-mcp/tests/guards.test.ts b/robinhood/robinhood-crypto-mcp/tests/guards.test.tsdeleted file mode 100644index 4586cb84f..000000000--- a/robinhood/robinhood-crypto-mcp/tests/guards.test.ts+++ /dev/null@@ -1,116 +0,0 @@-import { describe, it, expect } from 'vitest';-import {- loadTradingGuards,- assertOrderAllowed,- estimateNotionalUsd,- GuardViolationError,- TradingDisabledError,- DEFAULT_MAX_ORDER_USD,-} from '../src/shared/guards.js';--const enabled = (extra: Record<string, string> = {}) =>- ({ ROBINHOOD_CRYPTO_ENABLE_TRADING: '1', ...extra }) as NodeJS.ProcessEnv;--describe('trading opt-in', () => {- it('refuses to load guards unless trading is explicitly enabled', () => {- expect(() => loadTradingGuards({} as NodeJS.ProcessEnv)).toThrow(TradingDisabledError);- expect(() =>- loadTradingGuards({ ROBINHOOD_CRYPTO_ENABLE_TRADING: 'true' } as NodeJS.ProcessEnv),- ).toThrow(TradingDisabledError);- expect(() =>- loadTradingGuards({ ROBINHOOD_CRYPTO_ENABLE_TRADING: '0' } as NodeJS.ProcessEnv),- ).toThrow(TradingDisabledError);- });-- it('loads a conservative default cap when enabled', () => {- expect(loadTradingGuards(enabled()).maxOrderUsd).toBe(DEFAULT_MAX_ORDER_USD);- });-- it('rejects a non-positive or malformed cap rather than defaulting silently', () => {- for (const bad of ['0', '-5', 'abc']) {- expect(() => loadTradingGuards(enabled({ ROBINHOOD_CRYPTO_MAX_ORDER_USD: bad }))).toThrow(- GuardViolationError,- );- }- });-- it('parses an allowlist into normalized symbols', () => {- const guards = loadTradingGuards(- enabled({ ROBINHOOD_CRYPTO_SYMBOL_ALLOWLIST: 'btc-usd, eth-usd' }),- );- expect(guards.symbolAllowlist).toEqual(['BTC-USD', 'ETH-USD']);- });-});--describe('assertOrderAllowed', () => {- const guards = { maxOrderUsd: 100, symbolAllowlist: null, buyOnly: false };-- it('allows an order within the cap', () => {- expect(() =>- assertOrderAllowed({ symbol: 'BTC-USD', side: 'buy', notionalUsd: 99.99 }, guards),- ).not.toThrow();- });-- it('blocks an order above the cap', () => {- expect(() =>- assertOrderAllowed({ symbol: 'BTC-USD', side: 'buy', notionalUsd: 100.01 }, guards),- ).toThrow(/exceeds the .* ceiling/);- });-- it('refuses to place an order whose value cannot be determined', () => {- // Fails closed: an unknown notional must never be treated as zero.- expect(() =>- assertOrderAllowed({ symbol: 'BTC-USD', side: 'buy', notionalUsd: null }, guards),- ).toThrow(/Cannot determine the USD value/);- });-- it('enforces the symbol allowlist', () => {- const restricted = { ...guards, symbolAllowlist: ['BTC-USD'] };- expect(() =>- assertOrderAllowed({ symbol: 'DOGE-USD', side: 'buy', notionalUsd: 10 }, restricted),- ).toThrow(/not in ROBINHOOD_CRYPTO_SYMBOL_ALLOWLIST/);- expect(() =>- assertOrderAllowed({ symbol: 'btc-usd', side: 'buy', notionalUsd: 10 }, restricted),- ).not.toThrow();- });-- it('blocks sells in buy-only mode', () => {- const buyOnly = { ...guards, buyOnly: true };- expect(() =>- assertOrderAllowed({ symbol: 'BTC-USD', side: 'sell', notionalUsd: 10 }, buyOnly),- ).toThrow(/blocked by ROBINHOOD_CRYPTO_BUY_ONLY/);- expect(() =>- assertOrderAllowed({ symbol: 'BTC-USD', side: 'buy', notionalUsd: 10 }, buyOnly),- ).not.toThrow();- });-});--describe('estimateNotionalUsd', () => {- it('uses quote_amount directly when given', () => {- expect(estimateNotionalUsd({ quoteAmount: '25.50' })).toBe(25.5);- });-- it('multiplies quantity by limit price for a limit order', () => {- expect(estimateNotionalUsd({ assetQuantity: '0.5', limitPrice: '100' })).toBe(50);- });-- it('falls back to a live reference price for a market order', () => {- expect(estimateNotionalUsd({ assetQuantity: '2', referencePrice: 30 })).toBe(60);- });-- it('prefers the limit price over the reference price when both exist', () => {- expect(estimateNotionalUsd({ assetQuantity: '1', limitPrice: '10', referencePrice: 999 })).toBe(- 10,- );- });-- it('returns null when no price is available, rather than guessing', () => {- expect(estimateNotionalUsd({ assetQuantity: '1' })).toBeNull();- expect(estimateNotionalUsd({})).toBeNull();- });-- it('returns null for unparseable numbers instead of NaN', () => {- expect(estimateNotionalUsd({ quoteAmount: 'abc' })).toBeNull();- expect(estimateNotionalUsd({ assetQuantity: 'abc', referencePrice: 10 })).toBeNull();- });-});diff --git a/robinhood/robinhood-crypto-mcp/tests/signer.test.ts b/robinhood/robinhood-crypto-mcp/tests/signer.test.tsdeleted file mode 100644index 93e1da615..000000000--- a/robinhood/robinhood-crypto-mcp/tests/signer.test.ts+++ /dev/null@@ -1,177 +0,0 @@-import { describe, it, expect } from 'vitest';-import { verify } from 'node:crypto';-import {- buildAuthHeaders,- buildSignatureMessage,- privateKeyFromBase64Seed,- publicKeyBase64,- publicKeyFromBase64,- currentTimestampSeconds,- InvalidPrivateKeyError,-} from '../src/shared/signer.js';--/**- * Key material published in Robinhood's own API documentation as an example.- * These are documentation values, not live credentials.- */-const DOC_PRIVATE_KEY = 'xQnTJVeQLmw1/Mg2YimEViSpw/SdJcgNXZ5kQkAXNPU=';-const DOC_PUBLIC_KEY = 'jPItx4TLjcnSUnmnXQQyAKL4eJj3+oWNNMmmm2vATqk=';-const DOC_API_KEY = 'rh-api-6148effc-c0b1-486c-8940-a1d099456be6';-const DOC_TIMESTAMP = 1698708981;-const DOC_PATH = '/api/v1/crypto/trading/orders/';-const DOC_SIGNATURE =- 'q/nEtxp/P2Or3hph3KejBqnw5o9qeuQ+hYRnB56FaHbjDsNUY9KhB1asMxohDnzdVFSD7StaTqjSd9U9HvaRAw==';--describe('key handling', () => {- it('derives the public key Robinhood documents for its example private key', () => {- // The strongest available check that seed handling is correct: Robinhood- // publishes both halves, and only correct PKCS#8 wrapping reproduces one- // from the other.- const privateKey = privateKeyFromBase64Seed(DOC_PRIVATE_KEY);- expect(publicKeyBase64(privateKey)).toBe(DOC_PUBLIC_KEY);- });-- it('rejects a 64-byte expanded keypair with a message naming the mistake', () => {- const expanded = Buffer.concat([- Buffer.from(DOC_PRIVATE_KEY, 'base64'),- Buffer.from(DOC_PUBLIC_KEY, 'base64'),- ]).toString('base64');-- expect(() => privateKeyFromBase64Seed(expanded)).toThrow(InvalidPrivateKeyError);- expect(() => privateKeyFromBase64Seed(expanded)).toThrow(/64-byte keypair/);- });-- it('rejects a key of the wrong length', () => {- expect(() => privateKeyFromBase64Seed(Buffer.alloc(16).toString('base64'))).toThrow(- /must decode to 32 bytes, got 16/,- );- });-- it('tolerates surrounding whitespace, which shells and .env files add', () => {- const privateKey = privateKeyFromBase64Seed(` ${DOC_PRIVATE_KEY}\n`);- expect(publicKeyBase64(privateKey)).toBe(DOC_PUBLIC_KEY);- });-});--describe('signature message', () => {- it('concatenates api key, timestamp, path, method, body with no separators', () => {- expect(- buildSignatureMessage({- apiKey: 'KEY',- timestamp: 123,- path: '/api/v1/x/',- method: 'POST',- body: '{"a":1}',- }),- ).toBe('KEY123/api/v1/x/POST{"a":1}');- });-- it('omits the body for requests that have none', () => {- expect(- buildSignatureMessage({ apiKey: 'KEY', timestamp: 1, path: '/p/', method: 'GET' }),- ).toBe('KEY1/p/GET');- });-- it('uppercases the method', () => {- expect(- buildSignatureMessage({ apiKey: 'K', timestamp: 1, path: '/p/', method: 'post' }),- ).toBe('K1/p/POST');- });-});--describe('buildAuthHeaders', () => {- it('produces a signature that verifies against the matching public key', () => {- const privateKey = privateKeyFromBase64Seed(DOC_PRIVATE_KEY);- const body = '{"symbol":"BTC-USD"}';-- const headers = buildAuthHeaders({- apiKey: DOC_API_KEY,- privateKey,- path: DOC_PATH,- method: 'POST',- body,- timestamp: DOC_TIMESTAMP,- });-- const message = buildSignatureMessage({- apiKey: DOC_API_KEY,- timestamp: DOC_TIMESTAMP,- path: DOC_PATH,- method: 'POST',- body,- });-- const verified = verify(- null,- Buffer.from(message, 'utf8'),- publicKeyFromBase64(DOC_PUBLIC_KEY),- Buffer.from(headers['x-signature'], 'base64'),- );-- expect(verified).toBe(true);- expect(headers['x-api-key']).toBe(DOC_API_KEY);- expect(headers['x-timestamp']).toBe(String(DOC_TIMESTAMP));- });-- it('emits the timestamp in seconds, not milliseconds', () => {- const headers = buildAuthHeaders({- apiKey: 'K',- privateKey: privateKeyFromBase64Seed(DOC_PRIVATE_KEY),- path: '/p/',- method: 'GET',- });-- const timestamp = Number(headers['x-timestamp']);- // A ms timestamp would be ~1e12; seconds are ~1e9. Robinhood rejects- // anything more than 30s stale, so this unit error is fatal in production.- expect(timestamp).toBeLessThan(1e11);- expect(Math.abs(timestamp - currentTimestampSeconds())).toBeLessThanOrEqual(2);- });-});--describe("Robinhood's published conformance vector", () => {- /**- * Robinhood documents a worked example and invites implementers to check- * their signature against it. That published signature does NOT correspond- * to the JSON body a real client sends: it was generated by signing a Python- * dict repr (single quotes, spaces after colons, and a different key order- * than the accompanying table shows).- *- * This is pinned as a test so the quirk stays documented and nobody "fixes"- * a correct implementation to chase it. Signing the JSON body — what every- * working client does, and what Robinhood's own sample code does at runtime —- * is correct.- */- const DICT_REPR_BODY =- "{'client_order_id': '131de903-5a9c-4260-abc1-28d562a5dcf0', 'side': 'buy', " +- "'symbol': 'BTC-USD', 'type': 'market', 'market_order_config': {'asset_quantity': '0.1'}}";-- const JSON_BODY =- '{"client_order_id":"131de903-5a9c-4260-abc1-28d562a5dcf0","side":"buy",' +- '"type":"market","symbol":"BTC-USD","market_order_config":{"asset_quantity":"0.1"}}';-- const verifyVector = (body: string) =>- verify(- null,- Buffer.from(- buildSignatureMessage({- apiKey: DOC_API_KEY,- timestamp: DOC_TIMESTAMP,- path: DOC_PATH,- method: 'POST',- body,- }),- 'utf8',- ),- publicKeyFromBase64(DOC_PUBLIC_KEY),- Buffer.from(DOC_SIGNATURE, 'base64'),- );-- it('matches only a Python dict repr, confirming the published vector is unusable', () => {- expect(verifyVector(DICT_REPR_BODY)).toBe(true);- });-- it('does not match the JSON body a real client sends over the wire', () => {- expect(verifyVector(JSON_BODY)).toBe(false);- });-});diff --git a/robinhood/robinhood-crypto-mcp/tsconfig.json b/robinhood/robinhood-crypto-mcp/tsconfig.jsondeleted file mode 100644index 951cc562c..000000000--- a/robinhood/robinhood-crypto-mcp/tsconfig.json+++ /dev/null@@ -1,22 +0,0 @@-{- "compilerOptions": {- "target": "ES2022",- "module": "ESNext",- "moduleResolution": "Bundler",- "lib": ["ES2023"],- "types": ["node"],- "declaration": true,- "strict": true,- "noUncheckedIndexedAccess": true,- "noImplicitOverride": true,- "esModuleInterop": true,- "skipLibCheck": true,- "resolveJsonModule": true,- "verbatimModuleSyntax": true,- "isolatedModules": true,- "forceConsistentCasingInFileNames": true,- "outDir": "dist"- },- "include": ["src"],- "exclude": ["node_modules", "dist", "tests"]-}diff --git a/robinhood/robinhood-crypto-mcp/tsup.config.ts b/robinhood/robinhood-crypto-mcp/tsup.config.tsdeleted file mode 100644index b6b007007..000000000--- a/robinhood/robinhood-crypto-mcp/tsup.config.ts+++ /dev/null@@ -1,16 +0,0 @@-import { defineConfig } from 'tsup'--export default defineConfig({- entry: {- index: 'src/index.ts',- 'data-server': 'src/data-server.ts',- 'trading-server': 'src/trading-server.ts',- keygen: 'src/keygen.ts',- },- format: ['esm'],- dts: true,- clean: true,- sourcemap: true,- target: 'node20',- banner: { js: '' },-})diff --git a/robinhood/robinhood-crypto-mcp/vitest.config.ts b/robinhood/robinhood-crypto-mcp/vitest.config.tsdeleted file mode 100644index a8afbbf71..000000000--- a/robinhood/robinhood-crypto-mcp/vitest.config.ts+++ /dev/null@@ -1,9 +0,0 @@-import { defineConfig } from 'vitest/config'--export default defineConfig({- test: {- include: ['tests/**/*.test.ts'],- exclude: ['tests/**/*.live.test.ts'],- testTimeout: 30_000,- },-})diff --git a/robinhood/robinhood-crypto-mcp/vitest.live.config.ts b/robinhood/robinhood-crypto-mcp/vitest.live.config.tsdeleted file mode 100644index c108ef3fc..000000000--- a/robinhood/robinhood-crypto-mcp/vitest.live.config.ts+++ /dev/null@@ -1,10 +0,0 @@-import { defineConfig } from 'vitest/config'--// Live tests hit the real Robinhood API and need real credentials.-// They are excluded from `npm test` on purpose.-export default defineConfig({- test: {- include: ['tests/**/*.live.test.ts'],- testTimeout: 120_000,- },-})diff --git a/robinhood/robinhood-mcp b/robinhood/robinhood-mcpnew file mode 160000index 000000000..074da11ab--- /dev/null+++ b/robinhood/robinhood-mcp@@ -0,0 +1 @@+Subproject commit 074da11ab01bd1cc3721ae78de2c049d061678c4diff --git a/scripts/post-tweet.mjs b/scripts/post-tweet.mjsnew file mode 100644index 000000000..cf1d94771--- /dev/null+++ b/scripts/post-tweet.mjs@@ -0,0 +1,109 @@+#!/usr/bin/env node+// Post a single one-off tweet (or reply) from the @trythreews X account.+//+// scripts/changelog-x.mjs handles the chained release thread; this script is+// for standalone announcements that aren't a changelog entry (community+// channel launches, milestones, partnerships).+//+// Env (reads .env.local -> .env -> environment) — same OAuth 1.0a user+// context as changelog-x.mjs, from a developer.x.com app with Read+Write+// access to @trythreews:+// X_API_KEY app consumer key+// X_API_SECRET app consumer secret+// X_ACCESS_TOKEN user access token for @trythreews+// X_ACCESS_SECRET user access token secret for @trythreews+//+// Usage:+// node scripts/post-tweet.mjs --text "..."+// node scripts/post-tweet.mjs --file path/to/tweet.txt+// node scripts/post-tweet.mjs --text "..." --reply-to 1234567890+// node scripts/post-tweet.mjs --text "..." --dry-run++import { readFileSync } from 'node:fs';+import { resolve, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';++const here = dirname(fileURLToPath(import.meta.url));+const root = resolve(here, '..');++function loadEnvFile(path) {+ let raw;+ try {+ raw = readFileSync(path, 'utf8');+ } catch {+ return;+ }+ for (const line of raw.split('\n')) {+ const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/i);+ if (!m) continue;+ const [, k, v] = m;+ if (process.env[k]) continue;+ process.env[k] = v.replace(/^["']|["']$/g, '');+ }+}+loadEnvFile(resolve(root, '.env.local'));+loadEnvFile(resolve(root, '.env'));++const args = process.argv.slice(2);+const flag = (name) => args.includes(`--${name}`);+const opt = (name) => {+ const a = args.find((x) => x.startsWith(`--${name}=`));+ if (a) return a.split('=').slice(1).join('=');+ const i = args.indexOf(`--${name}`);+ return i !== -1 && args[i + 1] && !args[i + 1].startsWith('--') ? args[i + 1] : null;+};++const dryRun = flag('dry-run');+const filePath = opt('file');+const replyTo = opt('reply-to');+let text = opt('text');++if (!text && filePath) text = readFileSync(resolve(process.cwd(), filePath), 'utf8').trim();+if (!text) {+ console.error('Usage: node scripts/post-tweet.mjs --text "..." [--reply-to <tweetId>] [--dry-run]');+ console.error(' or: node scripts/post-tweet.mjs --file path/to/tweet.txt');+ process.exit(1);+}++// X counts every URL as 23 chars (t.co wrapping) and each emoji/astral+// codepoint as 2.+const URL_WEIGHT = 23;+const weightedLength = (s) =>+ [...s.replace(/https?:\/\/\S+/g, 'x'.repeat(URL_WEIGHT))].reduce(+ (n, ch) => n + (ch.codePointAt(0) > 0xffff ? 2 : 1),+ 0,+ );++const weight = weightedLength(text);+if (weight > 280) {+ console.error(`Tweet is ${weight} weighted chars, over the 280 limit. Trim it.`);+ process.exit(1);+}++console.log(`--- tweet (${weight} weighted chars)${replyTo ? `, reply to ${replyTo}` : ''}${dryRun ? ' — DRY RUN' : ''} ---`);+console.log(text);++if (dryRun) process.exit(0);++const creds = {+ appKey: process.env.X_API_KEY,+ appSecret: process.env.X_API_SECRET,+ accessToken: process.env.X_ACCESS_TOKEN,+ accessSecret: process.env.X_ACCESS_SECRET,+};+if (!(creds.appKey && creds.appSecret && creds.accessToken && creds.accessSecret)) {+ console.error('\nX_API_KEY, X_API_SECRET, X_ACCESS_TOKEN and X_ACCESS_SECRET must be set (see .env.example). Use --dry-run to preview without credentials.');+ process.exit(1);+}++const { TwitterApi } = await import('twitter-api-v2');+const client = new TwitterApi(creds);++try {+ const payload = replyTo ? { reply: { in_reply_to_tweet_id: replyTo } } : undefined;+ const { data } = await client.v2.tweet(text, payload);+ console.log(`\nposted https://x.com/trythreews/status/${data.id}`);+} catch (err) {+ console.error(`\nFAILED: ${err.message}`);+ process.exit(1);+}