{"id":50808132,"url":"https://github.com/AlexanderMerkel/binance-fix-connector-python","last_synced_at":"2026-06-30T10:00:47.606Z","repository":{"id":360263874,"uuid":"1040418485","full_name":"AlexanderMerkel/binance-fix-connector-python","owner":"AlexanderMerkel","description":"High-performance async Python library for Binance FIX API trading with full async/await support","archived":false,"fork":false,"pushed_at":"2026-05-25T17:10:57.000Z","size":146,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-05-25T18:33:01.667Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/AlexanderMerkel.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","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,"notice":null,"maintainers":null,"copyright":null,"agents":"AGENTS.md","dco":null,"cla":null}},"created_at":"2025-08-19T00:30:53.000Z","updated_at":"2026-05-25T17:11:01.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/AlexanderMerkel/binance-fix-connector-python","commit_stats":null,"previous_names":["alexandermerkel/binance-fix-connector-python"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/AlexanderMerkel/binance-fix-connector-python","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AlexanderMerkel%2Fbinance-fix-connector-python","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AlexanderMerkel%2Fbinance-fix-connector-python/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AlexanderMerkel%2Fbinance-fix-connector-python/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AlexanderMerkel%2Fbinance-fix-connector-python/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/AlexanderMerkel","download_url":"https://codeload.github.com/AlexanderMerkel/binance-fix-connector-python/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AlexanderMerkel%2Fbinance-fix-connector-python/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34961549,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-30T02:00:05.919Z","response_time":92,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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":[],"created_at":"2026-06-13T03:00:26.860Z","updated_at":"2026-06-30T10:00:47.599Z","avatar_url":"https://github.com/AlexanderMerkel.png","language":"Python","funding_links":[],"categories":["Trading \u0026 Backtesting"],"sub_categories":[],"readme":"# Async Binance SPOT FIX Connector for Python\n\nThis is an unofficial `asyncio`-native Python connector for Binance Financial Information eXchange (FIX) [SPOT messages](https://github.com/binance/binance-spot-api-docs/blob/master/fix-api.md#message-components).\nIt is aimed at testnet workflows, session experiments, and local latency research across Order Entry, Market Data, and Drop Copy.\n\n## Key Features\n\n- **Async-First API**: `asyncio` session management for running multiple FIX workflows in one event loop\n- **Quick Testing Workflow**: Examples for order entry, market data, drop copy, instrument queries, and limit checks\n- **Feed/Session Comparison**: Shared API surface for comparing Order Entry, Market Data, and Drop Copy behavior\n- **Latency Research Support**: Local sync-vs-async benchmark checks for research and regression testing\n- **Typed Core**: Type-annotated core library with `basedpyright` checks for `src/`\n- **SPOT FIX Workflows**: Helpers for Binance public SPOT FIX workflow areas: Order Entry, Market Data, and Drop Copy\n\n## Prerequisites\n\nBefore using or testing the library, ensure that the necessary dependencies are installed. You can do this by running the following command:\n\n```\npip install binance-fix-connector-async\n```\n\n**Notes:**\n\n- Python 3.13 or newer is required.\n- Binance FIX API supports Ed25519 keys. Please refer to this [tutorial](https://www.binance.com/en/support/faq/how-to-generate-an-ed25519-key-pair-to-send-api-requests-on-binance-6b9a63f1e3384cf48a2eedb82767a69a) for setting up an Ed25519 key pair on the mainnet, and this one for the [testnet](https://testnet.binance.vision/).\n- Ensure that your API key has the appropriate Fix API permissions for the Testnet environment before you begin testing.\n- Real testnet scenarios are marker-driven with `requires_testnet` and are not part of default CI runs.\n\n## Example\n\nAll the FIX messages can be created with the `BinanceFixConnector` class. The following example demonstrates how to create a simple order using the async FIX API:\n\n```python\nimport asyncio\nimport time\nfrom binance_fix_connector_async.fix_connector import create_order_entry_session\nfrom binance_fix_connector_async.utils import get_private_key\n\n# Credentials\nAPI_KEY = \"...\"\nPATH_TO_PRIVATE_KEY_PEM_FILE = \"/path/to/ed25519_private_key.pem\"\n\n# FIX URL\nFIX_OE_URL = \"tcp+tls://fix-oe.testnet.binance.vision:9000\"\n\n# Response types\nORD_STATUS = {\n    \"0\": \"NEW\",\n    \"1\": \"PARTIALLY_FILLED\",\n    \"2\": \"FILLED\",\n    \"4\": \"CANCELED\",\n    \"6\": \"PENDING_CANCEL\",\n    \"8\": \"REJECTED\",\n    \"A\": \"PENDING_NEW\",\n    \"C\": \"EXPIRED\",\n}\nORD_TYPES = {\"1\": \"MARKET\", \"2\": \"LIMIT\", \"3\": \"STOP\", \"4\": \"STOP_LIMIT\"}\nSIDES = {\"1\": \"BUY\", \"2\": \"SELL\"}\nTIME_IN_FORCE = {\n    \"1\": \"GOOD_TILL_CANCEL\",\n    \"3\": \"IMMEDIATE_OR_CANCEL\",\n    \"4\": \"FILL_OR_KILL\",\n}\nORD_REJECT_REASON = {\"99\": \"OTHER\"}\n\n# Parameter\nINSTRUMENT = \"BNBUSDT\"\n\nasync def main():\n    client_oe = await create_order_entry_session(\n        api_key=API_KEY,\n        private_key=get_private_key(PATH_TO_PRIVATE_KEY_PEM_FILE),\n        endpoint=FIX_OE_URL,\n    )\n    await client_oe.retrieve_messages_until(message_type=\"A\")\n\n    example = \"This example shows how to place a single order. Order type LIMIT.\\nCheck https://github.com/binance/binance-spot-api-docs/blob/master/fix-api.md#newordersingled for additional types.\"\n    client_oe.logger.info(example)\n\n    # PLACING SIMPLE ORDER\n    msg = await client_oe.create_fix_message_with_basic_header(\"D\")\n    msg.append_pair(38, 1)  # ORD QTY\n    msg.append_pair(40, 2)  # ORD TYPE\n    msg.append_pair(11, str(time.time_ns()))  # CL ORD ID\n    msg.append_pair(44, \"CURRENT_FILTER_VALID_PRICE\")  # PRICE; see examples/trade/new_order.py\n    msg.append_pair(54, 2)  # SIDE\n    msg.append_pair(55, INSTRUMENT)  # SYMBOL\n    msg.append_pair(59, 1)  # TIME IN FORCE\n    await client_oe.send_message(msg)\n\n    responses = await client_oe.retrieve_messages_until(message_type=\"8\")\n    resp = next(\n        (x for x in responses if x.message_type.decode(\"utf-8\") == \"8\"),\n        None,\n    )\n    client_oe.logger.info(\"Parsing response Execution Report (8) for an order LIMIT type.\")\n\n    cl_ord_id = None if not resp.get(11) else resp.get(11).decode(\"utf-8\")\n    order_qty = None if not resp.get(38) else resp.get(38).decode(\"utf-8\")\n    ord_type = None if not resp.get(40) else resp.get(40).decode(\"utf-8\")\n    side = None if not resp.get(54) else resp.get(54).decode(\"utf-8\")\n    symbol = None if not resp.get(55) else resp.get(55).decode(\"utf-8\")\n    price = None if not resp.get(44) else resp.get(44).decode(\"utf-8\")\n    time_in_force = None if not resp.get(59) else resp.get(59).decode(\"utf-8\")\n    cum_qty = None if not resp.get(14) else resp.get(14).decode(\"utf-8\")\n    last_qty = None if not resp.get(32) else resp.get(32).decode(\"utf-8\")\n    ord_status = None if not resp.get(39) else resp.get(39).decode(\"utf-8\")\n    ord_rej_reason = None if not resp.get(103) else resp.get(103).decode(\"utf-8\")\n    error_code = None if not resp.get(25016) else resp.get(25016).decode(\"utf-8\")\n    text = None if not resp.get(58) else resp.get(58).decode(\"utf-8\")\n\n    client_oe.logger.info(f\"Client order ID: {cl_ord_id}\")\n    client_oe.logger.info(f\"Symbol: {symbol}\")\n    client_oe.logger.info(\n        f\"Order -\u003e Type: {ORD_TYPES.get(ord_type, ord_type)} | Side: {SIDES.get(side, side)} | TimeInForce: {TIME_IN_FORCE.get(time_in_force,time_in_force)}\",\n    )\n    client_oe.logger.info(\n        f\"Price: {price} | Quantity: {order_qty} | cum qty: {cum_qty} | last qty: {last_qty}\"\n    )\n    client_oe.logger.info(\n        f\"Status: {ORD_STATUS.get(ord_status,ord_status)} | Msg: {ORD_REJECT_REASON.get(ord_rej_reason,ord_rej_reason)}\",\n    )\n    client_oe.logger.info(f\"Error code: {error_code} | Reason: {text}\")\n\n    # LOGOUT\n    client_oe.logger.info(\"LOGOUT (5)\")\n    await client_oe.logout()\n    await client_oe.retrieve_messages_until(message_type=\"5\")\n    client_oe.logger.info(\n        \"Closing the connection with server as we already sent the logout message\"\n    )\n    await client_oe.disconnect()\n\n# Run the async main function\nif __name__ == \"__main__\":\n    asyncio.run(main())\n```\n\nPlease look at [`examples`](./examples) folder to test the examples.\nTo try the examples, use [`config.json.example`](./config.json.example) in the repository root as a template, or provide credentials via environment variables.\nExamples use testnet credentials by default:\n\n```bash\nexport BINANCE_TESTNET_FIX_KEY=\"...\"\nexport BINANCE_TESTNET_FIX_PRIVATE_KEY_PATH=\"/path/to/ed25519_private_key.pem\"\n```\n\nSet `BINANCE_FIX_ENV=mainnet` or `USE_TESTNET=false` only when you explicitly want mainnet credentials.\n\n## API Reference\n\n### Factory Functions\n\nThe library provides three factory functions for different types of FIX sessions:\n\n#### `create_order_entry_session()`\n\n```python\ncreate_order_entry_session(\n    api_key: str,\n    private_key: ed25519.Ed25519PrivateKey,\n    endpoint: str = \"tcp+tls://fix-oe.binance.com:9000\",\n    sender_comp_id: str = \"TRADE\",\n    target_comp_id: str = \"SPOT\",\n    fix_version: str = \"FIX.4.4\",\n    heart_bt_int: int = 30,\n    message_handling: int = 2,\n    response_mode: int = 1,\n    recv_window: int | None = None,\n) -\u003e BinanceFixConnector\n```\n\nCreates a session for order placement and management.\n\n#### `create_market_data_session()`\n\n```python\ncreate_market_data_session(\n    api_key: str,\n    private_key: ed25519.Ed25519PrivateKey,\n    endpoint: str = \"tcp+tls://fix-md.binance.com:9000\",\n    sender_comp_id: str = \"WATCH\",\n    target_comp_id: str = \"SPOT\",\n    fix_version: str = \"FIX.4.4\",\n    heart_bt_int: int = 30,\n    message_handling: int = 2,\n    recv_window: int | None = None,\n) -\u003e BinanceFixConnector\n```\n\nCreates a session for market data streaming.\n\n#### `create_drop_copy_session()`\n\n```python\ncreate_drop_copy_session(\n    api_key: str,\n    private_key: ed25519.Ed25519PrivateKey,\n    endpoint: str = \"tcp+tls://fix-dc.binance.com:9000\",\n    sender_comp_id: str = \"TECH\",\n    target_comp_id: str = \"SPOT\",\n    fix_version: str = \"FIX.4.4\",\n    heart_bt_int: int = 30,\n    message_handling: int = 2,\n    response_mode: int = 1,\n    recv_window: int | None = None,\n    check_permissions: bool = False,\n    hmac_secret: str | None = None,\n    permission_base_url: str = \"https://api.binance.com\",\n) -\u003e BinanceFixConnector\n```\n\nCreates a session for trade reporting and compliance.\nThe optional permission check uses Binance's mainnet HMAC Wallet API restriction endpoint. Spot Testnet does not support `/sapi`; testnet Ed25519 FIX-key compatibility is validated by the FIX logon itself.\n\n### Core Methods\n\n#### Connection Management\n\n- `connect()` - Establish connection to Binance FIX server\n- `disconnect()` - Close connection and cleanup resources\n- `logon(recv_window=None)` - Perform FIX logon with authentication\n- `logout(text=None, recv_window=None)` - Send logout message\n\n#### Message Operations\n\n- `create_fix_message_with_basic_header(msg_type, recv_window=None)` - Create properly formatted FIX message\n- `send_message(message, raw=False)` - Send FIX message to server\n- `retrieve_messages_until(message_type, message_cl_ord_id=None, timeout_seconds=3)` - Retrieve messages until a specific message type, and optionally `ClOrdID`, is received\n- `get_all_new_messages_received()` - Get all received messages not returned by previous calls to this method\n\n#### Utility Functions\n\n- `get_api_key(config_path)` - Load API credentials from config file\n- `get_private_key(key_path)` - Load Ed25519 private key from PEM file\n\n## Async Testing and Feed Research\n\nThis project is an unofficial async research connector, not a replacement for Binance's [official sync library](https://github.com/binance/binance-fix-connector-python). It targets public Binance SPOT FIX workflow areas with an async execution model, making it easier to run multiple sessions, compare feed behavior, and prototype Python FIX workflows.\n\n### Async Connector Advantages\n\n| Feature | Async Implementation | Benefit |\n|---------|---------------------|---------|\n| **Concurrent Sessions** | Native `asyncio` support | Run market data, order entry, and drop copy experiments together |\n| **Feed Research** | Shared async connector surface | Compare session behavior without changing execution model |\n| **Python Prototyping** | Built for Python 3.13+ | Fits notebooks, scripts, FastAPI, and asyncio research tooling |\n| **Latency Research** | Local operation-latency benchmark | Compare sync vs async overhead on the target host |\n| **Regression Checks** | Repeated benchmark rows | Track performance drift while changing parser/session code |\n\n### Original Library Advantages\n\n| Feature | Sync Implementation | Benefit |\n|---------|-------------------|---------|\n| **Single Session Performance** | Thread-based execution | Can be slightly faster in single-session throughput; validate locally |\n| **Simplicity** | Traditional blocking I/O | Easier to understand for sync-only developers |\n| **Ecosystem Maturity** | Longer production usage | More battle-tested in diverse environments |\n| **Thread Integration** | Native threading | Better integration with thread-based applications |\n\n### Performance Comparison\n\nThe benchmark suite supports local research and regression testing. It is reproducible by command, but the exact microbenchmark values are host- and run-dependent. It uses one warmup run, seven measured repeats, and writes median/min-max rows to `benchmark/analysis_results.md`:\n\n| Metric | Reproducible report row |\n|--------|-------------------------|\n| **Message Creation Speed** | Async vs sync message creation throughput |\n| **Memory Usage** | Async vs sync peak memory usage |\n| **Mean Operation Latency** | Async vs sync mean operation latency |\n\nRun `benchmark/comprehensive_analysis.py` on the target host before using benchmark numbers for comparisons. Treat the generated values as local measurements, not universal latency claims.\n\n### 🔄 Migration Path\n\n**Migration Scope:**\n\n- Async code must add `await` around session creation, send/receive, and cleanup calls.\n- Message construction and supported FIX fields are intended to stay close to the original connector where the public APIs overlap.\n- Both libraries can be installed side by side under different import names.\n\n**Migration Steps:**\n\n```python\n# 1. Install async version\npip install binance-fix-connector-async\n\n# 2. Update imports\nfrom binance_fix_connector_async.fix_connector import create_order_entry_session\n\n# 3. Add async/await keywords\nasync def main():\n    client = await create_order_entry_session(api_key, private_key)\n    await client.send_message(msg)\n    await client.logout()\n\n# 4. Run with asyncio\nasyncio.run(main())\n```\n\n### 📈 Validation Results\n\nThe benchmark suite supports:\n\n- **Local performance research**: repeated median/min-max checks for message creation speed, peak memory usage, and mean operation latency\n- **Consistency**: message construction and state-transition parity checks\n- **Compatibility**: supported public factory and connector methods\n\n**Run validation yourself:**\n\n```bash\ncd benchmark/\npython comprehensive_analysis.py\n```\n\n## Documentation\n\n### Benchmark and Research Notes\n\n- **[Benchmark Results](benchmark/README.md)** - Reproducible local benchmark and compatibility analysis\n- **Run Analysis**: `python benchmark/comprehensive_analysis.py`\n\n### Official Binance Documentation\n\n- **[Binance FIX API Documentation](https://developers.binance.com/docs/binance-spot-api-docs/fix-api)** - Official FIX API reference\n\n## Summary\n\nBoth libraries provide Binance SPOT FIX access with different execution models. Choose based on your workflow:\n\n- **Async**: Useful for concurrent testnet scripts, feed/session comparison, and async research workflows\n- **Official sync connector**: Better default choice for simple, single-session, thread-based applications\n\nValidate the real testnet examples and E2E runner with your own FIX key before using the async connector in production.\n\n## License\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FAlexanderMerkel%2Fbinance-fix-connector-python","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FAlexanderMerkel%2Fbinance-fix-connector-python","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FAlexanderMerkel%2Fbinance-fix-connector-python/lists"}