btcturk-global 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. btcturk_global-0.1.0/.dockerignore +11 -0
  2. btcturk_global-0.1.0/.env.example +11 -0
  3. btcturk_global-0.1.0/.github/workflows/publish.yml +42 -0
  4. btcturk_global-0.1.0/.gitignore +11 -0
  5. btcturk_global-0.1.0/AGENTS.md +133 -0
  6. btcturk_global-0.1.0/Dockerfile +23 -0
  7. btcturk_global-0.1.0/LICENSE +21 -0
  8. btcturk_global-0.1.0/PKG-INFO +221 -0
  9. btcturk_global-0.1.0/README.md +201 -0
  10. btcturk_global-0.1.0/pyproject.toml +46 -0
  11. btcturk_global-0.1.0/scripts/smoke.py +370 -0
  12. btcturk_global-0.1.0/src/btcturk_global/__init__.py +3 -0
  13. btcturk_global-0.1.0/src/btcturk_global/auth.py +106 -0
  14. btcturk_global-0.1.0/src/btcturk_global/client.py +435 -0
  15. btcturk_global-0.1.0/src/btcturk_global/config.py +64 -0
  16. btcturk_global-0.1.0/src/btcturk_global/errors.py +156 -0
  17. btcturk_global-0.1.0/src/btcturk_global/mcp_server.py +519 -0
  18. btcturk_global-0.1.0/src/btcturk_global/models/__init__.py +70 -0
  19. btcturk_global-0.1.0/src/btcturk_global/models/base.py +22 -0
  20. btcturk_global-0.1.0/src/btcturk_global/models/private.py +184 -0
  21. btcturk_global-0.1.0/src/btcturk_global/models/public.py +167 -0
  22. btcturk_global-0.1.0/src/btcturk_global/models/ws.py +179 -0
  23. btcturk_global-0.1.0/src/btcturk_global/orderbook.py +78 -0
  24. btcturk_global-0.1.0/src/btcturk_global/ratelimit.py +55 -0
  25. btcturk_global-0.1.0/src/btcturk_global/transport.py +133 -0
  26. btcturk_global-0.1.0/src/btcturk_global/ws.py +421 -0
  27. btcturk_global-0.1.0/tests/__init__.py +0 -0
  28. btcturk_global-0.1.0/tests/conftest.py +63 -0
  29. btcturk_global-0.1.0/tests/fakes.py +95 -0
  30. btcturk_global-0.1.0/tests/fixtures/all_orders.json +39 -0
  31. btcturk_global-0.1.0/tests/fixtures/balances.json +37 -0
  32. btcturk_global-0.1.0/tests/fixtures/crypto_channels.json +4 -0
  33. btcturk_global-0.1.0/tests/fixtures/crypto_transactions.json +22 -0
  34. btcturk_global-0.1.0/tests/fixtures/currencies.json +30 -0
  35. btcturk_global-0.1.0/tests/fixtures/currency_channels.json +14 -0
  36. btcturk_global-0.1.0/tests/fixtures/exchangeinfo.json +67 -0
  37. btcturk_global-0.1.0/tests/fixtures/open_orders.json +43 -0
  38. btcturk_global-0.1.0/tests/fixtures/orderbook.json +18 -0
  39. btcturk_global-0.1.0/tests/fixtures/pairs.json +13 -0
  40. btcturk_global-0.1.0/tests/fixtures/ticker.json +25 -0
  41. btcturk_global-0.1.0/tests/fixtures/trades.json +29 -0
  42. btcturk_global-0.1.0/tests/fixtures/user_trades.json +22 -0
  43. btcturk_global-0.1.0/tests/fixtures/withdrawals.json +24 -0
  44. btcturk_global-0.1.0/tests/live/__init__.py +0 -0
  45. btcturk_global-0.1.0/tests/live/test_live_public.py +91 -0
  46. btcturk_global-0.1.0/tests/test_auth.py +102 -0
  47. btcturk_global-0.1.0/tests/test_config.py +93 -0
  48. btcturk_global-0.1.0/tests/test_errors.py +88 -0
  49. btcturk_global-0.1.0/tests/test_mcp.py +277 -0
  50. btcturk_global-0.1.0/tests/test_orderbook.py +114 -0
  51. btcturk_global-0.1.0/tests/test_package.py +5 -0
  52. btcturk_global-0.1.0/tests/test_private.py +444 -0
  53. btcturk_global-0.1.0/tests/test_public.py +169 -0
  54. btcturk_global-0.1.0/tests/test_ratelimit.py +96 -0
  55. btcturk_global-0.1.0/tests/test_transport.py +234 -0
  56. btcturk_global-0.1.0/tests/test_ws.py +250 -0
  57. btcturk_global-0.1.0/uv.lock +1201 -0
