{"id":29625385,"url":"https://github.com/usherlabs/cex-broker","last_synced_at":"2025-07-21T06:36:13.989Z","repository":{"id":304635691,"uuid":"1013913315","full_name":"usherlabs/cex-broker","owner":"usherlabs","description":"Unified gRPC API to CEXs by Usher Labs","archived":false,"fork":false,"pushed_at":"2025-07-14T09:30:09.000Z","size":277,"stargazers_count":0,"open_issues_count":2,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-07-14T12:31:33.385Z","etag":null,"topics":["binance","broker","bybit","centralised-exchange","cex","exchange","trading"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/usherlabs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-07-04T17:21:27.000Z","updated_at":"2025-07-13T12:46:32.000Z","dependencies_parsed_at":"2025-07-14T12:31:35.870Z","dependency_job_id":"dfd06b99-65c1-4bb4-bacc-eae5eca4c044","html_url":"https://github.com/usherlabs/cex-broker","commit_stats":null,"previous_names":["usherlabs/cex-broker"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/usherlabs/cex-broker","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/usherlabs%2Fcex-broker","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/usherlabs%2Fcex-broker/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/usherlabs%2Fcex-broker/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/usherlabs%2Fcex-broker/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/usherlabs","download_url":"https://codeload.github.com/usherlabs/cex-broker/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/usherlabs%2Fcex-broker/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":266253877,"owners_count":23900056,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["binance","broker","bybit","centralised-exchange","cex","exchange","trading"],"created_at":"2025-07-21T06:36:00.426Z","updated_at":"2025-07-21T06:36:13.981Z","avatar_url":"https://github.com/usherlabs.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# FietCexBroker\n\nA high-performance gRPC-based cryptocurrency exchange broker service that provides unified access to multiple centralized exchanges (CEX) including Binance and Bybit. Built with TypeScript, Bun, and CCXT for reliable trading operations.\n\n## Features\n\n- **Multi-Exchange Support**: Unified API for Binance and Bybit\n- **gRPC Interface**: High-performance RPC communication\n- **Real-time Pricing**: Optimal price discovery across exchanges\n- **Balance Management**: Real-time balance checking\n- **Order Management**: Create, track, and cancel orders\n- **Transfer Operations**: Withdraw funds to external addresses\n- **Token Conversion**: Convert between different tokens\n- **Policy Enforcement**: Configurable trading and withdrawal limits\n- **IP Authentication**: Security through IP whitelisting\n- **Type Safety**: Full TypeScript support with generated protobuf types\n\n## Prerequisites\n\n- [Bun](https://bun.sh) (v1.2.17 or higher)\n- API keys for supported exchanges (Binance, Bybit)\n\n## Installation\n\n1. Clone the repository:\n```bash\ngit clone \u003crepository-url\u003e\ncd fietCexBroker\n```\n\n2. Install dependencies:\n```bash\nbun install\n```\n\n3. Generate protobuf types:\n```bash\nbun run proto-gen\n```\n\n## Configuration\n\n### Environment Variables\n\nCreate a `.env` file in the root directory with the following variables:\n\n```env\n# Server Configuration\nPORT_NUM=8082\n\n# Exchange API Keys\nBINANCE_API_KEY=your_binance_api_key\nBINANCE_API_SECRET=your_binance_api_secret\nBYBIT_API_KEY=your_bybit_api_key\nBYBIT_API_SECRET=your_bybit_api_secret\n\n# Supported Brokers (optional, defaults to BINANCE,BYBIT)\nROOCH_CHAIN_ID=BINANCE,BYBIT\n```\n\n**Note**: API keys are only required for the exchanges you plan to use. The system will validate that required keys are provided based on the `ROOCH_CHAIN_ID` configuration.\n\n### Policy Configuration\n\nConfigure trading policies in `policy/policy.json`:\n\n```json\n{\n  \"withdraw\": {\n    \"rule\": {\n      \"networks\": [\"BEP20\", \"ARBITRUM\"],\n      \"whitelist\": [\"0x9d467fa9062b6e9b1a46e26007ad82db116c67cb\"],\n      \"amounts\": [\n        {\n          \"ticker\": \"USDC\",\n          \"max\": 100000,\n          \"min\": 1\n        },\n        {\n          \"ticker\": \"USDT\",\n          \"max\": 100000,\n          \"min\": 1\n        }\n      ]\n    }\n  },\n  \"deposit\": {},\n  \"order\": {\n    \"rule\": {\n      \"markets\": [\n        \"BINANCE:ARB/USDT\",\n        \"BYBIT:ARB/USDC\",\n        \"BINANCE:ETH/USDT\",\n        \"BINANCE:BTC/ETH\"\n      ],\n      \"limits\": [\n        { \"from\": \"USDT\", \"to\": \"ETH\", \"min\": 1, \"max\": 100000 },\n        { \"from\": \"ETH\", \"to\": \"USDT\", \"min\": 0.5, \"max\": 5 },\n        { \"from\": \"ARB\", \"to\": \"USDC\", \"min\": 1, \"max\": 1000 },\n        { \"from\": \"USDC\", \"to\": \"ARB\", \"min\": 1, \"max\": 10000 }\n      ]\n    }\n  }\n}\n```\n\n## Usage\n\n### Starting the Server\n\n```bash\n# Development\nbun run start\n\n# Production build\nbun run build\nbun run ./build/index.js\n```\n\n### Available Scripts\n\n```bash\n# Start the server\nbun run start\n\n# Build for production\nbun run build\n\n# Run tests\nbun test\n\n# Generate protobuf types\nbun run proto-gen\n\n# Format code\nbun run format\n\n# Lint code\nbun run lint\n\n# Check code (format + lint)\nbun run check\n```\n\n## API Reference\n\nThe service exposes a gRPC interface with the following methods:\n\n### GetOptimalPrice\n\nGet optimal buy/sell prices across supported exchanges.\n\n**Request:**\n```protobuf\nmessage OptimalPriceRequest {\n  string symbol = 1;            // Trading pair symbol, e.g. \"ARB/USDT\"\n  double quantity = 2;          // Quantity to buy or sell\n  OrderMode mode = 3;           // Buy (0) or Sell (1) mode\n}\n```\n\n**Response:**\n```protobuf\nmessage OptimalPriceResponse {\n  map\u003cstring, PriceInfo\u003e results = 1;\n}\n\nmessage PriceInfo {\n  double avgPrice = 1;          // Volume-weighted average price\n  double fillPrice = 2;         // Worst-case fill price\n}\n```\n\n**Example:**\n```typescript\nconst request = {\n  symbol: \"ARB/USDT\",\n  quantity: 100,\n  mode: 0  // BUY\n};\n```\n\n### GetBalance\n\nGet available balance for a specific currency on a specific exchange.\n\n**Request:**\n```protobuf\nmessage BalanceRequest {\n  string cex = 1;              // CEX identifier (e.g., \"BINANCE\", \"BYBIT\")\n  string token = 2;            // Token symbol, e.g. \"USDT\"\n}\n```\n\n**Response:**\n```protobuf\nmessage BalanceResponse {\n  double balance = 1;          // Available balance for the token\n  string currency = 2;         // Currency of the balance\n}\n```\n\n**Example:**\n```typescript\nconst request = {\n  cex: \"BINANCE\",\n  token: \"USDT\"\n};\n```\n\n### Deposit\n\nConfirm a deposit transaction.\n\n**Request:**\n```protobuf\nmessage DepositConfirmationRequest {\n  string chain = 1;\n  string recipient_address = 2;\n  double amount = 3;\n  string transaction_hash = 4;\n}\n```\n\n**Response:**\n```protobuf\nmessage DepositConfirmationResponse {\n  double newBalance = 1;\n}\n```\n\n### Transfer\n\nExecute a transfer/withdrawal to an external address.\n\n**Request:**\n```protobuf\nmessage TransferRequest {\n  string chain = 1;            // Network chain (e.g., \"ARBITRUM\", \"BEP20\")\n  string recipient_address = 2; // Destination address\n  double amount = 3;           // Amount to transfer\n  string cex = 4;              // CEX identifier\n  string token = 5;            // Token symbol\n}\n```\n\n**Response:**\n```protobuf\nmessage TransferResponse {\n  bool success = 1;\n  string transaction_id = 2;\n}\n```\n\n### Convert\n\nConvert between different tokens using limit orders.\n\n**Request:**\n```protobuf\nmessage ConvertRequest {\n  string from_token = 1;       // Source token\n  string to_token = 2;         // Destination token\n  double amount = 3;           // Amount to convert\n  double price = 4;            // Limit price\n  string cex = 5;              // CEX identifier\n}\n```\n\n**Response:**\n```protobuf\nmessage ConvertResponse {\n  string order_id = 3;\n}\n```\n\n### GetOrderDetails\n\nGet details of a specific order.\n\n**Request:**\n```protobuf\nmessage OrderDetailsRequest {\n  string order_id = 1;         // Unique order identifier\n  string cex = 2;              // CEX identifier\n}\n```\n\n**Response:**\n```protobuf\nmessage OrderDetailsResponse {\n  string order_id = 1;         // Unique order identifier\n  string status = 2;           // Current order status\n  double original_amount = 3;  // Original order amount\n  double filled_amount = 4;    // Amount that has been filled\n  string symbol = 5;           // Trading pair symbol\n  string mode = 6;             // Buy or Sell mode\n  double price = 7;            // Order price\n}\n```\n\n### CancelOrder\n\nCancel an existing order.\n\n**Request:**\n```protobuf\nmessage CancelOrderRequest {\n  string order_id = 1;         // Unique order identifier\n  string cex = 2;              // CEX identifier\n}\n```\n\n**Response:**\n```protobuf\nmessage CancelOrderResponse {\n  bool success = 1;            // Whether cancellation was successful\n  string final_status = 2;     // Final status of the order\n}\n```\n\n## Security\n\n### IP Authentication\n\nAll API calls require IP authentication. Configure allowed IPs in `helpers/index.ts`:\n\n```typescript\nconst ALLOWED_IPS = [\n  \"127.0.0.1\", // localhost\n  \"::1\",       // IPv6 localhost\n  // Add your allowed IP addresses here\n];\n```\n\n### API Key Management\n\n- Store API keys securely in environment variables\n- Use read-only API keys when possible\n- Regularly rotate API keys\n- Monitor API usage and set appropriate rate limits\n\n## Error Handling\n\nThe service returns appropriate gRPC status codes:\n\n- `INVALID_ARGUMENT`: Missing or invalid parameters\n- `PERMISSION_DENIED`: IP not allowed or policy violation\n- `NOT_FOUND`: Resource not found (e.g., currency balance)\n- `INTERNAL`: Server error\n\n## Development\n\n### Project Structure\n\n```\nfietCexBroker/\n├── config/                 # Configuration files\n│   ├── broker.ts          # Exchange broker setup\n│   └── index.ts           # Environment configuration\n├── helpers/               # Utility functions\n│   └── index.ts           # Core helper functions\n├── policy/                # Policy configuration\n│   └── policy.json        # Trading and withdrawal rules\n├── proto/                 # Protocol buffer definitions\n│   ├── fietCexNode/       # Generated TypeScript types\n│   ├── node.proto         # Service definition\n│   └── node.ts            # Type exports\n├── scripts/               # Build scripts\n│   └── patch-protobufjs.js\n├── index.ts               # Main server file\n├── types.ts               # TypeScript type definitions\n├── proto-gen.sh           # Protobuf generation script\n├── biome.json             # Code formatting/linting config\n├── bunfig.toml            # Bun configuration\n└── package.json           # Dependencies and scripts\n```\n\n### Adding New Exchanges\n\n1. Add the exchange to `types.ts` in the `BrokerList`\n2. Configure API keys in `config/index.ts`\n3. Initialize the broker in `config/broker.ts`\n4. Update policy configuration if needed\n\n### Testing\n\n```bash\n# Run all tests\nbun test\n\n# Run tests with watch mode\nbun test --watch\n\n# Run tests with coverage\nbun test --coverage\n```\n\n## Dependencies\n\n### Core Dependencies\n- `@grpc/grpc-js`: gRPC server implementation\n- `@grpc/proto-loader`: Protocol buffer loading\n- `ccxt`: Cryptocurrency exchange library\n- `dotenv`: Environment variable management\n- `joi`: Configuration validation\n\n### Development Dependencies\n- `@biomejs/biome`: Code formatting and linting\n- `@types/bun`: Bun type definitions\n- `bun-types`: Additional Bun types\n- `husky`: Git hooks\n\n## Contributing\n\n1. Fork the repository\n2. Create a feature branch\n3. Make your changes\n4. Add tests for new functionality\n5. Ensure all tests pass\n6. Run `bun run check` to format and lint code\n7. Submit a pull request\n\n## License\n\n[Add your license information here]\n\n## Support\n\nFor issues and questions, please open an issue on the repository or contact the development team.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fusherlabs%2Fcex-broker","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fusherlabs%2Fcex-broker","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fusherlabs%2Fcex-broker/lists"}