Examples
Example Client
This example will create a Websocket connection, subscribe to a price feed as well as fill and order updates, and place an order.
INFOThis example places a real order on the environment it connects to. It uses the sandbox (
env='sandbox'); do not point it at production.
Prices and amounts are sent as strings. Round the price to the instrument's price_precision (the number of decimal places, from Get Instruments). Orders are fill-or-kill: a buy priced at or above the market fills in full at the market price, and a buy priced below the market is canceled with error 10502. Requires zerocap-api 0.1.36 or later.
import time
import uuid
from zerocap_api import ZerocapRestClient, ZerocapWebsocketClient, ZerocapAPIError
api_key = ''
api_secret = ''
symbol = 'USDT/AUD'
amount = '10' # base-asset quantity, between the instrument's min_quantity and max_quantity
zc_rest = ZerocapRestClient(api_key, api_secret, env='sandbox')
zc_ws = ZerocapWebsocketClient(api_key, api_secret, env='sandbox')
instruments = {i['name']: i for i in zc_rest.get_instruments()['instruments']}
price_precision = int(instruments[symbol]['price_precision'])
stream = zc_ws.create_connection() # keep this generator and pass it to recv()
print(zc_ws.recv(stream)) # {'type': 'message', 'message': 'Successfully connected.'}
zc_ws.send({"type": "price", "symbols": [symbol]})
zc_ws.send({"type": "order"})
zc_ws.send({"type": "trade"})
client_order_id = str(uuid.uuid4())
order_sent = False
deadline = time.time() + 60 # give up if no price arrives within 60 seconds
try:
while time.time() < deadline:
message = zc_ws.recv(stream)
if message['type'] == 'error':
raise RuntimeError(message)
if message['type'] == 'price' and not order_sent:
best_ask = message['data']['asks'][0][0]
price = f"{best_ask * 1.001:.{price_precision}f}" # buy, accepting up to 0.1% above the best ask
try:
result = zc_rest.create_order(symbol=symbol, side='buy', type='limit', amount=amount,
price=price, client_order_id=client_order_id)
except ZerocapAPIError as e:
print("create_order failed", e.status_code, e.body)
break
print("create_order", result)
if 'error' in result: # refused by the trading engine (HTTP 200)
break
order_sent = True
deadline = time.time() + 10 # watch order and trade updates for 10 seconds
elif message['type'] in ('order', 'trade') and message['data']['client_order_id'] == client_order_id:
print(message['type'], message['data'])
finally:
zc_ws.close()Updated 23 days ago
Did this page help you?