@@ -0,0 +1,11 @@
1
+ .env
2
+ .env.*
3
+ !.env.example
4
+ .git
5
+ .venv
6
+ tests
7
+ **/__pycache__
8
+ **/*.pyc
9
+ .pytest_cache
10
+ Dockerfile
11
+ .dockerignore
@@ -0,0 +1,11 @@
1
+ # Copy to .env and fill in. Do not wrap values in quotes: `docker run --env-file`
2
+ # reads quotes literally, so they would become part of the key.
3
+ BTCTURK_API_KEY=
4
+ BTCTURK_API_SECRET=
5
+
6
+ # Optional: backward tolerance for X-Stamp in milliseconds (max 60000).
7
+ # BTCTURK_NONCE=
8
+
9
+ # MCP write tools, both off unless set to 1.
10
+ # BTCTURK_MCP_ALLOW_TRADING=1
11
+ # BTCTURK_MCP_ALLOW_WITHDRAWALS=1
@@ -0,0 +1,42 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+
7
+ permissions:
8
+ contents: read
9
+
10
+ jobs:
11
+ test:
12
+ runs-on: ubuntu-latest
13
+ steps:
14
+ - uses: actions/checkout@v4
15
+
16
+ - uses: astral-sh/setup-uv@v5
17
+ with:
18
+ enable-cache: true
19
+
20
+ - name: Install and test
21
+ run: |
22
+ uv sync --extra mcp --group dev
23
+ uv run pytest
24
+
25
+ publish:
26
+ needs: test
27
+ runs-on: ubuntu-latest
28
+ environment: release
29
+ # Job-level permissions replace workflow defaults; private repos need contents: read for checkout.
30
+ permissions:
31
+ contents: read
32
+ id-token: write
33
+ steps:
34
+ - uses: actions/checkout@v4
35
+
36
+ - uses: astral-sh/setup-uv@v5
37
+
38
+ - name: Build
39
+ run: uv build
40
+
41
+ - name: Publish to PyPI
42
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,11 @@
1
+ .env
2
+ .env.*
3
+ !.env.example
4
+ .venv/
5
+ __pycache__/
6
+ *.py[cod]
7
+ .pytest_cache/
8
+ *.egg-info/
9
+ build/
10
+ dist/
11
+ .DS_Store
@@ -0,0 +1,133 @@
1
+ # AGENTS.md
2
+
3
+ This file is for AI assistants working on behalf of a person who wants to install and use this project. That person may not be a developer. Write your replies in plain, step-by-step language, and keep them short. If you use a technical term, briefly explain it.
4
+
5
+ ## What this project does
6
+
7
+ It is a tool that connects to the BtcTurk Global exchange API. It reads live prices and order books. If an API key is provided, it can also read balances, orders and trade history. If the user chooses, it can place orders and request withdrawals too; both are off by default and only turned on when the user explicitly allows it.
8
+
9
+ ## Ask the user first
10
+
11
+ Before installing, ask the user for:
12
+
13
+ 1. Their BtcTurk Global API key (public key) and secret key. Do not make these up, guess them, or fill them with example values.
14
+ 2. What they want to do: only watch prices, view their balances and orders, or place orders?
15
+ 3. How to run it: directly on their computer, or in Docker?
16
+
17
+ Check what is available on the computer before you ask question 3, and only offer the options that can work:
18
+
19
+ - `uv --version` (for running directly on the computer)
20
+ - `docker info` (for Docker; it must print server information, otherwise Docker is installed but not running, or not installed)
21
+
22
+ If neither is available, tell the user what is missing and ask for permission to install one of them.
23
+
24
+ Use the keys only if the user gave them to you. Do not repeat, summarize or copy key values anywhere except the `.env` file.
25
+
26
+ ## Installation steps
27
+
28
+ All steps run from the project folder. Run `pwd` there to get its full path, you need it below.
29
+
30
+ ### Step 1: set up the `.env` file (both options)
31
+
32
+ 1. Copy `.env.example` to `.env`:
33
+ ```
34
+ cp .env.example .env
35
+ ```
36
+ 2. Open `.env` and write the keys the user gave you, in this format. Do not use quotation marks:
37
+ ```
38
+ BTCTURK_API_KEY=the_users_key
39
+ BTCTURK_API_SECRET=the_users_secret
40
+ ```
41
+
42
+ ### Step 2, option A: run directly on the computer (uv)
43
+
44
+ 1. Install the dependencies:
45
+ ```
46
+ uv sync --extra mcp
47
+ ```
48
+ 2. Give the user this `mcp.json` entry. Replace `/full/path/to/btcturk-global` with the real full path of the project folder (from `pwd`) and the `command` with the real full path of `uv` if the user's AI app cannot find it (`which uv` prints it):
49
+
50
+ ```json
51
+ {
52
+ "mcpServers": {
53
+ "btcturk-global": {
54
+ "command": "uv",
55
+ "args": ["--directory", "/full/path/to/btcturk-global", "run", "btcturk-global-mcp"]
56
+ }
57
+ }
58
+ }
59
+ ```
60
+
61
+ ### Step 2, option B: run with Docker
62
+
63
+ 1. Build the image:
64
+ ```
65
+ docker build -t btcturk-global-mcp .
66
+ ```
67
+ 2. Give the user this `mcp.json` entry. Replace `/full/path/to/btcturk-global/.env` with the real full path of the `.env` file (the project folder from `pwd`, then `/.env`):
68
+
69
+ ```json
70
+ {
71
+ "mcpServers": {
72
+ "btcturk-global-docker": {
73
+ "command": "docker",
74
+ "args": [
75
+ "run",
76
+ "--rm",
77
+ "-i",
78
+ "--init",
79
+ "--env-file",
80
+ "/full/path/to/btcturk-global/.env",
81
+ "btcturk-global-mcp"
82
+ ]
83
+ }
84
+ }
85
+ }
86
+ ```
87
+
88
+ Docker notes:
89
+
90
+ - The `--env-file` path must be a full path, not a relative one.
91
+ - Use `-i` but never `-t`; a terminal flag breaks the MCP connection.
92
+ - Docker Desktop must be running whenever the AI app uses the server.
93
+
94
+ ### Step 3: give the entry to the user and check it
95
+
96
+ - Replace every placeholder with the real value, so the user gets a finished entry and does not have to edit it. Never leave `/full/path/to/...` in what you hand over.
97
+ - Show the finished JSON to the user and explain where to paste it: the `mcpServers` section of the MCP configuration file of their AI app (for Cursor, `Settings > Tools & MCP`, or the file `~/.cursor/mcp.json`). Do not edit their configuration file yourself unless they ask you to.
98
+ - The entry has no keys in it. The server reads them from `.env`, so do not add an `env` section.
99
+ - Once the user has pasted it and restarted the app, check that it works: call `get_tickers` with `BTCUSDT`. If a price comes back, the setup is complete.
100
+
101
+ ## Available tools
102
+
103
+ Without a key, only the public tools work:
104
+
105
+ - **Market data:** `get_tickers`, `get_order_book`, `get_recent_trades`, `get_exchange_info`, `get_pairs`, `get_currencies`, `get_currency_channels`, `get_crypto_channels`
106
+ - **Live data:** `get_live_ticker`, `get_live_order_book`
107
+
108
+ With a key, these read-only tools are also available: `get_balances`, `get_open_orders`, `get_all_orders`, `get_order`, `get_trade_history`, `get_crypto_transactions`, `get_deposit_addresses`, `get_withdrawal_addresses`, `get_withdrawals`, `get_withdrawal`, `get_trade_volumes`.
109
+
110
+ Extra tools appear only when the user explicitly allows them (set in `.env`):
111
+
112
+ - `BTCTURK_MCP_ALLOW_TRADING=1` → `submit_order`, `cancel_order`, `cancel_orders` (placing and cancelling orders)
113
+ - `BTCTURK_MCP_ALLOW_WITHDRAWALS=1` → `create_withdrawal` (withdrawing funds)
114
+
115
+ ## Hard rules
116
+
117
+ - **Before placing an order or requesting a withdrawal**, write out every detail of the action (pair, buy/sell, amount, price, address and sum) for the user and get explicit approval. Do not call the tool without approval.
118
+ - **Do not turn on the trading or withdrawal flags unless the user asks.** Before turning one on, explain that it allows real transactions and ask for approval. Once the work is done, suggest turning it off again.
119
+ - **Never show, print, log, output or commit the secret key.**
120
+ - **Do not copy or share the `.env` file** to any other location.
121
+ - **Do not give definitive investment advice.** Share market data and point out the risks.
122
+ - **An "accepted" reply after placing an order does not mean the order was executed.** Check its status with `get_order` and tell the user the result.
123
+ - **If you get an error, explain the error `code` to the user.** Do not make decisions based on the error message text.
124
+
125
+ ## Troubleshooting
126
+
127
+ - **"uv not found":** `uv` is not installed. Ask the user for permission to install it, or offer the Docker option.
128
+ - **"Cannot connect to the Docker daemon" or `docker info` fails:** Docker Desktop is not running. Ask the user to start it.
129
+ - **"Unable to find image" (Docker):** The image was not built yet. Run `docker build -t btcturk-global-mcp .` from the project folder.
130
+ - **Tools do not appear:** If only the public tools are listed, the keys in `.env` are empty or wrapped in quotation marks. Remove the quotation marks.
131
+ - **`401` or "Invalid Nonce":** The computer's clock may be out of sync. Ask the user to sync the clock or restart Docker Desktop.
132
+ - **`429` (too many requests):** Wait a moment and reduce the number of requests.
133
+ - **Timeout:** If a timeout happens while placing an order, check with `get_open_orders` and `get_all_orders` whether the order was placed. You can search using the `client_id` from the error response. Do this before sending the order again.
@@ -0,0 +1,23 @@
1
+ # syntax=docker/dockerfile:1
2
+ FROM python:3.14-slim AS builder
3
+ COPY --from=ghcr.io/astral-sh/uv:0.12 /uv /usr/local/bin/uv
4
+ ENV UV_COMPILE_BYTECODE=1 \
5
+ UV_LINK_MODE=copy \
6
+ UV_PYTHON_DOWNLOADS=0
7
+ WORKDIR /app
8
+ COPY pyproject.toml uv.lock README.md ./
9
+ RUN --mount=type=cache,target=/root/.cache/uv \
10
+ uv sync --frozen --no-dev --extra mcp --no-install-project
11
+ COPY src ./src
12
+ RUN --mount=type=cache,target=/root/.cache/uv \
13
+ uv sync --frozen --no-dev --extra mcp --no-editable
14
+
15
+ FROM python:3.14-slim
16
+ ENV PYTHONUNBUFFERED=1 \
17
+ PATH="/app/.venv/bin:$PATH"
18
+ RUN useradd --create-home --uid 10001 app
19
+ COPY --from=builder --chown=app:app /app/.venv /app/.venv
20
+ USER app
21
+ WORKDIR /home/app
22
+ # stdio transport: run with `docker run -i` (no -t, a TTY corrupts the protocol stream).
23
+ ENTRYPOINT ["btcturk-global-mcp"]
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sinan Erdinç
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,221 @@
1
+ Metadata-Version: 2.5
2
+ Name: btcturk-global
3
+ Version: 0.1.0
4
+ Summary: Async Python client (REST + WebSocket) and MCP server for the BtcTurk Global API
5
+ Project-URL: Homepage, https://github.com/sinanerdinc/btcturk-global
6
+ Project-URL: Repository, https://github.com/sinanerdinc/btcturk-global
7
+ Project-URL: Issues, https://github.com/sinanerdinc/btcturk-global/issues
8
+ Author: Sinan Erdinç
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Requires-Python: >=3.11
12
+ Requires-Dist: httpx[http2]>=0.28
13
+ Requires-Dist: orjson>=3.10
14
+ Requires-Dist: pydantic<3,>=2.11
15
+ Requires-Dist: python-dotenv>=1.0
16
+ Requires-Dist: websockets>=14
17
+ Provides-Extra: mcp
18
+ Requires-Dist: mcp<3,>=2.3; extra == 'mcp'
19
+ Description-Content-Type: text/markdown
20
+
21
+ # btcturk-global
22
+
23
+ Async Python client (REST + WebSocket) and MCP server for the [BtcTurk Global API](https://docs.global.btcturk.com).
24
+
25
+ - `httpx` with HTTP/2 and a long-lived keep-alive connection pool.
26
+ - Pydantic v2 models; every price, amount and balance is a `Decimal` (never `float`).
27
+ - Client-side rate limiter matching the documented limits (3 requests / 500 ms, 60 requests / 10 s).
28
+ - WebSocket client with automatic reconnect, re-login, re-subscribe and a locally maintained order book.
29
+ - MCP server (stdio) with public, private, trading and withdrawal tools; write tools are off by default.
30
+
31
+ Requires Python 3.12+.
32
+
33
+ ## Install
34
+
35
+ ```bash
36
+ git clone <repo-url> btcturk-global
37
+ cd btcturk-global
38
+ uv sync # client only
39
+ uv sync --extra mcp # client + MCP server
40
+ ```
41
+
42
+ ## Credentials
43
+
44
+ Create API keys in BtcTurk Global and copy `.env.example` to `.env`:
45
+
46
+ ```dotenv
47
+ BTCTURK_API_KEY=your-public-key
48
+ BTCTURK_API_SECRET=your-private-key
49
+ # BTCTURK_NONCE=5000
50
+ ```
51
+
52
+ - Do not wrap values in quotes; quoted values are rejected with a clear error.
53
+ - `.env` is read from the current working directory; real environment variables win over `.env`.
54
+ - The secret is held as a `SecretStr` and never appears in logs, `repr` or tool output.
55
+ - Without credentials only public endpoints work.
56
+
57
+ ## REST client
58
+
59
+ ```python
60
+ import asyncio
61
+ from decimal import Decimal
62
+
63
+ from btcturk_global.client import BtcTurkClient
64
+
65
+
66
+ async def main() -> None:
67
+ # Reads BTCTURK_API_KEY / BTCTURK_API_SECRET from the environment or .env.
68
+ # Alternatively: BtcTurkClient(api_key="...", api_secret="...")
69
+ async with BtcTurkClient() as client:
70
+ tickers = await client.get_tickers("BTCUSDT")
71
+ print(tickers[0].last)
72
+
73
+ book = await client.get_orderbook("BTCUSDT", limit=10)
74
+ print(book.bids[0])
75
+
76
+ if client.has_credentials:
77
+ balances = await client.get_balances()
78
+ order = await client.submit_order(
79
+ "BTCUSDT", "buy", "limit", quantity=Decimal("0.001"), price=Decimal("50000")
80
+ )
81
+ print(order.id)
82
+
83
+
84
+ asyncio.run(main())
85
+ ```
86
+
87
+ Public methods: `get_exchange_info`, `get_tickers`, `get_tickers_by_currency`, `get_orderbook`, `get_trades`,
88
+ `get_pairs`, `get_currencies`, `get_currency_channels`, `get_crypto_channels`.
89
+
90
+ Private methods: `get_balances`, `get_trade_transactions`, `get_crypto_transactions`, `get_open_orders`,
91
+ `get_all_orders`, `get_order`, `submit_order`, `cancel_order`, `cancel_orders`, `get_deposit_addresses`,
92
+ `get_deposit_address`, `get_withdrawal_addresses`, `get_withdrawal_address`, `create_withdrawal`,
93
+ `get_withdrawals`, `get_withdrawal`, `get_trade_volumes`.
94
+
95
+ ### Behaviour worth knowing
96
+
97
+ - **Decimals.** Responses are parsed with `json.loads(parse_float=Decimal)`, so no precision is lost.
98
+ Order prices and quantities accept `Decimal`, `int` or `str`; `float` is rejected.
99
+ - **Errors.** All errors derive from `btcturk_global.errors.BtcTurkError`. API errors are `ApiError`
100
+ (with `status_code`, `code`, `message`); subclasses cover authentication (`AuthenticationError`),
101
+ rate limiting (`RateLimitError`), RFC 7807 problem documents (`ProblemError`) and per-field withdrawal
102
+ errors (`FieldValidationError`). Handle errors by `code`, not by message.
103
+ - **429.** Retried at most 2 times, and only when the server sends `Retry-After` of 5 seconds or less.
104
+ Otherwise `RateLimitError` is raised immediately.
105
+ - **No automatic retry on 5xx or connection errors.** A timeout raises `TransportError`. For
106
+ `submit_order` it carries the generated `client_id`, so you can look the order up before retrying.
107
+ - **Rate limiter is per process.** Other processes (or other machines behind the same IP) using the same
108
+ key share the server-side quota without knowing about each other.
109
+ - **Cancellation** means "accepted", not "applied"; confirm with `get_order`. `cancel_orders` returns
110
+ partial failures in `uncancelled_orders` instead of raising.
111
+ - **`BTCTURK_NONCE`** (1..60000 ms) is the window in which a signed request is valid. If your clock drifts
112
+ (common in Docker Desktop after the host sleeps) you will see `401 Invalid Nonce`; sync the clock or
113
+ restart Docker Desktop.
114
+
115
+ ## WebSocket client
116
+
117
+ ```python
118
+ import asyncio
119
+
120
+ from btcturk_global.ws import BtcTurkWebSocket
121
+
122
+
123
+ async def main() -> None:
124
+ async with BtcTurkWebSocket() as ws:
125
+ await ws.subscribe("ticker", "BTCUSDT")
126
+ await ws.subscribe_order_book("BTCUSDT")
127
+ await asyncio.sleep(2)
128
+
129
+ book = ws.order_book("BTCUSDT")
130
+ if book is not None and book.ready:
131
+ bids, asks = book.top(5)
132
+ print(bids[0], asks[0])
133
+
134
+ async for event in ws.events():
135
+ print(type(event).__name__)
136
+
137
+
138
+ asyncio.run(main())
139
+ ```
140
+
141
+ - Pass `signer=client.signer` to receive private events (balances, orders, user trades).
142
+ REST and WebSocket logins share one stamp sequence per API key, so signatures are never reused.
143
+ - On disconnect the client reconnects with jittered backoff, logs in again and re-sends every subscription.
144
+ A failed login is fatal and is raised from `wait_connected` / `events`.
145
+ - If a subscribed ticker stays silent for 5 seconds the connection is considered dead and reopened.
146
+ - The local order book buffers diffs until the snapshot arrives and resyncs itself on a change-set gap.
147
+ - The event queue is bounded (1000 by default); when it is full the oldest event is dropped and
148
+ `dropped_events` is incremented.
149
+
150
+ ## MCP server
151
+
152
+ ### Tools
153
+
154
+ | Group | Enabled when | Tools |
155
+ |-------|--------------|-------|
156
+ | Public | always | `get_tickers`, `get_order_book`, `get_recent_trades`, `get_exchange_info`, `get_pairs`, `get_currencies`, `get_currency_channels`, `get_crypto_channels`, `get_live_ticker`, `get_live_order_book` |
157
+ | Private (read-only) | API key and secret set | `get_balances`, `get_open_orders`, `get_all_orders`, `get_order`, `get_trade_history`, `get_crypto_transactions`, `get_deposit_addresses`, `get_withdrawal_addresses`, `get_withdrawals`, `get_withdrawal`, `get_trade_volumes` |
158
+ | Trading | credentials + `BTCTURK_MCP_ALLOW_TRADING=1` | `submit_order`, `cancel_order`, `cancel_orders` |
159
+ | Withdrawals | credentials + `BTCTURK_MCP_ALLOW_WITHDRAWALS=1` | `create_withdrawal` |
160
+
161
+ Flags are enabled only by the exact value `1`. The MCP server reads configuration from environment
162
+ variables only (and `.env` in its working directory).
163
+
164
+ The `get_live_*` tools open a single WebSocket lazily and keep up to 50 subscriptions (least recently used
165
+ pairs are dropped). Their output includes `received_at_ms` and `age_seconds`.
166
+
167
+ ### Run locally
168
+
169
+ ```bash
170
+ uv sync --extra mcp
171
+ uv run btcturk-global-mcp
172
+ ```
173
+
174
+ Cursor / Claude Desktop `mcp.json` (keys come from the project `.env`; do not put them in this file):
175
+
176
+ ```json
177
+ {
178
+ "mcpServers": {
179
+ "btcturk-global": {
180
+ "command": "uv",
181
+ "args": ["--directory", "/absolute/path/to/btcturk-global", "run", "btcturk-global-mcp"]
182
+ }
183
+ }
184
+ }
185
+ ```
186
+
187
+ ### Run with Docker
188
+
189
+ ```bash
190
+ git clone <repo-url> btcturk-global
191
+ cd btcturk-global
192
+ docker build -t btcturk-global-mcp .
193
+ docker run --rm -i --init --env-file /absolute/path/to/.env btcturk-global-mcp
194
+ ```
195
+
196
+ - Use `-i` but **not** `-t`: a TTY corrupts the stdio protocol stream.
197
+ - Use an absolute path for `--env-file`. Docker keeps quotes literally, so keep values unquoted.
198
+ - `.env` is excluded from the build context and never ends up in the image. The container runs as a
199
+ non-root user.
200
+
201
+ `mcp.json` for Docker:
202
+
203
+ ```json
204
+ {
205
+ "mcpServers": {
206
+ "btcturk-global": {
207
+ "command": "docker",
208
+ "args": ["run", "--rm", "-i", "--init", "--env-file", "/absolute/path/to/.env", "btcturk-global-mcp"]
209
+ }
210
+ }
211
+ }
212
+ ```
213
+
214
+ ## Tests
215
+
216
+ ```bash
217
+ uv run pytest # unit tests, no network access
218
+ BTCTURK_LIVE_TESTS=1 uv run pytest tests/live # opt-in smoke tests against public endpoints
219
+ ```
220
+
221
+ Live tests only call public endpoints; private and write endpoints are never tested live.
@@ -0,0 +1,201 @@
1
+ # btcturk-global
2
+
3
+ Async Python client (REST + WebSocket) and MCP server for the [BtcTurk Global API](https://docs.global.btcturk.com).
4
+
5
+ - `httpx` with HTTP/2 and a long-lived keep-alive connection pool.
6
+ - Pydantic v2 models; every price, amount and balance is a `Decimal` (never `float`).
7
+ - Client-side rate limiter matching the documented limits (3 requests / 500 ms, 60 requests / 10 s).
8
+ - WebSocket client with automatic reconnect, re-login, re-subscribe and a locally maintained order book.
9
+ - MCP server (stdio) with public, private, trading and withdrawal tools; write tools are off by default.
10
+
11
+ Requires Python 3.12+.
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ git clone <repo-url> btcturk-global
17
+ cd btcturk-global
18
+ uv sync # client only
19
+ uv sync --extra mcp # client + MCP server
20
+ ```
21
+
22
+ ## Credentials
23
+
24
+ Create API keys in BtcTurk Global and copy `.env.example` to `.env`:
25
+
26
+ ```dotenv
27
+ BTCTURK_API_KEY=your-public-key
28
+ BTCTURK_API_SECRET=your-private-key
29
+ # BTCTURK_NONCE=5000
30
+ ```
31
+
32
+ - Do not wrap values in quotes; quoted values are rejected with a clear error.
33
+ - `.env` is read from the current working directory; real environment variables win over `.env`.
34
+ - The secret is held as a `SecretStr` and never appears in logs, `repr` or tool output.
35
+ - Without credentials only public endpoints work.
36
+
37
+ ## REST client
38
+
39
+ ```python
40
+ import asyncio
41
+ from decimal import Decimal
42
+
43
+ from btcturk_global.client import BtcTurkClient
44
+
45
+
46
+ async def main() -> None:
47
+ # Reads BTCTURK_API_KEY / BTCTURK_API_SECRET from the environment or .env.
48
+ # Alternatively: BtcTurkClient(api_key="...", api_secret="...")
49
+ async with BtcTurkClient() as client:
50
+ tickers = await client.get_tickers("BTCUSDT")
51
+ print(tickers[0].last)
52
+
53
+ book = await client.get_orderbook("BTCUSDT", limit=10)
54
+ print(book.bids[0])
55
+
56
+ if client.has_credentials:
57
+ balances = await client.get_balances()
58
+ order = await client.submit_order(
59
+ "BTCUSDT", "buy", "limit", quantity=Decimal("0.001"), price=Decimal("50000")
60
+ )
61
+ print(order.id)
62
+
63
+
64
+ asyncio.run(main())
65
+ ```
66
+
67
+ Public methods: `get_exchange_info`, `get_tickers`, `get_tickers_by_currency`, `get_orderbook`, `get_trades`,
68
+ `get_pairs`, `get_currencies`, `get_currency_channels`, `get_crypto_channels`.
69
+
70
+ Private methods: `get_balances`, `get_trade_transactions`, `get_crypto_transactions`, `get_open_orders`,
71
+ `get_all_orders`, `get_order`, `submit_order`, `cancel_order`, `cancel_orders`, `get_deposit_addresses`,
72
+ `get_deposit_address`, `get_withdrawal_addresses`, `get_withdrawal_address`, `create_withdrawal`,
73
+ `get_withdrawals`, `get_withdrawal`, `get_trade_volumes`.
74
+
75
+ ### Behaviour worth knowing
76
+
77
+ - **Decimals.** Responses are parsed with `json.loads(parse_float=Decimal)`, so no precision is lost.
78
+ Order prices and quantities accept `Decimal`, `int` or `str`; `float` is rejected.
79
+ - **Errors.** All errors derive from `btcturk_global.errors.BtcTurkError`. API errors are `ApiError`
80
+ (with `status_code`, `code`, `message`); subclasses cover authentication (`AuthenticationError`),
81
+ rate limiting (`RateLimitError`), RFC 7807 problem documents (`ProblemError`) and per-field withdrawal
82
+ errors (`FieldValidationError`). Handle errors by `code`, not by message.
83
+ - **429.** Retried at most 2 times, and only when the server sends `Retry-After` of 5 seconds or less.
84
+ Otherwise `RateLimitError` is raised immediately.
85
+ - **No automatic retry on 5xx or connection errors.** A timeout raises `TransportError`. For
86
+ `submit_order` it carries the generated `client_id`, so you can look the order up before retrying.
87
+ - **Rate limiter is per process.** Other processes (or other machines behind the same IP) using the same
88
+ key share the server-side quota without knowing about each other.
89
+ - **Cancellation** means "accepted", not "applied"; confirm with `get_order`. `cancel_orders` returns
90
+ partial failures in `uncancelled_orders` instead of raising.
91
+ - **`BTCTURK_NONCE`** (1..60000 ms) is the window in which a signed request is valid. If your clock drifts
92
+ (common in Docker Desktop after the host sleeps) you will see `401 Invalid Nonce`; sync the clock or
93
+ restart Docker Desktop.
94
+
95
+ ## WebSocket client
96
+
97
+ ```python
98
+ import asyncio
99
+
100
+ from btcturk_global.ws import BtcTurkWebSocket
101
+
102
+
103
+ async def main() -> None:
104
+ async with BtcTurkWebSocket() as ws:
105
+ await ws.subscribe("ticker", "BTCUSDT")
106
+ await ws.subscribe_order_book("BTCUSDT")
107
+ await asyncio.sleep(2)
108
+
109
+ book = ws.order_book("BTCUSDT")
110
+ if book is not None and book.ready:
111
+ bids, asks = book.top(5)
112
+ print(bids[0], asks[0])
113
+
114
+ async for event in ws.events():
115
+ print(type(event).__name__)
116
+
117
+
118
+ asyncio.run(main())
119
+ ```
120
+
121
+ - Pass `signer=client.signer` to receive private events (balances, orders, user trades).
122
+ REST and WebSocket logins share one stamp sequence per API key, so signatures are never reused.
123
+ - On disconnect the client reconnects with jittered backoff, logs in again and re-sends every subscription.
124
+ A failed login is fatal and is raised from `wait_connected` / `events`.
125
+ - If a subscribed ticker stays silent for 5 seconds the connection is considered dead and reopened.
126
+ - The local order book buffers diffs until the snapshot arrives and resyncs itself on a change-set gap.
127
+ - The event queue is bounded (1000 by default); when it is full the oldest event is dropped and
128
+ `dropped_events` is incremented.
129
+
130
+ ## MCP server
131
+
132
+ ### Tools
133
+
134
+ | Group | Enabled when | Tools |
135
+ |-------|--------------|-------|
136
+ | Public | always | `get_tickers`, `get_order_book`, `get_recent_trades`, `get_exchange_info`, `get_pairs`, `get_currencies`, `get_currency_channels`, `get_crypto_channels`, `get_live_ticker`, `get_live_order_book` |
137
+ | Private (read-only) | API key and secret set | `get_balances`, `get_open_orders`, `get_all_orders`, `get_order`, `get_trade_history`, `get_crypto_transactions`, `get_deposit_addresses`, `get_withdrawal_addresses`, `get_withdrawals`, `get_withdrawal`, `get_trade_volumes` |
138
+ | Trading | credentials + `BTCTURK_MCP_ALLOW_TRADING=1` | `submit_order`, `cancel_order`, `cancel_orders` |
139
+ | Withdrawals | credentials + `BTCTURK_MCP_ALLOW_WITHDRAWALS=1` | `create_withdrawal` |
140
+
141
+ Flags are enabled only by the exact value `1`. The MCP server reads configuration from environment
142
+ variables only (and `.env` in its working directory).
143
+
144
+ The `get_live_*` tools open a single WebSocket lazily and keep up to 50 subscriptions (least recently used
145
+ pairs are dropped). Their output includes `received_at_ms` and `age_seconds`.
146
+
147
+ ### Run locally
148
+
149
+ ```bash
150
+ uv sync --extra mcp
151
+ uv run btcturk-global-mcp
152
+ ```
153
+
154
+ Cursor / Claude Desktop `mcp.json` (keys come from the project `.env`; do not put them in this file):
155
+
156
+ ```json
157
+ {
158
+ "mcpServers": {
159
+ "btcturk-global": {
160
+ "command": "uv",
161
+ "args": ["--directory", "/absolute/path/to/btcturk-global", "run", "btcturk-global-mcp"]
162
+ }
163
+ }
164
+ }
165
+ ```
166
+
167
+ ### Run with Docker
168
+
169
+ ```bash
170
+ git clone <repo-url> btcturk-global
171
+ cd btcturk-global
172
+ docker build -t btcturk-global-mcp .
173
+ docker run --rm -i --init --env-file /absolute/path/to/.env btcturk-global-mcp
174
+ ```
175
+
176
+ - Use `-i` but **not** `-t`: a TTY corrupts the stdio protocol stream.
177
+ - Use an absolute path for `--env-file`. Docker keeps quotes literally, so keep values unquoted.
178
+ - `.env` is excluded from the build context and never ends up in the image. The container runs as a
179
+ non-root user.
180
+
181
+ `mcp.json` for Docker:
182
+
183
+ ```json
184
+ {
185
+ "mcpServers": {
186
+ "btcturk-global": {
187
+ "command": "docker",
188
+ "args": ["run", "--rm", "-i", "--init", "--env-file", "/absolute/path/to/.env", "btcturk-global-mcp"]
189
+ }
190
+ }
191
+ }
192
+ ```
193
+
194
+ ## Tests
195
+
196
+ ```bash
197
+ uv run pytest # unit tests, no network access
198
+ BTCTURK_LIVE_TESTS=1 uv run pytest tests/live # opt-in smoke tests against public endpoints
199
+ ```
200
+
201
+ Live tests only call public endpoints; private and write endpoints are never tested live.