From 648533bfe0d329ab4f3c1d92a8cebcc5abd8df09 Mon Sep 17 00:00:00 2001 From: cdm Date: Fri, 18 Nov 2022 16:02:58 +0000 Subject: [PATCH 01/33] Clean sample-api-scripts file structure for v2 data node support --- .gitignore | 1 + Pipfile | 13 - Pipfile.lock | 68 --- fees-margins-estimation/README.md | 39 -- ...s-margins-estimate-with-Vega-API-client.py | 134 ----- .../get-fees-margins-estimate.py | 140 ------ .../get-fees-margins-estimate.sh | 121 ----- fees-margins-estimation/response-examples.txt | 37 -- get-assets/get-asset-gql.sh | 45 -- get-assets/get-assets-gql.sh | 45 -- get-assets/get-assets.py | 71 --- get-assets/response-examples.txt | 45 -- get-by-reference/README.md | 44 -- .../get-order-by-reference-gql.sh | 51 -- ...order-by-reference-with-Vega-API-client.py | 41 -- get-by-reference/get-order-by-reference.py | 42 -- get-by-reference/get-order-by-reference.sh | 34 -- get-by-reference/response-examples.txt | 19 - get-markets-and-market-data/README.md | 48 -- .../get-markets-and-market-data-gql.sh | 101 ---- ...ets-and-marketdata-with-Vega-API-client.py | 47 -- .../get-markets-and-marketdata.py | 51 -- .../get-markets-and-marketdata.sh | 42 -- get-markets-and-market-data/get-markets.sh | 40 -- .../response-examples.txt | 127 ----- get-network-parameters/README.md | 43 -- .../get-network-parameters-gql.sh | 40 -- ...network-parameters-with-Vega-API-client.py | 46 -- .../get-network-parameters.py | 43 -- .../get-network-parameters.sh | 34 -- get-network-parameters/response-examples.txt | 22 - get-orders-and-trades/README.md | 57 --- ...-trades-for-market-with-Vega-API-client.py | 51 -- .../get-orders-and-trades-for-market.py | 55 --- .../get-orders-and-trades-for-market.sh | 45 -- ...d-trades-for-party-with-Vega-API-client.py | 95 ---- .../get-orders-and-trades-for-party.py | 90 ---- .../get-orders-and-trades-for-party.sh | 61 --- ...t-trades-for-order-with-Vega-API-client.py | 40 -- get-orders-and-trades/get-trades-for-order.py | 40 -- get-orders-and-trades/get-trades-for-order.sh | 32 -- get-orders-and-trades/response-examples.txt | 129 ----- get-statistics/README.md | 45 -- get-statistics/get-statistics-gql.sh | 49 -- .../get-statistics-with-Vega-API-client.py | 35 -- get-statistics/get-statistics.py | 37 -- get-statistics/get-statistics.sh | 30 -- .../Get-Market.graphql | 0 .../Get-Markets.graphql | 0 graphql/README.md | 0 {get-assets => graphql}/get-asset.graphql | 0 {get-assets => graphql}/get-assets.graphql | 0 .../get-network-parameters.graphql | 0 .../get-orderbyreference.graphql | 0 .../get-orders-and-trades-for-market.graphql | 0 .../get-orders-and-trades-for-party.graphql | 0 .../get-parties-accounts.graphql | 0 .../get-statistics.graphql | 0 .../get-trades-for-order.graphql | 0 .../get-vega-time.graphql | 0 .../stream-events.graphql | 0 .../stream-market-data.graphql | 0 .../stream-orders-by-reference.graphql | 0 .../stream-orders.graphql | 0 .../stream-trades.graphql | 0 helpers.py | 44 -- helpers.sh | 26 - parties-and-accounts/README.md | 53 -- .../get-accounts-with-Vega-API-client.py | 127 ----- parties-and-accounts/get-accounts.py | 124 ----- parties-and-accounts/get-accounts.sh | 104 ---- .../get-parties-with-Vega-API-client.py | 38 -- parties-and-accounts/get-parties.py | 54 -- parties-and-accounts/get-parties.sh | 34 -- parties-and-accounts/response-examples.txt | 109 ----- propose-freeform/README.md | 29 -- propose-freeform/party-has-proposed.py | 114 ----- .../propose-vote-enact-freeform.py | 288 ----------- propose-markets/README.md | 30 -- ...ropose-vote-enact-market-time-triggered.py | 453 ----------------- propose-markets/propose-vote-enact-market.py | 462 ------------------ propose-markets/response-examples.txt | 91 ---- propose-netparams/README.md | 29 -- .../propose-vote-enact-netparams.py | 321 ------------ propose-votes/README.md | 27 - propose-votes/manage-proposals-gql.sh | 145 ------ .../manage-proposals-with-Vega-API-client.py | 119 ----- propose-votes/manage-proposals.py | 124 ----- propose-votes/response-examples.txt | 65 --- rest/README.md | 0 set-env.ps1 | 9 - stream-events/README.md | 27 - stream-events/response-examples.txt | 45 -- .../stream-events-with-Vega-API-client.py | 70 --- stream-events/stream-events.sh | 136 ------ stream-marketdata/LICENSE | 31 -- stream-marketdata/README.md | 25 - stream-marketdata/stream-marketdata-gql.sh | 47 -- stream-marketdata/stream-marketdata.py | 85 ---- stream-orders-and-trades/README.md | 32 -- stream-orders-and-trades/stream-orders-gql.sh | 50 -- .../stream-orders-with-Vega-API-client.py | 59 --- stream-orders-and-trades/stream-trades-gql.sh | 47 -- .../stream-trades-with-Vega-API-client.py | 61 --- stream-orders-by-reference/README.md | 27 - .../stream-orders-with-Vega-API-client.py | 54 -- stream-orders-by-reference/stream-orders.sh | 30 -- submit-amend-cancel-orders/README.md | 44 -- .../response-examples.txt | 46 -- ...mend-cancel-orders-with-Vega-API-client.py | 279 ----------- .../submit-amend-cancel-orders.py | 294 ----------- .../submit-amend-cancel-orders.sh | 280 ----------- submit-amend-liquidity-provision/README.md | 40 -- .../response-examples.txt | 99 ---- ...ty-provision-order-with-Vega-API-client.py | 172 ------- .../submit-amend-liquidity-provision-order.py | 160 ------ .../submit-amend-liquidity-provision-order.sh | 250 ---------- submit-amend-pegged-order/README.md | 42 -- ...amend-pegged-order-with-Vega-API-client.py | 235 --------- .../submit-amend-pegged-order.py | 233 --------- .../submit-amend-pegged-order.sh | 217 -------- submit-cancel-liquidity-provision/README.md | 40 -- .../response-examples.txt | 99 ---- ...ty-provision-order-with-Vega-API-client.py | 157 ------ ...submit-cancel-liquidity-provision-order.py | 148 ------ ...submit-cancel-liquidity-provision-order.sh | 125 ----- submit-create-liquidity-provision/README.md | 40 -- .../response-examples.txt | 99 ---- ...ty-provision-order-with-Vega-API-client.py | 190 ------- ...submit-create-liquidity-provision-order.py | 180 ------- ...submit-create-liquidity-provision-order.sh | 156 ------ vega-time/README.md | 46 -- vega-time/get-time-gql.sh | 39 -- vega-time/get-time-with-Vega-API-client.py | 37 -- vega-time/get-time.py | 40 -- vega-time/get-time.sh | 31 -- vega-time/response-examples.txt | 6 - wallet/README.md | 44 -- wallet/response-examples.txt | 80 --- wallet/wallet.py | 138 ------ wallet/wallet.sh | 113 ----- 141 files changed, 1 insertion(+), 10608 deletions(-) delete mode 100644 Pipfile delete mode 100644 Pipfile.lock delete mode 100644 fees-margins-estimation/README.md delete mode 100644 fees-margins-estimation/get-fees-margins-estimate-with-Vega-API-client.py delete mode 100644 fees-margins-estimation/get-fees-margins-estimate.py delete mode 100755 fees-margins-estimation/get-fees-margins-estimate.sh delete mode 100644 fees-margins-estimation/response-examples.txt delete mode 100644 get-assets/get-asset-gql.sh delete mode 100644 get-assets/get-assets-gql.sh delete mode 100644 get-assets/get-assets.py delete mode 100644 get-assets/response-examples.txt delete mode 100644 get-by-reference/README.md delete mode 100644 get-by-reference/get-order-by-reference-gql.sh delete mode 100644 get-by-reference/get-order-by-reference-with-Vega-API-client.py delete mode 100644 get-by-reference/get-order-by-reference.py delete mode 100755 get-by-reference/get-order-by-reference.sh delete mode 100644 get-by-reference/response-examples.txt delete mode 100644 get-markets-and-market-data/README.md delete mode 100644 get-markets-and-market-data/get-markets-and-market-data-gql.sh delete mode 100644 get-markets-and-market-data/get-markets-and-marketdata-with-Vega-API-client.py delete mode 100644 get-markets-and-market-data/get-markets-and-marketdata.py delete mode 100755 get-markets-and-market-data/get-markets-and-marketdata.sh delete mode 100644 get-markets-and-market-data/get-markets.sh delete mode 100644 get-markets-and-market-data/response-examples.txt delete mode 100644 get-network-parameters/README.md delete mode 100644 get-network-parameters/get-network-parameters-gql.sh delete mode 100644 get-network-parameters/get-network-parameters-with-Vega-API-client.py delete mode 100644 get-network-parameters/get-network-parameters.py delete mode 100755 get-network-parameters/get-network-parameters.sh delete mode 100644 get-network-parameters/response-examples.txt delete mode 100644 get-orders-and-trades/README.md delete mode 100644 get-orders-and-trades/get-orders-and-trades-for-market-with-Vega-API-client.py delete mode 100644 get-orders-and-trades/get-orders-and-trades-for-market.py delete mode 100755 get-orders-and-trades/get-orders-and-trades-for-market.sh delete mode 100644 get-orders-and-trades/get-orders-and-trades-for-party-with-Vega-API-client.py delete mode 100644 get-orders-and-trades/get-orders-and-trades-for-party.py delete mode 100755 get-orders-and-trades/get-orders-and-trades-for-party.sh delete mode 100644 get-orders-and-trades/get-trades-for-order-with-Vega-API-client.py delete mode 100644 get-orders-and-trades/get-trades-for-order.py delete mode 100755 get-orders-and-trades/get-trades-for-order.sh delete mode 100644 get-orders-and-trades/response-examples.txt delete mode 100644 get-statistics/README.md delete mode 100644 get-statistics/get-statistics-gql.sh delete mode 100644 get-statistics/get-statistics-with-Vega-API-client.py delete mode 100644 get-statistics/get-statistics.py delete mode 100755 get-statistics/get-statistics.sh rename {get-markets-and-market-data => graphql}/Get-Market.graphql (100%) rename {get-markets-and-market-data => graphql}/Get-Markets.graphql (100%) create mode 100644 graphql/README.md rename {get-assets => graphql}/get-asset.graphql (100%) rename {get-assets => graphql}/get-assets.graphql (100%) rename get-network-parameters/Get-NetworkParameters.graphql => graphql/get-network-parameters.graphql (100%) rename {get-by-reference => graphql}/get-orderbyreference.graphql (100%) rename {get-orders-and-trades => graphql}/get-orders-and-trades-for-market.graphql (100%) rename {get-orders-and-trades => graphql}/get-orders-and-trades-for-party.graphql (100%) rename parties-and-accounts/GetPartirsAccounts.graphql => graphql/get-parties-accounts.graphql (100%) rename {get-statistics => graphql}/get-statistics.graphql (100%) rename {get-orders-and-trades => graphql}/get-trades-for-order.graphql (100%) rename vega-time/Get-VegaTime.graphql => graphql/get-vega-time.graphql (100%) rename {stream-events => graphql}/stream-events.graphql (100%) rename stream-marketdata/stream-marketdata.graphql => graphql/stream-market-data.graphql (100%) rename stream-orders-by-reference/stream-ordersbyreference.graphql => graphql/stream-orders-by-reference.graphql (100%) rename {stream-orders-and-trades => graphql}/stream-orders.graphql (100%) rename {stream-orders-and-trades => graphql}/stream-trades.graphql (100%) delete mode 100644 helpers.py delete mode 100644 helpers.sh delete mode 100644 parties-and-accounts/README.md delete mode 100755 parties-and-accounts/get-accounts-with-Vega-API-client.py delete mode 100755 parties-and-accounts/get-accounts.py delete mode 100755 parties-and-accounts/get-accounts.sh delete mode 100755 parties-and-accounts/get-parties-with-Vega-API-client.py delete mode 100755 parties-and-accounts/get-parties.py delete mode 100755 parties-and-accounts/get-parties.sh delete mode 100644 parties-and-accounts/response-examples.txt delete mode 100644 propose-freeform/README.md delete mode 100644 propose-freeform/party-has-proposed.py delete mode 100644 propose-freeform/propose-vote-enact-freeform.py delete mode 100644 propose-markets/README.md delete mode 100644 propose-markets/propose-vote-enact-market-time-triggered.py delete mode 100644 propose-markets/propose-vote-enact-market.py delete mode 100644 propose-markets/response-examples.txt delete mode 100644 propose-netparams/README.md delete mode 100644 propose-netparams/propose-vote-enact-netparams.py delete mode 100644 propose-votes/README.md delete mode 100755 propose-votes/manage-proposals-gql.sh delete mode 100755 propose-votes/manage-proposals-with-Vega-API-client.py delete mode 100644 propose-votes/manage-proposals.py delete mode 100644 propose-votes/response-examples.txt create mode 100644 rest/README.md delete mode 100644 set-env.ps1 delete mode 100644 stream-events/README.md delete mode 100644 stream-events/response-examples.txt delete mode 100644 stream-events/stream-events-with-Vega-API-client.py delete mode 100755 stream-events/stream-events.sh delete mode 100644 stream-marketdata/LICENSE delete mode 100644 stream-marketdata/README.md delete mode 100644 stream-marketdata/stream-marketdata-gql.sh delete mode 100644 stream-marketdata/stream-marketdata.py delete mode 100644 stream-orders-and-trades/README.md delete mode 100644 stream-orders-and-trades/stream-orders-gql.sh delete mode 100644 stream-orders-and-trades/stream-orders-with-Vega-API-client.py delete mode 100644 stream-orders-and-trades/stream-trades-gql.sh delete mode 100644 stream-orders-and-trades/stream-trades-with-Vega-API-client.py delete mode 100644 stream-orders-by-reference/README.md delete mode 100644 stream-orders-by-reference/stream-orders-with-Vega-API-client.py delete mode 100755 stream-orders-by-reference/stream-orders.sh delete mode 100644 submit-amend-cancel-orders/README.md delete mode 100644 submit-amend-cancel-orders/response-examples.txt delete mode 100644 submit-amend-cancel-orders/submit-amend-cancel-orders-with-Vega-API-client.py delete mode 100644 submit-amend-cancel-orders/submit-amend-cancel-orders.py delete mode 100755 submit-amend-cancel-orders/submit-amend-cancel-orders.sh delete mode 100644 submit-amend-liquidity-provision/README.md delete mode 100644 submit-amend-liquidity-provision/response-examples.txt delete mode 100644 submit-amend-liquidity-provision/submit-amend-liquidity-provision-order-with-Vega-API-client.py delete mode 100644 submit-amend-liquidity-provision/submit-amend-liquidity-provision-order.py delete mode 100755 submit-amend-liquidity-provision/submit-amend-liquidity-provision-order.sh delete mode 100644 submit-amend-pegged-order/README.md delete mode 100644 submit-amend-pegged-order/submit-amend-pegged-order-with-Vega-API-client.py delete mode 100644 submit-amend-pegged-order/submit-amend-pegged-order.py delete mode 100755 submit-amend-pegged-order/submit-amend-pegged-order.sh delete mode 100644 submit-cancel-liquidity-provision/README.md delete mode 100644 submit-cancel-liquidity-provision/response-examples.txt delete mode 100644 submit-cancel-liquidity-provision/submit-cancel-liquidity-provision-order-with-Vega-API-client.py delete mode 100644 submit-cancel-liquidity-provision/submit-cancel-liquidity-provision-order.py delete mode 100755 submit-cancel-liquidity-provision/submit-cancel-liquidity-provision-order.sh delete mode 100644 submit-create-liquidity-provision/README.md delete mode 100644 submit-create-liquidity-provision/response-examples.txt delete mode 100644 submit-create-liquidity-provision/submit-create-liquidity-provision-order-with-Vega-API-client.py delete mode 100644 submit-create-liquidity-provision/submit-create-liquidity-provision-order.py delete mode 100755 submit-create-liquidity-provision/submit-create-liquidity-provision-order.sh delete mode 100644 vega-time/README.md delete mode 100644 vega-time/get-time-gql.sh delete mode 100755 vega-time/get-time-with-Vega-API-client.py delete mode 100755 vega-time/get-time.py delete mode 100755 vega-time/get-time.sh delete mode 100644 vega-time/response-examples.txt delete mode 100644 wallet/README.md delete mode 100644 wallet/response-examples.txt delete mode 100644 wallet/wallet.py delete mode 100755 wallet/wallet.sh diff --git a/.gitignore b/.gitignore index df4e59c..ef83220 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ credentials.* *.tmp .idea .DS_Store +token.temp diff --git a/Pipfile b/Pipfile deleted file mode 100644 index 3c1d5e7..0000000 --- a/Pipfile +++ /dev/null @@ -1,13 +0,0 @@ -[[source]] -url = "https://pypi.python.org/simple" -verify_ssl = true -name = "pypi" - -[packages] -requests = "==2.27.1" -websocket-client = "==1.3.2" - -[dev-packages] - -[requires] -python_version = "3.8" diff --git a/Pipfile.lock b/Pipfile.lock deleted file mode 100644 index 2ba3dc6..0000000 --- a/Pipfile.lock +++ /dev/null @@ -1,68 +0,0 @@ -{ - "_meta": { - "hash": { - "sha256": "9708a5448a49df35a9d289ba8857f35ba9dfb7ead1e7071355e4ac34f5c35aa0" - }, - "pipfile-spec": 6, - "requires": { - "python_version": "3.8" - }, - "sources": [ - { - "name": "pypi", - "url": "https://pypi.python.org/simple", - "verify_ssl": true - } - ] - }, - "default": { - "certifi": { - "hashes": [ - "sha256:78884e7c1d4b00ce3cea67b44566851c4343c120abd683433ce934a68ea58872", - "sha256:d62a0163eb4c2344ac042ab2bdf75399a71a2d8c7d47eac2e2ee91b9d6339569" - ], - "version": "==2021.10.8" - }, - "charset-normalizer": { - "hashes": [ - "sha256:2857e29ff0d34db842cd7ca3230549d1a697f96ee6d3fb071cfa6c7393832597", - "sha256:6881edbebdb17b39b4eaaa821b438bf6eddffb4468cf344f09f89def34a8b1df" - ], - "markers": "python_version >= '3'", - "version": "==2.0.12" - }, - "idna": { - "hashes": [ - "sha256:84d9dd047ffa80596e0f246e2eab0b391788b0503584e8945f2368256d2735ff", - "sha256:9d643ff0a55b762d5cdb124b8eaa99c66322e2157b69160bc32796e824360e6d" - ], - "markers": "python_version >= '3'", - "version": "==3.3" - }, - "requests": { - "hashes": [ - "sha256:68d7c56fd5a8999887728ef304a6d12edc7be74f1cfa47714fc8b414525c9a61", - "sha256:f22fa1e554c9ddfd16e6e41ac79759e17be9e492b3587efa038054674760e72d" - ], - "index": "pypi", - "version": "==2.27.1" - }, - "urllib3": { - "hashes": [ - "sha256:44ece4d53fb1706f667c9bd1c648f5469a2ec925fcf3a776667042d645472c14", - "sha256:aabaf16477806a5e1dd19aa41f8c2b7950dd3c746362d7e3223dbe6de6ac448e" - ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4' and python_version < '4'", - "version": "==1.26.9" - }, - "websocket-client": { - "hashes": [ - "sha256:50b21db0058f7a953d67cc0445be4b948d7fc196ecbeb8083d68d94628e4abf6", - "sha256:722b171be00f2b90e1d4fb2f2b53146a536ca38db1da8ff49c972a4e1365d0ef" - ], - "index": "pypi", - "version": "==1.3.2" - } - }, - "develop": {} -} diff --git a/fees-margins-estimation/README.md b/fees-margins-estimation/README.md deleted file mode 100644 index 7717211..0000000 --- a/fees-margins-estimation/README.md +++ /dev/null @@ -1,39 +0,0 @@ -[![Gitpod ready-to-code](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/vegaprotocol/sample-api-scripts) - -# Sample API scripts - Estimate fees and margins - -These scripts perform the following actions: - -- Calculate the estimated fees for an order on Vega -- Calculate the estimated margins for an order on Vega - -Please see the documentation on Vega for further information. - -## Shell + curl - -Calculate estimated trading fees and margin using shell scripts and `curl` only [REST API]: - -```bash -bash fees-margins-estimation/get-fees-margins-estimate.sh -``` - -## Python + requests - -Calculate estimated trading fees and margin using python3 and the [requests](https://pypi.org/project/requests/) library [REST API]: - -```bash -python3 fees-margins-estimation/get-fees-margins-estimate.py -``` - -## Python + Vega-API-client - -Calculate estimated trading fees and margin python3 and the [Vega-API-client](https://pypi.org/project/Vega-API-client/) library [gRPC API]: - -```bash -python3 fees-margins-estimation/get-fees-margins-estimate-with-Vega-API-client.py -``` - ---- - -**[Home](../README.md)** - diff --git a/fees-margins-estimation/get-fees-margins-estimate-with-Vega-API-client.py b/fees-margins-estimation/get-fees-margins-estimate-with-Vega-API-client.py deleted file mode 100644 index 9723e2d..0000000 --- a/fees-margins-estimation/get-fees-margins-estimate-with-Vega-API-client.py +++ /dev/null @@ -1,134 +0,0 @@ -#!/usr/bin/python3 - -""" -Script language: Python3 - -Talks to: -- Vega node (gRPC) - -Apps/Libraries: -- gRPC: Vega-API-client (https://pypi.org/project/Vega-API-client/) -""" - -# Note: this file uses smart-tags in comments to section parts of the code to -# show them as snippets in our documentation. They are not necessary to be -# included when creating your own custom code. -# -# Example of smart-tags: -# __something: -# some code here -# :something__ - -import os -import requests -import helpers - -node_url_grpc = os.getenv("NODE_URL_GRPC") -if not helpers.check_var(node_url_grpc): - print("Error: Invalid or missing NODE_URL_GRPC environment variable.") - exit(1) - -wallet_server_url = os.getenv("WALLETSERVER_URL") -if not helpers.check_url(wallet_server_url): - print("Error: Invalid or missing WALLETSERVER_URL environment variable.") - exit(1) - -wallet_name = os.getenv("WALLET_NAME") -if not helpers.check_var(wallet_name): - print("Error: Invalid or missing WALLET_NAME environment variable.") - exit(1) - -wallet_passphrase = os.getenv("WALLET_PASSPHRASE") -if not helpers.check_var(wallet_passphrase): - print("Error: Invalid or missing WALLET_PASSPHRASE environment variable.") - exit(1) - -# Help guide users against including api version suffix on url -wallet_server_url = helpers.check_wallet_url(wallet_server_url) - -# __import_client: -import vegaapiclient as vac - -# Vega gRPC clients for reading/writing data -data_client = vac.VegaTradingDataClient(node_url_grpc) -# :import_client__ - -##################################################################################### -# W A L L E T S E R V I C E # -##################################################################################### - -print(f"Logging into wallet: {wallet_name}") - -# Log in to an existing wallet -req = {"wallet": wallet_name, "passphrase": wallet_passphrase} -response = requests.post(f"{wallet_server_url}/api/v1/auth/token", json=req) -helpers.check_response(response) -token = response.json()["token"] - -assert token != "" -print("Logged in to wallet successfully") - -# List key pairs and select public key to use -headers = {"Authorization": f"Bearer {token}"} -response = requests.get(f"{wallet_server_url}/api/v1/keys", headers=headers) -helpers.check_response(response) -keys = response.json()["keys"] -pubkey = keys[0]["pub"] - -assert pubkey != "" -print("Selected pubkey for signing") - -##################################################################################### -# F I N D M A R K E T # -##################################################################################### - -# __get_market: -# Request the identifier for the market to place on -markets = data_client.Markets(vac.data_node.api.v1.trading_data.MarketsRequest()).markets -marketID = markets[0].id -# :get_market__ - -assert marketID != "" -print(f"Market found: {marketID}") - -##################################################################################### -# F E E E S T I M A T I O N # -##################################################################################### - -# __get_fees_estimate: -# Request to estimate trading fees on a Vega network -estimate = vac.data_node.api.v1.trading_data.EstimateFeeRequest( - order=vac.vega.vega.Order( - market_id=marketID, - party_id=pubkey, - price="100000", - size=100, - side=vac.vega.vega.Side.SIDE_BUY, - time_in_force=vac.vega.vega.Order.TimeInForce.TIME_IN_FORCE_GTC, - type=vac.vega.vega.Order.Type.TYPE_LIMIT, - ) -) -estimated_fees = data_client.EstimateFee(estimate) -print("FeeEstimates:\n{}".format(estimated_fees)) -# :get_fees_estimate__ - -##################################################################################### -# M A R G I N E S T I M A T I O N # -##################################################################################### - -# __get_margins_estimate: -# Request to estimate trading margin on a Vega network -estimate = vac.data_node.api.v1.trading_data.EstimateMarginRequest( - order=vac.vega.vega.Order( - market_id=marketID, - party_id=pubkey, - price="600000", - size=10, - side=vac.vega.vega.Side.SIDE_BUY, - time_in_force=vac.vega.vega.Order.TimeInForce.TIME_IN_FORCE_GTC, - type=vac.vega.vega.Order.Type.TYPE_LIMIT, - ) -) -estimated_margins = data_client.EstimateMargin(estimate) -print("MarginEstimates:\n{}".format(estimated_margins)) -# :get_margins_estimate__ diff --git a/fees-margins-estimation/get-fees-margins-estimate.py b/fees-margins-estimation/get-fees-margins-estimate.py deleted file mode 100644 index 881d069..0000000 --- a/fees-margins-estimation/get-fees-margins-estimate.py +++ /dev/null @@ -1,140 +0,0 @@ -#!/usr/bin/python3 - -""" -Script language: Python3 - -Talks to: -- Vega node (REST) - -Apps/Libraries: -- REST: requests (https://pypi.org/project/requests/) -""" - -# Note: this file uses smart-tags in comments to section parts of the code to -# show them as snippets in our documentation. They are not necessary to be -# included when creating your own custom code. -# -# Example of smart-tags: -# __something: -# some code here -# :something__ - -import json -import requests -import os -import helpers - -node_url_rest = os.getenv("NODE_URL_REST") -if not helpers.check_url(node_url_rest): - print("Error: Invalid or missing NODE_URL_REST environment variable.") - exit(1) - -wallet_server_url = os.getenv("WALLETSERVER_URL") -if not helpers.check_url(wallet_server_url): - print("Error: Invalid or missing WALLETSERVER_URL environment variable.") - exit(1) - -wallet_name = os.getenv("WALLET_NAME") -if not helpers.check_var(wallet_name): - print("Error: Invalid or missing WALLET_NAME environment variable.") - exit(1) - -wallet_passphrase = os.getenv("WALLET_PASSPHRASE") -if not helpers.check_var(wallet_passphrase): - print("Error: Invalid or missing WALLET_PASSPHRASE environment variable.") - exit(1) - -# Help guide users against including api version suffix on url -wallet_server_url = helpers.check_wallet_url(wallet_server_url) - -##################################################################################### -# W A L L E T S E R V I C E # -##################################################################################### - -print(f"Logging into wallet: {wallet_name}") - -# Log in to an existing wallet -req = {"wallet": wallet_name, "passphrase": wallet_passphrase} -response = requests.post(f"{wallet_server_url}/api/v1/auth/token", json=req) -helpers.check_response(response) -token = response.json()["token"] - -assert token != "" -print("Logged in to wallet successfully") - -# List key pairs and select public key to use -headers = {"Authorization": f"Bearer {token}"} -response = requests.get(f"{wallet_server_url}/api/v1/keys", headers=headers) -helpers.check_response(response) -keys = response.json()["keys"] -pubkey = keys[0]["pub"] - -assert pubkey != "" -print("Selected pubkey for signing") - -##################################################################################### -# F I N D M A R K E T # -##################################################################################### - -# __get_market: -# Request the identifier for the market to place on -url = f"{node_url_rest}/markets" -response = requests.get(url) -helpers.check_response(response) -marketID = response.json()["markets"][0]["id"] -# :get_market__ - -assert marketID != "" -print(f"Market found: {marketID}") - -##################################################################################### -# F E E E S T I M A T I O N # -##################################################################################### - -# __get_fees_estimate: -# Request to estimate trading fees on a Vega network -req = { - "order": { - "marketId": marketID, - "partyId": pubkey, - "price": "100000", - "size": "100", - "side": "SIDE_BUY", - "timeInForce": "TIME_IN_FORCE_GTC", - "type": "TYPE_LIMIT", - } -} -print(json.dumps(req, indent=2, sort_keys=True)) -url = f"{node_url_rest}/orders/fee/estimate" -response = requests.post(url, json=req) -helpers.check_response(response) -estimatedFees = response.json() -print("FeeEstimates:\n{}".format( - json.dumps(estimatedFees, indent=2, sort_keys=True))) -# :get_fees_estimate__ - -##################################################################################### -# M A R G I N E S T I M A T I O N # -##################################################################################### - -# __get_margins_estimate: -# Request to estimate trading margin on a Vega network -req = { - "order": { - "marketId": marketID, - "partyId": pubkey, - "price": "600000", - "size": "10", - "side": "SIDE_BUY", - "timeInForce": "TIME_IN_FORCE_GTC", - "type": "TYPE_LIMIT", - } -} -print(json.dumps(req, indent=2, sort_keys=True)) -url = f"{node_url_rest}/orders/margins/estimate" -response = requests.post(url, json=req) -helpers.check_response(response) -estimatedMargin = response.json() -print("MarginsEstimate:\n{}".format( - json.dumps(estimatedMargin, indent=2, sort_keys=True))) -# :get_margins_estimate__ diff --git a/fees-margins-estimation/get-fees-margins-estimate.sh b/fees-margins-estimation/get-fees-margins-estimate.sh deleted file mode 100755 index 6c53191..0000000 --- a/fees-margins-estimation/get-fees-margins-estimate.sh +++ /dev/null @@ -1,121 +0,0 @@ -#!/usr/bin/env bash - -# Script language: bash -# -# Talks to: -# - Vega node (REST) -# -# Apps/Libraries: -# - REST: curl - -# Note: this file uses smart-tags in comments to section parts of the code to -# show them as snippets in our documentation. They are not necessary to be -# included when creating your own custom code. -# -# Example of smart-tags: -# __something: -# some code here -# :something__ - -source helpers.sh - -check_url "NODE_URL_REST" || exit 1 -check_url "WALLETSERVER_URL" || exit 1 - -check_var "WALLET_NAME" || exit 1 -check_var "WALLET_PASSPHRASE" || exit 1 - -##################################################################################### -# W A L L E T S E R V I C E # -##################################################################################### - -echo "Logging into wallet: $WALLET_NAME" - -# __login_wallet: -# Log in to an existing wallet -req='{"wallet": "'"$WALLET_NAME"'","passphrase": "'"$WALLET_PASSPHRASE"'"}' -url="$WALLETSERVER_URL/api/v1/auth/token" -response="$(curl -s -XPOST -d "$req" "$url")" -token="$(echo "$response" | jq -r .token)" -# :login_wallet__ - -test "$token" == null && exit 1 -echo "Logged in to wallet successfully" - -# __get_pubkey: -# List key pairs and select public key to use -hdr="Authorization: Bearer $token" -url="$WALLETSERVER_URL/api/v1/keys" -response="$(curl -s -XGET -H "$hdr" "$url")" -pubKey="$(echo "$response" | jq -r '.keys[0].pub')" -# :get_pubkey__ - -test -n "$pubKey" || exit 1 -test "$pubKey" == null && exit 1 -echo "Selected pubkey for signing" - -##################################################################################### -# F I N D M A R K E T # -##################################################################################### - -# __get_market: -# Request the identifier for the market to place on -url="$NODE_URL_REST/markets" -response="$(curl -s "$url")" -marketID="$(echo "$response" | jq -r '.markets[0].id')" -# :get_market__ - -echo "Market found: $marketID" - -##################################################################################### -# F E E E S T I M A T I O N # -##################################################################################### - -# __get_fees_estimate: -# Request to estimate trading fees on a Vega network -cat >req.json <req.json <query <query <query <query <query <query <query < 0 -pubKey = keys[0]["pub"] -# :find_keypair__ - -assert pubKey != "" - -# __get_orders_for_party: -# Request a list of orders by party (pubKey) -url = "{base}/parties/{party}/orders".format(base=node_url_rest, party=pubKey) -response = requests.get(url) -helpers.check_response(response) -response_json = response.json() -print("OrdersByParty:\n{}".format(json.dumps(response_json, indent=2, sort_keys=True))) -# :get_orders_for_party__ - -# __get_trades_for_party: -# Request a list of trades by party (pubKey) -url = "{base}/parties/{party}/trades".format(base=node_url_rest, party=pubKey) -response = requests.get(url) -helpers.check_response(response) -response_json = response.json() -print("TradesByParty:\n{}".format(json.dumps(response_json, indent=2, sort_keys=True))) -# :get_trades_for_party__ diff --git a/get-orders-and-trades/get-orders-and-trades-for-party.sh b/get-orders-and-trades/get-orders-and-trades-for-party.sh deleted file mode 100755 index 2a429ce..0000000 --- a/get-orders-and-trades/get-orders-and-trades-for-party.sh +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env bash - -# Script language: bash -# -# Talks to: -# - Vega wallet (REST) -# - Vega node (REST) -# -# Apps/Libraries: -# - REST: curl - -# Note: this file uses smart-tags in comments to section parts of the code to -# show them as snippets in our documentation. They are not necessary to be -# included when creating your own custom code. -# -# Example of smart-tags: -# __something: -# some code here -# :something__ - -source helpers.sh - -check_url "NODE_URL_REST" || exit 1 -check_url "WALLETSERVER_URL" || exit 1 -check_var "WALLET_NAME" || exit 1 -check_var "WALLET_PASSPHRASE" || exit 1 - -# Log in to wallet -req='{"wallet": "'"$WALLET_NAME"'","passphrase": "'"$WALLET_PASSPHRASE"'"}' -url="$WALLETSERVER_URL/api/v1/auth/token" -response="$(curl -s -XPOST -d "$req" "$url")" -token="$(echo "$response" | jq -r .token)" -echo $response - -# Get first key pair -test "$token" == null && exit 1 -hdr="Authorization: Bearer $token" -url="$WALLETSERVER_URL/api/v1/keys" -response="$(curl -s -XGET -H "$hdr" "$url")" -pubKey="$(echo "$response" | jq -r '.keys[0].pub')" -echo $response - -# __get_orders_for_party: -# Request a list of orders by party (pubKey) -url="$NODE_URL_REST/parties/$pubKey/orders" -response="$(curl -s "$url")" -echo $response -orders="$(echo "$response" | jq -r .orders)" -echo "OrdersByParty: -$orders" -# :get_orders_for_party__ - -# __get_trades_for_party: -# Request a list of trades by party (pubKey) -url="$NODE_URL_REST/parties/$pubKey/trades" -response="$(curl -s "$url")" -echo $response -trades="$(echo "$response" | jq -r .trades)" -echo "TradesByParty: -$trades" -# :get_trades_for_party__ \ No newline at end of file diff --git a/get-orders-and-trades/get-trades-for-order-with-Vega-API-client.py b/get-orders-and-trades/get-trades-for-order-with-Vega-API-client.py deleted file mode 100644 index 2f20745..0000000 --- a/get-orders-and-trades/get-trades-for-order-with-Vega-API-client.py +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/python3 - -""" -Script language: Python3 - -Talks to: -- Vega node (gRPC) - -Apps/Libraries: -- Vega-API-client (https://pypi.org/project/Vega-API-client/) -""" - -# Note: this file uses smart-tags in comments to section parts of the code to -# show them as snippets in our documentation. They are not necessary to be -# included when creating your own custom code. -# -# Example of smart-tags: -# __something: -# some code here -# :something__ - -import os - -node_url_grpc = os.getenv("NODE_URL_GRPC") - -# __import_client: -import vegaapiclient as vac -data_client = vac.VegaTradingDataClient(node_url_grpc) -# :import_client__ - -# __get_trades_for_order: -# Request a list of trades for a specific order on a Vega network -order_id = "V0000929211-0046318720" -trades_by_order_request = vac.data_node.api.v1.trading_data.TradesByOrderRequest( - # Note: orderID has capitalised ID in TradesByOrderRequest - order_id=order_id -) -trades_response = data_client.TradesByOrder(trades_by_order_request) -print("TradesByOrderID:\n{}".format(trades_response)) -# :get_trades_for_order__ diff --git a/get-orders-and-trades/get-trades-for-order.py b/get-orders-and-trades/get-trades-for-order.py deleted file mode 100644 index fb91f43..0000000 --- a/get-orders-and-trades/get-trades-for-order.py +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/python3 - -""" -Script language: Python3 - -Talks to: -- Vega node (REST) - -Apps/Libraries: -- REST: requests (https://pypi.org/project/requests/) -""" - -# Note: this file uses smart-tags in comments to section parts of the code to -# show them as snippets in our documentation. They are not necessary to be -# included when creating your own custom code. -# -# Example of smart-tags: -# __something: -# some code here -# :something__ - -import json -import os -import requests -import helpers - -node_url_rest = os.getenv("NODE_URL_REST") -if not helpers.check_url(node_url_rest): - print("Error: Invalid or missing NODE_URL_REST environment variable.") - exit(1) - -# __get_trades_for_order: -# Request a list of trades for a specific order on a Vega network -orderID = "V0000929211-0046318720" -url = "{base}/orders/{orderID}/trades".format(base=node_url_rest, orderID=orderID) -response = requests.get(url) -helpers.check_response(response) -responseJson = response.json() -print("TradesByOrderID:\n{}".format(json.dumps(responseJson, indent=2, sort_keys=True))) -# :get_trades_for_order__ diff --git a/get-orders-and-trades/get-trades-for-order.sh b/get-orders-and-trades/get-trades-for-order.sh deleted file mode 100755 index d8fa45d..0000000 --- a/get-orders-and-trades/get-trades-for-order.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env bash - -# Script language: bash -# -# Talks to: -# - Vega node (REST) -# -# Apps/Libraries: -# - REST: curl - -# Note: this file uses smart-tags in comments to section parts of the code to -# show them as snippets in our documentation. They are not necessary to be -# included when creating your own custom code. -# -# Example of smart-tags: -# __something: -# some code here -# :something__ - -source helpers.sh - -check_url "NODE_URL_REST" || exit 1 - -# __get_trades_for_order: -# Request a list of trades for a specific order on a Vega network -orderID="V0000929211-0046318720" -url="$NODE_URL_REST/orders/$orderID/trades" -response="$(curl -s "$url")" -trades="$(echo "$response" | jq -r .trades)" -echo "TradesByOrderID: -$trades" -# :get_trades_for_order__ \ No newline at end of file diff --git a/get-orders-and-trades/response-examples.txt b/get-orders-and-trades/response-examples.txt deleted file mode 100644 index 9a2b346..0000000 --- a/get-orders-and-trades/response-examples.txt +++ /dev/null @@ -1,129 +0,0 @@ -### __example_get_orders_for_market_response: -# Response for a list of orders by market on a Vega network -{ - "orders": [ - { - "batchId": "0", - "createdAt": "1600787450760093039", - "expiresAt": "1600788350594784506", - "id": "V0000847866-0042253452", - "marketId": "LBXRA65PN4FN5HBWRI2YBCOYDG2PBGYU", - "partyId": "c8e71b495736122977e56428341fa8fc8b1c39bdd76336869a3ab49274c9cf22", - "price": "128588", - "reason": "ORDER_ERROR_NONE", - "reference": "6ae0679b-b4b9-4a31-82ef-cbca7a38e436", - "remaining": "2503", - "side": "SIDE_BUY", - "size": "2503", - "status": "STATUS_ACTIVE", - "timeInForce": "TIME_IN_FORCE_GTT", - "type": "TYPE_LIMIT", - "updatedAt": "0", - "version": "1" - }, - ... - ] -} -# Note: some fields/records have been omitted to improve readability -### :example_get_orders_for_market_response__ - -### __example_get_orders_for_party_response: -# Response for a list of orders by party (public key) on a Vega network -{ - "orders": [ - { - "batchId": "0", - "createdAt": "1600787450760093039", - "expiresAt": "1600788350594784506", - "id": "V0000847866-0042253452", - "marketId": "LBXRA65PN4FN5HBWRI2YBCOYDG2PBGYU", - "partyId": "c8e71b495736122977e56428341fa8fc8b1c39bdd76336869a3ab49274c9cf22", - "price": "128588", - "reason": "ORDER_ERROR_NONE", - "reference": "6ae0679b-b4b9-4a31-82ef-cbca7a38e436", - "remaining": "2503", - "side": "SIDE_BUY", - "size": "2503", - "status": "STATUS_ACTIVE", - "timeInForce": "TIME_IN_FORCE_GTT", - "type": "TYPE_LIMIT", - "updatedAt": "0", - "version": "1" - }, - ... - ] -} -# Note: some fields/records have been omitted to improve readability -### :example_get_orders_for_party_response__ - - -### __example_get_trades_for_order_response: -# Response for a list of trades by a specific order on a Vega network -{ - "trades": [ - { - "aggressor": "SIDE_SELL", - "buyOrder": "V0000929211-0046318720", - "buyer": "ac9d9fe2e5904308d9c0f6fe758f8a4f4dd9636ab35584f95909010b7ec7edc9", - "buyerAuctionBatch": "0", - "buyerFee": { - "infrastructureFee": "0", - "liquidityFee": "0", - "makerFee": "0" - }, - "id": "V0000929226-0046319448-0000000001", - "marketId": "RTJVFCMFZZQQLLYVSXTWEN62P6AH6OCN", - "price": "3230", - "sellOrder": "V0000929226-0046319448", - "seller": "c210a614a93c4859feb4c963f07f3e7556d5ffb333a397fc512917cb28d79925", - "sellerAuctionBatch": "0", - "sellerFee": { - "infrastructureFee": "33", - "liquidityFee": "65", - "makerFee": "17" - }, - "size": "20", - "timestamp": "1600855316508081490", - "type": "TYPE_DEFAULT" - }, - ... - ] -} -# Note: some fields/records have been omitted to improve readability -### :example_get_trades_for_order_response__ - - -### __example_get_trades_for_market_response: -# Response for a list of trades by market on a Vega network -{ - "trades": [ - { - "aggressor": "SIDE_BUY", - "buyOrder": "V0000847867-0042253516", - "buyer": "e445f32a61ee4f554151ab9e33ed10bf60bfab71de4095f09303ef9f99ce4caf", - "buyerAuctionBatch": "0", - "buyerFee": { - "infrastructureFee": "37963", - "liquidityFee": "75926", - "makerFee": "18982" - }, - "id": "V0000847867-0042253516-0000000001", - "marketId": "LBXRA65PN4FN5HBWRI2YBCOYDG2PBGYU", - "price": "128687", - "sellOrder": "V0000847867-0042253504", - "seller": "1b7afb77e09e5134f2bfb35a5bb6c658ea709b90fb3404ae9c1abbbf1e20fccc", - "sellerAuctionBatch": "0", - "sellerFee": { - "infrastructureFee": "0", - "liquidityFee": "0", - "makerFee": "0" - }, - "size": "590", - "timestamp": "1600787451589210295", - "type": "TYPE_DEFAULT" - }, - ... - ] -} -# Note: some fields/records have been omitted to improve readability -### :example_get_trades_for_market_response__ diff --git a/get-statistics/README.md b/get-statistics/README.md deleted file mode 100644 index 22ef258..0000000 --- a/get-statistics/README.md +++ /dev/null @@ -1,45 +0,0 @@ -[![Gitpod ready-to-code](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/vegaprotocol/sample-api-scripts) - -# Sample API scripts - Vega statistics - -These scripts talk to a Vega node and get the latest statistics. -Please see the documentation on Vega for further information. - -## Shell + curl - -Get the latest statistics using shell scripts and `curl` only [REST API]: - -```bash -bash get-statistics/get-statistics.sh -``` - -## Python + requests - -Get the latest statistics using python3 and the [requests](https://pypi.org/project/requests/) library [REST API]: - -```bash -python3 get-statistics/get-statistics.py -``` - -## Python + Vega-API-client - -Get the latest statistics using python3 and the [Vega-API-client](https://pypi.org/project/Vega-API-client/) library [gRPC API]: - -```bash -python3 get-statistics/get-statistics-with-Vega-API-client.py -``` - -## GraphQL -[![Graphql - Get-Statistics](https://img.shields.io/badge/Graphql-Get--Statistics-2ea44f?logo=GraphQL)](https://www.graphqlbin.com/v2/g8LlIm) - -Get the latest statistics using shell scripts and [graphqurl](https://github.com/hasura/graphqurl) only [GraphQL API]: - -```bash -bash get-statistics/get-statistics-gql.sh -``` - - ---- - -**[Home](../README.md)** - diff --git a/get-statistics/get-statistics-gql.sh b/get-statistics/get-statistics-gql.sh deleted file mode 100644 index 2fcf49c..0000000 --- a/get-statistics/get-statistics-gql.sh +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env bash - -# Script language: bash - -# Talks to: -# - Vega node (GraphQL) -# -# Apps/Libraries: -# - GraphQL: graphqurl (https://github.com/hasura/graphqurl) -# - REST: curl - -# Note: this file uses smart-tags in comments to section parts of the code to -# show them as snippets in our documentation. They are not necessary to be -# included when creating your own custom code. -# -# Example of smart-tags: -# __something: -# some code here -# :something__ -# - -source helpers.sh -check_url "NODE_URL_GRAPHQL" || exit 1 - -##################################################################################### -# GET STATISTICS # -##################################################################################### - -# __get_statistics: -# Request the statistics for a node on Vega -cat >query < None: - assert ( - r.status_code == 200 - ), f"{r.url} returned HTTP {r.status_code} {r.text}" - - -def check_var(val: Union[str, None]) -> bool: - return val is not None and val != "" and "example" not in val - - -def check_url(url: str) -> bool: - return check_var(url) and ( - url.startswith("localhost:") or url.startswith("https://") or url.startswith("http://") - ) - - -def random_string(length: int = 20) -> str: - choices = string.ascii_letters + string.digits - return "".join(random.choice(choices) for i in range(length)) - - -def check_wallet_url(url: str) -> str: - for suffix in ["/api/v1/", "/api/v1", "/"]: - if url.endswith(suffix): - print( - f'There\'s no need to add "{suffix}" to WALLETSERVER_URL. ' - "Removing it." - ) - url = url[: -len(suffix)] - return url - - -def enum_to_str(e: Any, val: int) -> str: - return e.keys()[e.values().index(val)] - - -def generate_id(n :int) -> str: - return ''.join(random.choices(string.ascii_lowercase + (2 * string.digits), k=n)) diff --git a/helpers.sh b/helpers.sh deleted file mode 100644 index 374aa38..0000000 --- a/helpers.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env bash - -GQL_HEADER="-H content-type: application/json" - -check_var() { - var_name="$1" - var_value="${!var_name}" - if [[ -z "$var_value" ]] ; then - echo "Invalid $var_name - empty" - return 1 - fi - if echo "$var_value" | grep -q example ; then - echo "Invalid $var_name - contains \"example\"" - return 1 - fi -} - -check_url() { - var_name="$1" - check_var "$var_name" || return 1 - var_value="${!var_name}" - if ! echo "$var_value" | grep -qE '^http[s]?://' ; then - echo "Invalid $var_name - does not start with \"http://\" or \"https://\"" - return 1 - fi -} diff --git a/parties-and-accounts/README.md b/parties-and-accounts/README.md deleted file mode 100644 index 58863a5..0000000 --- a/parties-and-accounts/README.md +++ /dev/null @@ -1,53 +0,0 @@ -[![Gitpod ready-to-code](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/vegaprotocol/sample-api-scripts) - -# Sample API scripts - List Parties - -These scripts perform the following actions: - -- Get a list of parties on Vega -- Get a party for a given identifier (pubkey) -- Get a list of accounts for a market on Vega -- Get a list of accounts for a party on Vega - -Please see the documentation on Vega for further information. - -## Shell + curl - -Get parties and accounts on Vega using shell scripts and `curl` only [REST API]: - -```bash -bash parties-and-accounts/get-parties.sh -``` - -```bash -bash parties-and-accounts/get-accounts.sh -``` - -## Python + requests - -Get parties and accounts on Vega using python3 and the [requests](https://pypi.org/project/requests/) library [REST API]: - -```bash -python3 parties-and-accounts/get-parties.py -``` - -```bash -python3 parties-and-accounts/get-accounts.py -``` - -## Python + Vega-API-client - -Get parties and accounts on Vega using python3 and the [Vega-API-client](https://pypi.org/project/Vega-API-client/) library [gRPC API]: - -```bash -python3 parties-and-accounts/get-parties-with-Vega-API-client.py -``` - -```bash -python3 parties-and-accounts/get-accounts-with-Vega-API-client.py -``` - ---- - -**[Home](../README.md)** - diff --git a/parties-and-accounts/get-accounts-with-Vega-API-client.py b/parties-and-accounts/get-accounts-with-Vega-API-client.py deleted file mode 100755 index f8c4ce7..0000000 --- a/parties-and-accounts/get-accounts-with-Vega-API-client.py +++ /dev/null @@ -1,127 +0,0 @@ -#!/usr/bin/python3 - -""" -Script language: Python3 - -Talks to: -- Vega node (gRPC) - -Apps/Libraries: -- Vega-API-client (https://pypi.org/project/Vega-API-client/) - -Responses: -- response-examples.txt -""" - -# Note: this file uses smart-tags in comments to section parts of the code to -# show them as snippets in our documentation. They are not necessary to be -# included when creating your own custom code. -# -# Example of smart-tags: -# __something: -# some code here -# :something__ - -import requests -import helpers -import os - -node_url_grpc = os.getenv("NODE_URL_GRPC") -if not helpers.check_var(node_url_grpc): - print("Error: Invalid or missing NODE_URL_GRPC environment variable.") - exit(1) - -wallet_server_url = os.getenv("WALLETSERVER_URL") -if not helpers.check_url(wallet_server_url): - print("Error: Invalid or missing WALLETSERVER_URL environment variable.") - exit(1) - -wallet_name = os.getenv("WALLET_NAME") -if not helpers.check_var(wallet_name): - print("Error: Invalid or missing WALLET_NAME environment variable.") - exit(1) - -wallet_passphrase = os.getenv("WALLET_PASSPHRASE") -if not helpers.check_var(wallet_passphrase): - print("Error: Invalid or missing WALLET_PASSPHRASE environment variable.") - exit(1) - -# Help guide users against including api version suffix on url -wallet_server_url = helpers.check_wallet_url(wallet_server_url) - -# __import_client: -import vegaapiclient as vac - -# Vega gRPC clients for reading/writing data -data_client = vac.VegaTradingDataClient(node_url_grpc) -# :import_client__ - -##################################################################################### -# W A L L E T S E R V I C E # -##################################################################################### - -print(f"Logging into wallet: {wallet_name}") - -# __login_wallet: -# Log in to an existing wallet -req = {"wallet": wallet_name, "passphrase": wallet_passphrase} -response = requests.post(f"{wallet_server_url}/api/v1/auth/token", json=req) -helpers.check_response(response) -token = response.json()["token"] -# :login_wallet__ - -assert token != "" -print("Logged in to wallet successfully") - -# __get_pubkey: -# List key pairs and select public key to use -headers = {"Authorization": f"Bearer {token}"} -response = requests.get(f"{wallet_server_url}/api/v1/keys", headers=headers) -helpers.check_response(response) -keys = response.json()["keys"] -pubkey = keys[0]["pub"] -# :get_pubkey__ - -assert pubkey != "" -print("Selected pubkey for signing") - -##################################################################################### -# M A R K E T A C C O U N T S # -##################################################################################### - -# Request a list of markets and select the first one -req = vac.data_node.api.v1.trading_data.MarketsRequest() -markets = data_client.Markets(req).markets -marketID = markets[0].id - -assert marketID != "" -print(f"Market found: {marketID}") - -# __get_accounts_by_market: -# Request a list of accounts for a market on a Vega network -request = vac.data_node.api.v1.trading_data.MarketAccountsRequest(market_id=marketID) -market_accounts = data_client.MarketAccounts(request) -print("Market accounts:\n{}".format(market_accounts)) -# :get_accounts_by_market__ - -##################################################################################### -# P A R T Y A C C O U N T S # -##################################################################################### - -# __get_accounts_by_party: -# Request a list of accounts for a party (pubkey) on a Vega network -request = vac.data_node.api.v1.trading_data.PartyAccountsRequest(party_id=pubkey) -party_accounts = data_client.PartyAccounts(request) -print("Party accounts:\n{}".format(party_accounts)) -# :get_accounts_by_party__ - -##################################################################################### -# P A R T Y P O S I T I O N S # -##################################################################################### - -# __get_positions_by_party: -# Request a list of positions for a party (pubkey) on a Vega network -request = vac.data_node.api.v1.trading_data.PositionsByPartyRequest(party_id=pubkey) -party_positions = data_client.PositionsByParty(request) -print("Party positions:\n{}".format(party_positions)) -# :get_positions_by_party__ diff --git a/parties-and-accounts/get-accounts.py b/parties-and-accounts/get-accounts.py deleted file mode 100755 index 4028d69..0000000 --- a/parties-and-accounts/get-accounts.py +++ /dev/null @@ -1,124 +0,0 @@ -#!/usr/bin/python3 - -""" -Script language: Python3 - -Talks to: -- Vega node (REST) - -Apps/Libraries: -- REST: requests (https://pypi.org/project/requests/) - -Responses: -- response-examples.txt -""" - -# Note: this file uses smart-tags in comments to section parts of the code to -# show them as snippets in our documentation. They are not necessary to be -# included when creating your own custom code. -# -# Example of smart-tags: -# __something: -# some code here -# :something__ - -import json -import requests -import os -import helpers - -node_url_rest = os.getenv("NODE_URL_REST") -if not helpers.check_url(node_url_rest): - print("Error: Invalid or missing NODE_URL_REST environment variable.") - exit(1) - -wallet_server_url = os.getenv("WALLETSERVER_URL") -if not helpers.check_url(wallet_server_url): - print("Error: Invalid or missing WALLETSERVER_URL environment variable.") - exit(1) - -wallet_name = os.getenv("WALLET_NAME") -if not helpers.check_var(wallet_name): - print("Error: Invalid or missing WALLET_NAME environment variable.") - exit(1) - -wallet_passphrase = os.getenv("WALLET_PASSPHRASE") -if not helpers.check_var(wallet_passphrase): - print("Error: Invalid or missing WALLET_PASSPHRASE environment variable.") - exit(1) - -# Help guide users against including api version suffix on url -wallet_server_url = helpers.check_wallet_url(wallet_server_url) - -##################################################################################### -# W A L L E T S E R V I C E # -##################################################################################### - -print(f"Logging into wallet: {wallet_name}") - -# Log in to an existing wallet -req = {"wallet": wallet_name, "passphrase": wallet_passphrase} -response = requests.post(f"{wallet_server_url}/api/v1/auth/token", json=req) -helpers.check_response(response) -token = response.json()["token"] - -assert token != "" -print("Logged in to wallet successfully") - -# List key pairs and select public key to use -headers = {"Authorization": f"Bearer {token}"} -response = requests.get(f"{wallet_server_url}/api/v1/keys", headers=headers) -helpers.check_response(response) -keys = response.json()["keys"] -pubkey = keys[0]["pub"] - -assert pubkey != "" -print("Selected pubkey for signing") - -##################################################################################### -# M A R K E T A C C O U N T S # -##################################################################################### - -# Request a list of markets and select the first one -url = f"{node_url_rest}/markets" -response = requests.get(url) -helpers.check_response(response) -marketID = response.json()["markets"][0]["id"] - -assert marketID != "" -print(f"Market found: {marketID}") - -# __get_accounts_by_market: -# Request a list of accounts for a market on a Vega network -url = f"{node_url_rest}/markets/{marketID}/accounts" -response = requests.get(url) -helpers.check_response(response) -response_json = response.json() -print("Market accounts:\n{}".format(json.dumps(response_json, indent=2, sort_keys=True))) -# :get_accounts_by_market__ - -##################################################################################### -# P A R T Y A C C O U N T S # -##################################################################################### - -# __get_accounts_by_party: -# Request a list of accounts for a party (pubkey) on a Vega network -url = f"{node_url_rest}/parties/{pubkey}/accounts" -response = requests.get(url) -helpers.check_response(response) -response_json = response.json() -print("Party accounts:\n{}".format(json.dumps(response_json, indent=2, sort_keys=True))) -# :get_accounts_by_party__ - -##################################################################################### -# P A R T Y P O S I T I O N S # -##################################################################################### - -# __get_positions_by_party: -# Request a list of positions for a party (pubkey) on a Vega network -url = f"{node_url_rest}/parties/{pubkey}/positions" -response = requests.get(url) -helpers.check_response(response) -response_json = response.json() -print("Party positions:\n{}".format(json.dumps(response_json, indent=2, sort_keys=True))) -# :get_positions_by_party__ diff --git a/parties-and-accounts/get-accounts.sh b/parties-and-accounts/get-accounts.sh deleted file mode 100755 index 1272d0d..0000000 --- a/parties-and-accounts/get-accounts.sh +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env bash - -# Script language: bash - -# Talks to: -# - Vega wallet (REST) -# - Vega node (REST) -# -# Apps/Libraries: -# - REST: curl - -# Note: this file uses smart-tags in comments to section parts of the code to -# show them as snippets in our documentation. They are not necessary to be -# included when creating your own custom code. -# -# Example of smart-tags: -# __something: -# some code here -# :something__ -# - -source helpers.sh - -check_url "NODE_URL_REST" || exit 1 -check_url "WALLETSERVER_URL" || exit 1 - -check_var "WALLET_NAME" || exit 1 -check_var "WALLET_PASSPHRASE" || exit 1 - -##################################################################################### -# W A L L E T S E R V I C E # -##################################################################################### - -echo "Logging into wallet: $WALLET_NAME" - -# __login_wallet: -# Log in to an existing wallet -req='{"wallet": "'"$WALLET_NAME"'","passphrase": "'"$WALLET_PASSPHRASE"'"}' -url="$WALLETSERVER_URL/api/v1/auth/token" -response="$(curl -s -XPOST -d "$req" "$url")" -token="$(echo "$response" | jq -r .token)" -# :login_wallet__ - -test "$token" == null && exit 1 -echo "Logged in to wallet successfully" - -# __get_pubkey: -# List key pairs and select public key to use -hdr="Authorization: Bearer $token" -url="$WALLETSERVER_URL/api/v1/keys" -response="$(curl -s -XGET -H "$hdr" "$url")" -pubkey="$(echo "$response" | jq -r '.keys[0].pub')" -# :get_pubkey__ - -test -n "$pubkey" || exit 1 -test "$pubkey" == null && exit 1 -echo "Selected pubkey for signing" - -##################################################################################### -# M A R K E T A C C O U N T S # -##################################################################################### - -# Request a list of markets and select the first one -url="$NODE_URL_REST/markets" -response="$(curl -s "$url")" -marketID="$(echo "$response" | jq -r '.markets[0].id')" -# :get_market__ - -echo "Market found: $marketID" - -# __get_accounts_by_market: -# Request a list of accounts for a market on a Vega network -url="$NODE_URL_REST/markets/$marketID/accounts" -response="$(curl -s "$url")" -accounts="$(echo "$response" | jq -r .accounts)" -echo "Market accounts: -$accounts" -# :get_accounts_by_market__ - -##################################################################################### -# P A R T Y A C C O U N T S # -##################################################################################### - -# __get_accounts_by_party: -# Request a list of accounts for a party (pubkey) on a Vega network -url="$NODE_URL_REST/parties/$pubkey/accounts" -response="$(curl -s "$url")" -accounts="$(echo "$response" | jq -r .accounts)" -echo "Party accounts: -$accounts" -# :get_accounts_by_party__ - -##################################################################################### -# P A R T Y P O S I T I O N S # -##################################################################################### - -# __get_positions_by_party: -# Request a list of positions for a party (pubkey) on a Vega network -url="$NODE_URL_REST/parties/$pubkey/positions" -response="$(curl -s "$url")" -positions="$(echo "$response" | jq -r .positions)" -echo "Party positions: -$positions" -# :get_positions_by_party__ diff --git a/parties-and-accounts/get-parties-with-Vega-API-client.py b/parties-and-accounts/get-parties-with-Vega-API-client.py deleted file mode 100755 index c1549b0..0000000 --- a/parties-and-accounts/get-parties-with-Vega-API-client.py +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/python3 - -""" -Script language: Python3 - -Talks to: -- Vega node (gRPC) - -Apps/Libraries: -- Vega-API-client (https://pypi.org/project/Vega-API-client/) - -Responses: -- response-examples.txt -""" - -# Note: this file uses smart-tags in comments to section parts of the code to -# show them as snippets in our documentation. They are not necessary to be -# included when creating your own custom code. -# -# Example of smart-tags: -# __something: -# some code here -# :something__ - -import os -# __import_client: -import vegaapiclient as vac -# :import_client__ - -node_url_grpc = os.getenv("NODE_URL_GRPC") - -# __get_parties: -# Request a list of parties trading on a Vega network -data_client = vac.VegaTradingDataClient(node_url_grpc) -req = vac.data_node.api.v1.trading_data.PartiesRequest() -response = data_client.Parties(req) -print("Parties:\n{}".format(response)) -# :get_parties__ diff --git a/parties-and-accounts/get-parties.py b/parties-and-accounts/get-parties.py deleted file mode 100755 index dbd7c78..0000000 --- a/parties-and-accounts/get-parties.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/python3 - -""" -Script language: Python3 - -Talks to: -- Vega node (REST) - -Apps/Libraries: -- REST: requests (https://pypi.org/project/requests/) - -Responses: -- response-examples.txt -""" - -# Note: this file uses smart-tags in comments to section parts of the code to -# show them as snippets in our documentation. They are not necessary to be -# included when creating your own custom code. -# -# Example of smart-tags: -# __something: -# some code here -# :something__ - -import json -import os -import requests -import helpers - -node_url_rest = os.getenv("NODE_URL_REST") -if not helpers.check_url(node_url_rest): - print("Error: Invalid or missing NODE_URL_REST environment variable.") - exit(1) - -# __get_parties: -# Request a list of parties trading on a Vega network -url = "{base}/parties".format(base=node_url_rest) -response = requests.get(url) -helpers.check_response(response) -response_json = response.json() -print("Parties:\n{}".format(json.dumps(response_json, indent=2, sort_keys=True))) -# :get_parties__ - -assert len(response_json["parties"]) > 0 -pubkey = response_json["parties"][0]["id"] - -# __get_party_by_id: -# Request a party by their identifier (this is their public key) -url = "{base}/parties/{partyID}".format(base=node_url_rest, partyID=pubkey) -response = requests.get(url) -helpers.check_response(response) -response_json = response.json() -print("PartyById:\n{}".format(json.dumps(response_json, indent=2, sort_keys=True))) -# :get_party_by_id__ diff --git a/parties-and-accounts/get-parties.sh b/parties-and-accounts/get-parties.sh deleted file mode 100755 index ec2cfd7..0000000 --- a/parties-and-accounts/get-parties.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env bash - -# Script language: bash -# -# Talks to: -# - Vega node (REST) -# -# Apps/Libraries: -# - REST: curl -# -# Responses: -# - response-examples.txt - -# Note: this file uses smart-tags in comments to section parts of the code to -# show them as snippets in our documentation. They are not necessary to be -# included when creating your own custom code. -# -# Example of smart-tags: -# __something: -# some code here -# :something__ - -source helpers.sh - -check_url "NODE_URL_REST" || exit 1 - -# __get_parties: -# Request a list of parties trading on a Vega network -url="$NODE_URL_REST/parties" -response="$(curl -s "$url")" -parties="$(echo "$response" | jq -r .parties)" -echo "Parties: -$parties" -# :get_parties__ \ No newline at end of file diff --git a/parties-and-accounts/response-examples.txt b/parties-and-accounts/response-examples.txt deleted file mode 100644 index 9bd8b50..0000000 --- a/parties-and-accounts/response-examples.txt +++ /dev/null @@ -1,109 +0,0 @@ -### __example_parties_response: -# Response for a list of parties trading on a Vega network -{ - "parties": [ - { - "id": "d2a645968df520712395caca1e82e022bba0b4816e66b827823ffc0163007fad" - }, - { - "id": "530067c6777a5fafa484eda5eda7fc46f6d6f218c7686d517554d1d2d83fcfda" - }, - ... - { - "id": "beb34ecb89187d18afba6f2cb40f2a35fd4c163fd21b27425af305bb5e0ef8da" - }, - ] -} -# Note: some fields/records have been omitted to improve readability -### :example_parties_response__ - -### __example_party_by_id_response: -# Response for a party by their identifier (this is their public key) -{ - "party": { - "id": "d2a645968df520712395caca1e82e022bba0b4816e66b827823ffc0163007fad" - } -} -### :example_party_by_id_response__ - -### __example_accounts_by_market_response: -# Response for a list of collateral accounts for a market on a Vega network -{ - "accounts": [ - { - "asset": "94beaabf8a99450f148e337c68357d800dcf52e2f08b50ad89ca37fb3c451fb1", - "balance": "0", - "id": "", - "marketId": "2bc517590ebf1edc401c988a20a8e5451faXX33b5eae842ce1713c3e9c26a28d", - "owner": "", - "type": "ACCOUNT_TYPE_INSURANCE" - }, - { - "asset": "94beaabf8a99450f148e337c68357d800dcf52e2f08b50ad89ca37fb3c451fb1", - "balance": "6900000000", - "id": "", - "marketId": "2bc517590ebf1edc401c988a20a8e5451faXX33b5eae842ce1713c3e9c26a28d", - "owner": "", - "type": "ACCOUNT_TYPE_FEES_LIQUIDITY" - } - ] -} -### :example_accounts_by_market_response__ - -### __example_accounts_by_party_response: -# Response for a list of collateral accounts for a party (pubkey) on a Vega network -{ - "accounts": [ - { - "asset": "16657915cb47f8c9c50c753e95a9a8107933a904fcdefaebe10284bbd37649b9", - "balance": "2500000", - "id": "", - "marketId": "", - "owner": "ac9d9fe2e5904308d9c0f6fe758f8a4f4dd9636a23423sdff0b7ec7edc9", - "type": "ACCOUNT_TYPE_GENERAL" - }, - { - "asset": "2fdd696ac7787d98afcbc136d4cf17bc595f7c0c6d3bf57c0ceeb5184347b725", - "balance": "1000000", - "id": "", - "marketId": "", - "owner": "ac9d9fe2e5904308d9c0f6fe758f8a4f4dd9636a23423sdff0b7ec7edc9", - "type": "ACCOUNT_TYPE_GENERAL" - }, - { - "asset": "94beaabf8a99450f148e337c68357d800dcf52e2f08b50ad89ca37fb3c451fb1", - "balance": "50000000000", - "id": "", - "marketId": "", - "owner": "ac9d9fe2e5904308d9c0f6fe758f8a4f4dd9636a23423sdff0b7ec7edc9", - "type": "ACCOUNT_TYPE_GENERAL" - }, - { - "asset": "tVOTE", - "balance": "1", - "id": "", - "marketId": "", - "owner": "ac9d9fe2e5904308d9c0f6fe758f8a4f4dd9636a23423sdff0b7ec7edc9", - "type": "ACCOUNT_TYPE_GENERAL" - }, - ] -} -### :example_accounts_by_party_response__ - -### __example_positions_by_party_response: -# Response for a list of positions for a party (pubkey) on a Vega network -{ - "positions": [ - { - "averageEntryPrice": "0", - "marketId": "RTJVFCMFZZQQLLYVSXTWEN62P6AH6OCN", - "openVolume": "0", - "partyId": "ac9d9fe2e5904308d9c0f6fe758f8a4f4dd9636a23423sdff0b7ec7edc9", - "realisedPNL": "231", - "unrealisedPNL": "0", - "updatedAt": "1606232706823742661" - } - ... - ] -} -### :example_positions_by_party_response__ \ No newline at end of file diff --git a/propose-freeform/README.md b/propose-freeform/README.md deleted file mode 100644 index 9c3ed15..0000000 --- a/propose-freeform/README.md +++ /dev/null @@ -1,29 +0,0 @@ -[![Gitpod ready-to-code](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/vegaprotocol/sample-api-scripts) - -# Sample API scripts - Propose Freeform Proposal - -These scripts talk to a Vega node as well as a Vega wallet to propose a freeform proposal: - -- Login to existing wallet -- Select key-pair -- Find an existing asset with a specific name -- Get current time on Vega blockchain -- Prepare and submit a freeform proposal -- Wait for proposal to be accepted and processed -- Vote on the proposal -- Wait for voting to be enacted - -Please see the documentation on Vega for further information. - -## Python + requests - -Interact with wallet and node API operations using python3 and the [requests](https://pypi.org/project/requests/) library [REST API]: - -```bash -python3 propose-markets/propose-vote-enact-freeform.py -``` - ---- - -**[Home](../README.md)** - diff --git a/propose-freeform/party-has-proposed.py b/propose-freeform/party-has-proposed.py deleted file mode 100644 index d7784cc..0000000 --- a/propose-freeform/party-has-proposed.py +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/python3 - -""" -Script language: Python3 - -Talks to: -- Vega data node (REST) -- Vega wallet (REST) - -Apps/Libraries: -- REST: requests (https://pypi.org/project/requests/) -""" - -# Note: this file uses smart-tags in comments to section parts of the code to -# show them as snippets in our documentation. They are not necessary to be -# included when creating your own custom code. -# -# Example of smart-tags: -# __something: -# some code here -# :something__ - -import sys -import requests -import time -import os -import helpers - -def main(): - node_url_rest = os.getenv("NODE_URL_REST") - if not helpers.check_url(node_url_rest): - print("Error: Invalid or missing NODE_URL_REST environment variable.") - sys.exit(1) - - wallet_server_url = os.getenv("WALLETSERVER_URL") - - wallet_name = os.getenv("WALLET_NAME") - if not helpers.check_var(wallet_name): - print("Error: Invalid or missing WALLET_NAME environment variable.") - sys.exit(1) - - wallet_passphrase = os.getenv("WALLET_PASSPHRASE") - if not helpers.check_var(wallet_passphrase): - print("Error: Invalid or missing WALLET_PASSPHRASE environment variable.") - sys.exit(1) - - # Help guide users against including api version suffix on url - wallet_server_url = helpers.check_wallet_url(wallet_server_url) - - ##################################################################################### - # W A L L E T S E R V I C E # - ##################################################################################### - - print(f"Logging into wallet: {wallet_name}") - - # __login_wallet: - # Log in to an existing wallet - req = {"wallet": wallet_name, "passphrase": wallet_passphrase} - response = requests.post(f"{wallet_server_url}/api/v1/auth/token", json=req) - helpers.check_response(response) - token = response.json()["token"] - # :login_wallet__ - - assert token != "" - print("Logged in to wallet successfully") - - # __get_pubkey: - # List key pairs and select public key to use - headers = {"Authorization": f"Bearer {token}"} - response = requests.get(f"{wallet_server_url}/api/v1/keys", headers=headers) - helpers.check_response(response) - keys = response.json()["keys"] - pubkey = keys[0]["pub"] - # :get_pubkey__ - - assert pubkey - print("Selected pubkey for signing") - - ##################################################################################### - # F I N D P R O P O S A L S # - ##################################################################################### - - # __get_proposals_for_party: - # Request a list of proposals available for party/pubkey - url = f"{node_url_rest}/parties/{pubkey}/proposals" - response = requests.get(url) - helpers.check_response(response) - # :get_proposals_for_party__ - - # Debugging - # print(response.json()) - - print(f"Listing proposals for pubkey {pubkey}:") - - freeform_total = 0 - - proposals = response.json()["data"] - for proposal in proposals: - proposal_id = proposal["proposal"]["id"] - proposal_state = proposal["proposal"]["state"] - proposal_ref = proposal["proposal"]["reference"] - proposal_terms = proposal["proposal"]["terms"] - print(f"\nid: {proposal_id} - state: {proposal_state} - ref: {proposal_ref}") - print(f"{proposal_terms}") - if "newFreeform" in proposal_terms: - freeform_total = freeform_total+1 - print("^^ freeform governance proposal found ^^") - - print(f"\nTotal proposals found: {len(proposals)}") - print(f" - of which freeform proposals found: {freeform_total}") - - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/propose-freeform/propose-vote-enact-freeform.py b/propose-freeform/propose-vote-enact-freeform.py deleted file mode 100644 index 6a2f618..0000000 --- a/propose-freeform/propose-vote-enact-freeform.py +++ /dev/null @@ -1,288 +0,0 @@ -#!/usr/bin/python3 - -""" -Script language: Python3 - -Talks to: -- Vega node (REST) -- Vega wallet (REST) - -Apps/Libraries: -- REST: requests (https://pypi.org/project/requests/) -""" - -# Note: this file uses smart-tags in comments to section parts of the code to -# show them as snippets in our documentation. They are not necessary to be -# included when creating your own custom code. -# -# Example of smart-tags: -# __something: -# some code here -# :something__ - -import sys -import requests -import time -import os -import helpers - -def main(): - node_url_rest = os.getenv("NODE_URL_REST") - if not helpers.check_url(node_url_rest): - print("Error: Invalid or missing NODE_URL_REST environment variable.") - sys.exit(1) - - wallet_server_url = os.getenv("WALLETSERVER_URL") - - wallet_name = os.getenv("WALLET_NAME") - if not helpers.check_var(wallet_name): - print("Error: Invalid or missing WALLET_NAME environment variable.") - sys.exit(1) - - wallet_passphrase = os.getenv("WALLET_PASSPHRASE") - if not helpers.check_var(wallet_passphrase): - print("Error: Invalid or missing WALLET_PASSPHRASE environment variable.") - sys.exit(1) - - # Help guide users against including api version suffix on url - wallet_server_url = helpers.check_wallet_url(wallet_server_url) - - ##################################################################################### - # W A L L E T S E R V I C E # - ##################################################################################### - - print(f"Logging into wallet: {wallet_name}") - - # __login_wallet: - # Log in to an existing wallet - req = {"wallet": wallet_name, "passphrase": wallet_passphrase} - response = requests.post(f"{wallet_server_url}/api/v1/auth/token", json=req) - helpers.check_response(response) - token = response.json()["token"] - # :login_wallet__ - - assert token != "" - print("Logged in to wallet successfully") - - # __get_pubkey: - # List key pairs and select public key to use - headers = {"Authorization": f"Bearer {token}"} - response = requests.get(f"{wallet_server_url}/api/v1/keys", headers=headers) - helpers.check_response(response) - keys = response.json()["keys"] - pubkey = keys[0]["pub"] - # :get_pubkey__ - - assert pubkey - print("Selected pubkey for signing") - - ##################################################################################### - # F I N D A S S E T S # - ##################################################################################### - - - # __get_assets: - # Request a list of assets available on a Vega network - url = f"{node_url_rest}/assets" - response = requests.get(url) - helpers.check_response(response) - # :get_assets__ - - # Debugging - # print("Assets:\n{}".format( - # json.dumps(response.json(), indent=2, sort_keys=True))) - - ##################################################################################### - # G O V E R N A N C E T O K E N C H E C K # - ##################################################################################### - - # Get the identifier of the governance asset on the Vega network - assets = response.json()["assets"] - vote_asset_id = next((x["id"] for x in assets if x["details"]["symbol"] == "VEGA"), None) - if vote_asset_id is None: - print("VEGA asset not found on specified Vega network, please symbol name check and try again") - sys.exit(1) - - # Request accounts for party and check governance asset balance - url = f"{node_url_rest}/parties/{pubkey}/accounts" - response = requests.get(url) - helpers.check_response(response) - - # Debugging - # print("Accounts:\n{}".format( - # json.dumps(response.json(), indent=2, sort_keys=True))) - - voting_balance = 0 - accounts = response.json()["accounts"] - for account in accounts: - if account["asset"] == vote_asset_id: - print("Found governance asset account") - print(account) - voting_balance = account["balance"] - break - - if voting_balance == 0: - print(f"Please deposit VEGA asset to public key {pubkey} and try again") - sys.exit(1) - - ##################################################################################### - # B L O C K C H A I N T I M E # - ##################################################################################### - - # __get_time: - # Request the current blockchain time, and convert to time in seconds - response = requests.get(f"{node_url_rest}/time") - helpers.check_response(response) - blockchain_time = int(response.json()["timestamp"]) - blockchain_time_seconds = int(blockchain_time / 1e9) # Seconds precision - # :get_time__ - - assert blockchain_time > 0 - assert blockchain_time_seconds > 0 - print(f"Blockchain time: {blockchain_time} ({blockchain_time_seconds} seconds past epoch)") - - ##################################################################################### - # F R E E F O R M # - ##################################################################################### - - # Step 1 propose a freeform proposal - - # __prepare_propose_newFreeform: - # Compose a freeform governance proposal - proposal_ref = f"{pubkey}-{helpers.generate_id(30)}" - - # Set closing/enactment and validation timestamps to valid time offsets - # from the current Vega blockchain time - closing_time = blockchain_time_seconds + 172900 - validation_time = blockchain_time_seconds + 1 - - new_freeform = { - "proposalSubmission": { - "reference": proposal_ref, - "rationale": { - "url": "www.example.com/full-proposal.md", - "description": "A short description of the proposals", - "hash": "1869c3081c5a294269070aa496a4d80d1b0824c239af02625b2e304f011bb190" - }, - "terms": { - "closingTimestamp": closing_time, - "validationTimestamp": validation_time, - "newFreeform": {}, - } - }, - "pubKey": pubkey, - "propagate": True - } - - # __sign_tx_proposal: - # Sign the proposal transaction - # Note: Setting propagate to true will also submit to a Vega node - url = f"{wallet_server_url}/api/v1/command/sync" - response = requests.post(url, headers=headers, json=new_freeform) - helpers.check_response(response) - # :sign_tx_proposal__ - - print("Signed proposal and sent to Vega") - - # Debugging - # print("Signed transaction:\n", response.json(), "\n") - - # Wait for proposal to be included in a block and to be accepted by Vega network - print("Waiting for blockchain...", end="", flush=True) - proposal_id = "" - done = False - while not done: - time.sleep(0.5) - print(".", end="", flush=True) - my_proposals = requests.get(node_url_rest + "/parties/" + pubkey + "/proposals") - if my_proposals.status_code != 200: - continue - - for n in my_proposals.json()["data"]: - if n["proposal"]["reference"] == proposal_ref: - proposal_id = n["proposal"]["id"] - print() - if (n["proposal"]['state'] == 'STATE_REJECTED') or (n["proposal"]['state'] == 'STATE_DECLINED') or ( - n["proposal"]['state'] == 'STATE_FAILED'): - print("Your proposal has been " + n["proposal"]['state'] + "!") - print("Due to: " + n["proposal"]["reason"]) - if ((n["proposal"]["errorDetails"]) != ''): print("Further details: " + n["proposal"]["errorDetails"]) - exit() - else: - print("Your proposal has been accepted by the network!") - print(n) - done = True - break - - assert proposal_id != "" - - ##################################################################################### - # V O T E O N P A R A M E T E R # - ##################################################################################### - - # STEP 2 - Let's vote on the proposal - - # IMPORTANT: When voting for a proposal on the Vega Testnet, typically a single - # YES vote from the proposer will not be enough to vote the proposal into existence. - # This is because of the network minimum threshold for voting on proposals. - # A proposer should enlist the help/YES votes from other community members, ideally on the - # Community forums (https://community.vega.xyz/c/testnet) or Discord (https://vega.xyz/discord) - - # Further documentation on proposal voting and review here: https://docs.testnet.vega.xyz/docs/api-howtos/proposals/ - - # __prepare_vote: - # Prepare a vote for the proposal - vote = { - "voteSubmission": { - "value": "VALUE_YES", # Can be either VALUE_YES or VALUE_NO - "proposalId": proposal_id, - }, - "pubKey": pubkey, - "propagate": True - } - # :prepare_vote__ - - # Debugging - # print("Prepared vote:\n", prepared_vote, "\n") - - # __sign_tx_vote: - # Sign the vote transaction - # Note: Setting propagate to true will also submit to a Vega node - url = f"{wallet_server_url}/api/v1/command/sync" - response = requests.post(url, headers=headers, json=vote) - helpers.check_response(response) - # :sign_tx_vote__ - - print("Signed vote on proposal and sent to Vega") - - # Debugging - print("Signed transaction:\n", response.json(), "\n") - - # Optionally wait for proposal time to elapse - # print("Waiting for vote on proposal to succeed or fail...", end="", flush=True) - # while True: - # time.sleep(0.5) - # my_proposals = requests.get( - # node_url_rest + "/parties/" + pubkey + "/proposals" - # ) - # if my_proposals.status_code != 200: - # continue - - # proposal = next((n["proposal"] for n in my_proposals.json()["data"] if n["proposal"]["reference"] == proposal_ref), None) - - # if proposal is None or proposal["state"] == "STATE_OPEN": - # continue - - # if proposal["state"] == "STATE_PASSED": - # print("proposal vote has succeeded, waiting for enactment") - # continue - - # print(proposal) - # if proposal["state"] == "STATE_ENACTED": - # break - - # sys.exit(1) - - -if __name__ == "__main__": - main() diff --git a/propose-markets/README.md b/propose-markets/README.md deleted file mode 100644 index 33a68ff..0000000 --- a/propose-markets/README.md +++ /dev/null @@ -1,30 +0,0 @@ -[![Gitpod ready-to-code](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/vegaprotocol/sample-api-scripts) - -# Sample API scripts - Propose Markets - -These scripts talk to a Vega node as well as a Vega wallet to propose/create a new market: - -- Login to existing wallet -- Select key-pair -- Find an existing asset with a specific name -- Get current time on Vega blockchain -- Prepare and submit a new market proposal -- Wait for market proposal to be accepted and processed -- Vote on the proposal -- Wait for voting to succeed -- Wait for market to become available on Vega - -Please see the documentation on Vega for further information. - -## Python + requests - -Interact with wallet and node API operations using python3 and the [requests](https://pypi.org/project/requests/) library [REST API]: - -```bash -python3 propose-markets/propose-vote-enact-market.py -``` - ---- - -**[Home](../README.md)** - diff --git a/propose-markets/propose-vote-enact-market-time-triggered.py b/propose-markets/propose-vote-enact-market-time-triggered.py deleted file mode 100644 index 82c2f21..0000000 --- a/propose-markets/propose-vote-enact-market-time-triggered.py +++ /dev/null @@ -1,453 +0,0 @@ -#!/usr/bin/python3 - -""" -Script language: Python3 - -Talks to: -- Vega node (REST) -- Vega wallet (REST) - -Apps/Libraries: -- REST: requests (https://pypi.org/project/requests/) -""" - -# Note: this file uses smart-tags in comments to section parts of the code to -# show them as snippets in our documentation. They are not necessary to be -# included when creating your own custom code. -# -# Example of smart-tags: -# __something: -# some code here -# :something__ - -import os -import sys -import requests -import time -import helpers - - -node_url_rest = os.getenv("NODE_URL_REST") -if not helpers.check_url(node_url_rest): - print("Error: Invalid or missing NODE_URL_REST environment variable.") - sys.exit(1) - -wallet_server_url = os.getenv("WALLETSERVER_URL") - -wallet_name = os.getenv("WALLET_NAME") -if not helpers.check_var(wallet_name): - print("Error: Invalid or missing WALLET_NAME environment variable.") - sys.exit(1) - -wallet_passphrase = os.getenv("WALLET_PASSPHRASE") -if not helpers.check_var(wallet_passphrase): - print("Error: Invalid or missing WALLET_PASSPHRASE environment variable.") - sys.exit(1) - -# Help guide users against including api version suffix on url -wallet_server_url = helpers.check_wallet_url(wallet_server_url) - -############################################################################### -# W A L L E T S E R V I C E # -############################################################################### - -print(f"Logging into wallet: {wallet_name}") - -# __login_wallet: -# Log in to an existing wallet -req = {"wallet": wallet_name, "passphrase": wallet_passphrase} -response = requests.post(f"{wallet_server_url}/api/v1/auth/token", json=req) -helpers.check_response(response) -token = response.json()["token"] -# :login_wallet__ - -assert token != "" -print("Logged in to wallet successfully") - -# __get_pubkey: -# List key pairs and select public key to use -headers = {"Authorization": f"Bearer {token}"} -response = requests.get(f"{wallet_server_url}/api/v1/keys", headers=headers) -helpers.check_response(response) -keys = response.json()["keys"] -pubkey = keys[0]["pub"] -# :get_pubkey__ - -assert pubkey != "" -print("Selected pubkey for signing") - -############################################################################### -# F I N D A S S E T S # -############################################################################### - -# __get_assets: -# Request a list of assets available on a Vega network -url = f"{node_url_rest}/assets" -response = requests.get(url) -helpers.check_response(response) -# :get_assets__ - -# Debugging -# print("Assets:\n{}".format( -# json.dumps(response.json(), indent=2, sort_keys=True))) - -# __find_asset: -# Find settlement asset with name tDAI -found_asset_id = None -assets = response.json()["assets"] -for asset in assets: - if asset["details"]["symbol"] == "tDAI": - print("Found an asset with symbol tDAI") - print(asset) - found_asset_id = asset["id"] - break -# :find_asset__ - -if found_asset_id is None: - print( - "tDAI asset not found on specified Vega network, please propose and " - "create this asset first" - ) - sys.exit(1) - -############################################################################### -# G O V E R N A N C E T O K E N C H E C K # -############################################################################### - -# Get the identifier of the governance asset on the Vega network -assets = response.json()["assets"] -vote_asset_id = next((x["id"] for x in assets if x["details"]["symbol"] == "VOTE"), None) -if vote_asset_id is None: - print("VEGA asset not found on specified Vega network, please symbol name check and try again") - sys.exit(1) - -# Request accounts for party and check governance asset balance -url = f"{node_url_rest}/parties/{pubkey}/accounts" -response = requests.get(url) -helpers.check_response(response) - -# Debugging -# print("Accounts:\n{}".format( -# json.dumps(response.json(), indent=2, sort_keys=True))) - -voting_balance = 0 -accounts = response.json()["accounts"] -for account in accounts: - if account["asset"] == vote_asset_id: - print("Found governance asset account") - print(account) - voting_balance = account["balance"] - break - -if voting_balance == 0: - print(f"Please deposit VEGA asset to public key {pubkey} and try again") - sys.exit(1) - -############################################################################### -# B L O C K C H A I N T I M E # -############################################################################### - -# __get_time: -# Request the current blockchain time, and convert to time in seconds -response = requests.get(f"{node_url_rest}/time") -helpers.check_response(response) -blockchain_time = int(response.json()["timestamp"]) -blockchain_time_seconds = int(blockchain_time / 1e9) # Seconds precision -# :get_time__ - -assert blockchain_time > 0 -assert blockchain_time_seconds > 0 -print( - f"Blockchain time: {blockchain_time} ({blockchain_time_seconds} seconds " - "past epoch)" -) - -############################################################################### -# P R O P O S E M A R K E T # -############################################################################### - -# STEP 1 - Propose a BTC/DAI futures market - -# Further documentation on creating markets: -# https://docs.testnet.vega.xyz/docs/api-howtos/create-market/ - -# __prepare_propose_market: -# Compose a governance proposal for a new market -proposal_ref = f"{pubkey}-{helpers.generate_id(30)}" - -# Set closing/enactment and validation timestamps to valid time offsets -# from the current Vega blockchain time -closing_time = blockchain_time_seconds + 360 -enactment_time = blockchain_time_seconds + 480 -validation_time = blockchain_time_seconds + 1 - -# The proposal command below contains the configuration for a new market -proposal = { - "proposalSubmission": { - "reference": proposal_ref, - "rationale": { - "description": "New market BTCDAI" - }, - "terms": { - "closingTimestamp": closing_time, - "enactmentTimestamp": enactment_time, - "validationTimestamp": validation_time, - "newMarket": { - "changes": { - "decimalPlaces": 5, - "instrument": { - "name": "BTC/DAI (2022, tDAI)", - "code": "CRYPTO:BTCDAI/DEC22", - "future": { - "oracleSpecForSettlementPrice": { - "pubKeys": ["c77fe74b64b2c97723bac8c3f110e5c3d7fb78f6c6c8915a56cb962968fbcfa7"], - "filters": [ - { - "key": { - "name": "price.BTCDAI.value", - "type": "TYPE_INTEGER", - }, - "conditions": [ - { - "operator": "OPERATOR_GREATER_THAN", - "value": "0", - }, - ], - }, - ], - }, - "oracleSpecForTradingTermination": { - "pubKeys": [], - "filters": [ - { - "key": { - "name": "vegaprotocol.builtin.timestamp", - "type": "TYPE_TIMESTAMP", - }, - "conditions": [ - { - "operator": "OPERATOR_GREATER_THAN_OR_EQUAL", - "value": "1648684800000000000", - }, - ], - }, - ], - }, - "oracleSpecBinding": { - "settlementPriceProperty": "price.BTCDAI.value", - "tradingTerminationProperty": "vegaprotocol.builtin.timestamp" - }, - "quoteName": "tDAI", - "settlementAsset": found_asset_id, - } - }, - "metadata": [ - "base:BTC", - "quote:DAI", - ], - "priceMonitoringParameters": { - "triggers": [ - { - "horizon": 43200, - "probability": "0.9999999", - "auctionExtension": 600 - }, - { - "horizon": 300, - "probability": "0.9999", - "auctionExtension": 60 - } - ] - }, - "liquidityMonitoringParameters": { - "targetStakeParameters": { - "timeWindow": 3600, - "scalingFactor": 10, - }, - "triggeringRatio": 0, - "auctionExtension": 0, - }, - "logNormal": { - "riskAversionParameter": 0.01, - "tau": 1.90128526884173e-06, - "params": {"mu": 0, "r": 0.016, "sigma": 0.05}, - }, - }, - "liquidityCommitment": { - "commitmentAmount": "1", - "fee": "0.01", - "sells": [ - { - "reference": "PEGGED_REFERENCE_BEST_ASK", - "proportion": 10, - "offset": "2000", - }, - { - "reference": "PEGGED_REFERENCE_BEST_ASK", - "proportion": 10, - "offset": "1000", - }, - ], - "buys": [ - { - "reference": "PEGGED_REFERENCE_BEST_BID", - "proportion": 10, - "offset": "1000", - }, - { - "reference": "PEGGED_REFERENCE_BEST_BID", - "proportion": 10, - "offset": "2000", - }, - ], - "reference": "", - }, - } - } - }, - "pubKey": pubkey, - "propagate": True -} -# :prepare_propose_market__ - -print("Market proposal: ", proposal) - -# __sign_tx_proposal: -# Sign the new market proposal transaction -# Note: Setting propagate to true will also submit to a Vega node -url = f"{wallet_server_url}/api/v1/command/sync" -response = requests.post(url, headers=headers, json=proposal) -helpers.check_response(response) -# :sign_tx_proposal__ - -print("Signed market proposal and sent to Vega") - -# Debugging -# print("Signed transaction:\n", response.json(), "\n") - -# Wait for proposal to be included in a block and to be accepted by Vega -# network -print("Waiting for blockchain...", end="", flush=True) -proposal_id = "" -done = False -while not done: - time.sleep(0.5) - print(".", end="", flush=True) - my_proposals = requests.get( - node_url_rest + "/parties/" + pubkey + "/proposals" - ) - if my_proposals.status_code != 200: - continue - - for n in my_proposals.json()["data"]: - if n["proposal"]["reference"] == proposal_ref: - proposal_id = n["proposal"]["id"] - print() - print("Your proposal has been accepted by the network") - print(n) - done = True - break - -assert proposal_id != "" - -############################################################################### -# V O T E O N M A R K E T # -############################################################################### - -# STEP 2 - Let's vote on the market proposal - -# IMPORTANT: When voting for a proposal on the Vega Testnet, typically a single -# YES vote from the proposer will not be enough to vote the market into -# existence. This is because of the network minimum threshold for voting on -# proposals, this threshold for market proposals this is currently a 66% -# majority vote either YES or NO. -# A proposer should enlist the help/YES votes from other community members, -# ideally on the Community forums (https://community.vega.xyz/c/testnet) or -# Discord (https://vega.xyz/discord) - -# Further documentation on proposal voting and review here: -# https://docs.testnet.vega.xyz/docs/api-howtos/proposals/ - -# __prepare_vote: -# Create a vote message, to vote on the proposal -vote = { - "voteSubmission": { - "value": "VALUE_YES", # Can be either VALUE_YES or VALUE_NO - "proposalId": proposal_id, - }, - "pubKey": pubkey, - "propagate": True -} -# :prepare_vote__ - -# Debugging -# print("Vote submission:\n", vote, "\n") - -# __sign_tx_vote: -# Sign the vote transaction -# Note: Setting propagate to true will also submit to a Vega node -url = f"{wallet_server_url}/api/v1/command/sync" -response = requests.post(url, headers=headers, json=vote) -helpers.check_response(response) -# :sign_tx_vote__ - -print("Signed vote on proposal and sent to Vega") - -# Debugging -# print("Signed transaction:\n", response.json(), "\n") - -print("Waiting for vote on proposal to succeed or fail...", end="", flush=True) -while True: - time.sleep(0.5) - my_proposals = requests.get( - node_url_rest + "/parties/" + pubkey + "/proposals" - ) - if my_proposals.status_code != 200: - continue - - proposal = next((n["proposal"] for n in my_proposals.json()["data"] if n["proposal"]["reference"] == proposal_ref), None) - - if proposal is None or proposal["state"] == "STATE_OPEN": - continue - - if proposal["state"] == "STATE_PASSED": - print("proposal vote has succeeded, waiting for enactment") - continue - - if proposal["state"] in ["STATE_ENACTED", "STATE_REJECTED", "STATE_FAILED"]: - break - - print(proposal) - sys.exit(1) - - -############################################################################### -# W A I T F O R M A R K E T # -############################################################################### - -# STEP 3 - Wait for market to be enacted - -# IMPORTANT: When voting for a proposal on the Vega Testnet, typically a single -# YES vote from the proposer will not be enough to vote the market into -# existence. As described above in STEP 2, a market will need community voting -# support to be passed and then enacted. - -# __wait_for_market: -print("Waiting for proposal to be enacted or failed...", end="", flush=True) -done = False -while not done: - time.sleep(0.5) - print(".", end="", flush=True) - markets = requests.get(node_url_rest + "/markets") - if markets.status_code != 200: - continue - - for n in markets.json()["markets"]: - if n["id"] == proposal_id: - print() - print(n) - done = True - break -# :wait_for_market__ - -# Completed. diff --git a/propose-markets/propose-vote-enact-market.py b/propose-markets/propose-vote-enact-market.py deleted file mode 100644 index 2b00c8e..0000000 --- a/propose-markets/propose-vote-enact-market.py +++ /dev/null @@ -1,462 +0,0 @@ -#!/usr/bin/python3 - -""" -Script language: Python3 - -Talks to: -- Vega node (REST) -- Vega wallet (REST) - -Apps/Libraries: -- REST: requests (https://pypi.org/project/requests/) -""" - -# Note: this file uses smart-tags in comments to section parts of the code to -# show them as snippets in our documentation. They are not necessary to be -# included when creating your own custom code. -# -# Example of smart-tags: -# __something: -# some code here -# :something__ - -import os -import sys -import requests -import time -import helpers - - -node_url_rest = os.getenv("NODE_URL_REST") -if not helpers.check_url(node_url_rest): - print("Error: Invalid or missing NODE_URL_REST environment variable.") - sys.exit(1) - -wallet_server_url = os.getenv("WALLETSERVER_URL") - -wallet_name = os.getenv("WALLET_NAME") -if not helpers.check_var(wallet_name): - print("Error: Invalid or missing WALLET_NAME environment variable.") - sys.exit(1) - -wallet_passphrase = os.getenv("WALLET_PASSPHRASE") -if not helpers.check_var(wallet_passphrase): - print("Error: Invalid or missing WALLET_PASSPHRASE environment variable.") - sys.exit(1) - -# Help guide users against including api version suffix on url -wallet_server_url = helpers.check_wallet_url(wallet_server_url) - -############################################################################### -# W A L L E T S E R V I C E # -############################################################################### - -print(f"Logging into wallet: {wallet_name}") - -# __login_wallet: -# Log in to an existing wallet -req = {"wallet": wallet_name, "passphrase": wallet_passphrase} -response = requests.post(f"{wallet_server_url}/api/v1/auth/token", json=req) -helpers.check_response(response) -token = response.json()["token"] -# :login_wallet__ - -assert token != "" -print("Logged in to wallet successfully") - -# __get_pubkey: -# List key pairs and select public key to use -headers = {"Authorization": f"Bearer {token}"} -response = requests.get(f"{wallet_server_url}/api/v1/keys", headers=headers) -helpers.check_response(response) -keys = response.json()["keys"] -pubkey = keys[0]["pub"] -# :get_pubkey__ - -assert pubkey != "" -print("Selected pubkey for signing") - -############################################################################### -# F I N D A S S E T S # -############################################################################### - -# __get_assets: -# Request a list of assets available on a Vega network -url = f"{node_url_rest}/assets" -response = requests.get(url) -helpers.check_response(response) -# :get_assets__ - -# Debugging -# print("Assets:\n{}".format( -# json.dumps(response.json(), indent=2, sort_keys=True))) - -# __find_asset: -# Find settlement asset with name tDAI -found_asset_id = None -assets = response.json()["assets"] -for asset in assets: - if asset["details"]["symbol"] == "tDAI": - print("Found an asset with symbol tDAI") - print(asset) - found_asset_id = asset["id"] - break -# :find_asset__ - -if found_asset_id is None: - print( - "tDAI asset not found on specified Vega network, please propose and " - "create this asset first" - ) - sys.exit(1) - -############################################################################### -# G O V E R N A N C E T O K E N C H E C K # -############################################################################### - -# Get the identifier of the governance asset on the Vega network -assets = response.json()["assets"] -vote_asset_id = next((x["id"] for x in assets if x["details"]["symbol"] == "VEGA"), None) -if vote_asset_id is None: - print("VEGA asset not found on specified Vega network, please symbol name check and try again") - sys.exit(1) - -# Request accounts for party and check governance asset balance -url = f"{node_url_rest}/parties/{pubkey}/accounts" -response = requests.get(url) -helpers.check_response(response) - -# Debugging -# print("Accounts:\n{}".format( -# json.dumps(response.json(), indent=2, sort_keys=True))) - -voting_balance = 0 -accounts = response.json()["accounts"] -for account in accounts: - if account["asset"] == vote_asset_id: - print("Found governance asset account") - print(account) - voting_balance = account["balance"] - break - -if voting_balance == 0: - print(f"Please deposit VEGA asset to public key {pubkey} and try again") - sys.exit(1) - -############################################################################### -# B L O C K C H A I N T I M E # -############################################################################### - -# __get_time: -# Request the current blockchain time, and convert to time in seconds -response = requests.get(f"{node_url_rest}/time") -helpers.check_response(response) -blockchain_time = int(response.json()["timestamp"]) -blockchain_time_seconds = int(blockchain_time / 1e9) # Seconds precision -# :get_time__ - -assert blockchain_time > 0 -assert blockchain_time_seconds > 0 -print( - f"Blockchain time: {blockchain_time} ({blockchain_time_seconds} seconds " - "past epoch)" -) - -############################################################################### -# P R O P O S E M A R K E T # -############################################################################### - -# STEP 1 - Propose a BTC/DAI futures market - -# Further documentation on creating markets: -# https://docs.testnet.vega.xyz/docs/api-howtos/create-market/ - -# IMPORTANT: Governance token $VEGA must be staked to propose markets on Vega - -# __prepare_propose_market: -# Compose a governance proposal for a new market -proposal_ref = f"{pubkey}-{helpers.generate_id(30)}" - -# Set closing/enactment and validation timestamps to valid time offsets -# from the current Vega blockchain time -closing_time = blockchain_time_seconds + 80000 -enactment_time = blockchain_time_seconds + 86500 -validation_time = blockchain_time_seconds + 1 - -# The proposal command below contains the configuration for a new market -proposal = { - "proposalSubmission": { - "reference": proposal_ref, - "rationale": { - "description": "New market BTCDAI" - }, - "terms": { - "closingTimestamp": closing_time, - "enactmentTimestamp": enactment_time, - "validationTimestamp": validation_time, - "newMarket": { - "changes": { - "decimalPlaces": 5, - "instrument": { - "name": "BTC/DAI (2022, tDAI)", - "code": "CRYPTO:BTCDAI/DEC22", - "future": { - "oracleSpecForSettlementPrice": { - "pubKeys": ["c77fe74b64b2c97723bac8c3f110e5c3d7fb78f6c6c8915a56cb962968fbcfa7"], - "filters": [ - { - "key": { - "name": "price.BTCDAI.value", - "type": "TYPE_INTEGER", - }, - "conditions": [ - { - "operator": "OPERATOR_GREATER_THAN", - "value": "0", - }, - ], - }, - ], - }, - "oracleSpecForTradingTermination": { - "pubKeys": ["c77fe74b64b2c97723bac8c3f110e5c3d7fb78f6c6c8915a56cb962968fbcfa7"], - "filters": [ - { - "key": { - "name": "trading.terminated.BTCDAI", - "type": "TYPE_BOOLEAN" - }, - "conditions": [ - { - "operator": "OPERATOR_EQUALS", - "value": "true" - } - ], - }, - ], - }, - "oracleSpecBinding": { - "settlementPriceProperty": "price.BTCDAI.value", - "tradingTerminationProperty": "trading.terminated.BTCDAI" - }, - "quoteName": "tDAI", - "settlementAsset": found_asset_id, - } - }, - "metadata": [ - "base:BTC", - "quote:DAI", - ], - "priceMonitoringParameters": { - "triggers": [ - { - "horizon": 43200, - "probability": "0.9999999", - "auctionExtension": 600 - }, - { - "horizon": 300, - "probability": "0.9999", - "auctionExtension": 60 - } - ] - }, - "liquidityMonitoringParameters": { - "targetStakeParameters": { - "timeWindow": 3600, - "scalingFactor": 10, - }, - "triggeringRatio": 0, - "auctionExtension": 0, - }, - "logNormal": { - "riskAversionParameter": 0.01, - "tau": 1.90128526884173e-06, - "params": {"mu": 0, "r": 0.016, "sigma": 0.05}, - }, - }, - "liquidityCommitment": { - "commitmentAmount": "1", - "fee": "0.01", - "sells": [ - { - "reference": "PEGGED_REFERENCE_BEST_ASK", - "proportion": 10, - "offset": "2000", - }, - { - "reference": "PEGGED_REFERENCE_BEST_ASK", - "proportion": 10, - "offset": "1000", - }, - ], - "buys": [ - { - "reference": "PEGGED_REFERENCE_BEST_BID", - "proportion": 10, - "offset": "1000", - }, - { - "reference": "PEGGED_REFERENCE_BEST_BID", - "proportion": 10, - "offset": "2000", - }, - ], - "reference": "", - }, - } - } - }, - "pubKey": pubkey, - "propagate": True -} -# :prepare_propose_market__ - -print("Market proposal: ", proposal) - -# __sign_tx_proposal: -# Sign the new market proposal transaction -# Note: Setting propagate to true will also submit to a Vega node -url = f"{wallet_server_url}/api/v1/command/sync" -response = requests.post(url, headers=headers, json=proposal) -helpers.check_response(response) -# :sign_tx_proposal__ - -print("Signed market proposal and sent to Vega") - -# Debugging -# print("Signed transaction:\n", response.json(), "\n") - -# Wait for proposal to be included in a block and to be accepted by Vega -# network -print("Waiting for blockchain...", end="", flush=True) -proposal_id = "" -done = False -while not done: - time.sleep(0.5) - - print(".", end="", flush=True) - my_proposals = requests.get( - node_url_rest + "/parties/" + pubkey + "/proposals" - ) - if my_proposals.status_code != 200: - continue - - for n in my_proposals.json()["data"]: - if n["proposal"]["reference"] == proposal_ref: - proposal_id = n["proposal"]["id"] - print() - if (n["proposal"]['state']=='STATE_REJECTED') or (n["proposal"]['state']=='STATE_DECLINED') or (n["proposal"]['state']=='STATE_FAILED'): - print("Your proposal has been " + n["proposal"]['state'] + "!") - print("Due to: " + n["proposal"]["reason"]) - if ((n["proposal"]["errorDetails"]) != ''): print("Further details: " + n["proposal"]["errorDetails"]) - exit() - else: - print("Your proposal has been accepted by the network!") - print(n) - done = True - break - -assert proposal_id != "" - -############################################################################### -# V O T E O N M A R K E T # -############################################################################### - -# STEP 2 - Let's vote on the market proposal - -# IMPORTANT: When voting for a proposal on the Vega Testnet, typically a single -# YES vote from the proposer will not be enough to vote the market into -# existence. This is because of the network minimum threshold for voting on -# proposals, this threshold for market proposals this is currently a 66% -# majority vote either YES or NO. -# A proposer should enlist the help/YES votes from other community members, -# ideally on the Community forums (https://community.vega.xyz/c/testnet) or -# Discord (https://vega.xyz/discord) - -# Further documentation on proposal voting and review here: -# https://docs.testnet.vega.xyz/docs/api-howtos/proposals/ - -# __prepare_vote: -# Create a vote message, to vote on the proposal -vote = { - "voteSubmission": { - "value": "VALUE_YES", # Can be either VALUE_YES or VALUE_NO - "proposalId": proposal_id, - }, - "pubKey": pubkey, - "propagate": True -} -# :prepare_vote__ - -# Debugging -# print("Vote submission:\n", vote, "\n") - -# __sign_tx_vote: -# Sign the vote transaction -# Note: Setting propagate to true will also submit to a Vega node -url = f"{wallet_server_url}/api/v1/command/sync" -response = requests.post(url, headers=headers, json=vote) -helpers.check_response(response) -# :sign_tx_vote__ - -print("Signed vote on proposal and sent to Vega") - -# Debugging -# print("Signed transaction:\n", response.json(), "\n") - -print("Waiting for vote on proposal to succeed or fail...", end="", flush=True) -while True: - time.sleep(0.5) - my_proposals = requests.get( - node_url_rest + "/parties/" + pubkey + "/proposals" - ) - if my_proposals.status_code != 200: - continue - - proposal = next((n["proposal"] for n in my_proposals.json()["data"] if n["proposal"]["reference"] == proposal_ref), None) - - if proposal is None or proposal["state"] == "STATE_OPEN": - continue - - if proposal["state"] == "STATE_PASSED": - print("proposal vote has succeeded, waiting for enactment") - continue - - if proposal["state"] == "STATE_ENACTED": - break - - print(proposal) - sys.exit(1) - - -############################################################################### -# W A I T F O R M A R K E T # -############################################################################### - -# STEP 3 - Wait for market to be enacted - -# IMPORTANT: When voting for a proposal on the Vega Testnet, typically a single -# YES vote from the proposer will not be enough to vote the market into -# existence. As described above in STEP 2, a market will need community voting -# support to be passed and then enacted. - -# __wait_for_market: -print("Waiting for proposal to be enacted or failed...", end="", flush=True) -done = False -while not done: - time.sleep(0.5) - print(".", end="", flush=True) - markets = requests.get(node_url_rest + "/markets") - if markets.status_code != 200: - continue - - for n in markets.json()["markets"]: - if n["id"] == proposal_id: - print() - print(n) - done = True - break -# :wait_for_market__ - -# Completed. diff --git a/propose-markets/response-examples.txt b/propose-markets/response-examples.txt deleted file mode 100644 index 5b17a0d..0000000 --- a/propose-markets/response-examples.txt +++ /dev/null @@ -1,91 +0,0 @@ -### __example_sign_tx_proposal_response: -# Response for signing the prepared proposal -{ - "base64Bundle": "CuIBCrIBMWY5MjViYzMtNjFhMi00YzNiLTg5ZmEtMGJlNDZkY ... QAIEgx2ZWdhL2VkMjU1MTkYAQ==", - "hexBundle": "0ae2010ab20131663932356263332d363161322d3463336 ... 823766567612f656432353531391801", - "signedTx": { - "sig": { - "algo": "vega/ed25519", - "sig": "0jsqbLcBc4nT4Y4u3OikFGxrmKWUKTLaOPo/zbbMiROJsAzVEXNgLTPhlmKdDA4BQViZSVdgqXvvVCZQC8kACA==", - "version": 1 - }, - "tx": "CrIBMWY5MjViYzMtNjFhMi00YzNiLTg5ZmEtMGJlNDZkYmRhZTQ ... QELfsftyQ==" - } -} -# Note: some fields have been shortened to improve readability -### :example_sign_tx_proposal_response__ - -### __example_sign_tx_vote_response: -# Response for signing the governance vote for the proposed market -{ - "base64Bundle": "AyUUirIBMWY5MjViYzMtNjFhMi00YzNiLTg5ZmEtMGJlNDZkY ... QAIEgx2ZWdhL2VkMjU1MTkYAQ==", - "hexBundle": "0bb2010ab20131663932356263332d363161322d3463336 ... 823766567612f656432353531391801", - "signedTx": { - "sig": { - "algo": "vega/ed25519", - "sig": "0ogeDLcBc4nT4Y4u3OikFGxrmKWUKTLaOPo/zbbMiROJsAzVEXNgLTPhlmKdDA4BQViZSVdgqXvvVCZQC8kACA==", - "version": 1 - }, - "tx": "eeIDSWY5MjViYzMtNjFhMi00YzNiLTg5ZmEtMGJlNDZkYmRhZTQ ... QEFSDftyQ==" - } -} -# Note: some fields have been shortened to improve readability -### :example_sign_tx_vote_response__ - - -### __example_wait_for_market_response: -# Response from a newly enacted market -{ - "id": "P0000006542-0000000001", - "tradableInstrument": { - "instrument": { - "id": "", - "code": "CRYPTO:BTCDAI/DEC20", - "name": "BTC/DAI", - "baseName": "BTC", - "metadata": { - "tags": [] - }, - "initialMarkPrice": "1", - "future": { - "maturity": "2021-06-30T23:59:59Z", - "settlementAsset": "94beaabf8a99450 ... c68357d800dcf52e2f08b50ad89ca37fb3c451fb1", - "quoteName": "DAI", - "ethereumEvent": { - "contractID": "0x0B484706 ... 4b2266446B1cb6d648E3cC1", - "event": "price_changed", - "value": "1500000" - } - } - }, - "marginCalculator": { - "scalingFactors": { - "searchLevel": 1.1, - "initialMargin": 1.2, - "collateralRelease": 1.4 - } - }, - "logNormalRiskModel": { - "riskAversionParameter": 0.01, - "tau": 1.9012853E-6, - "params": { - "mu": 0, - "r": 0.016, - "sigma": 0.05 - } - } - }, - "decimalPlaces": "5", - "fees": { - "factors": { - "makerFee": "0.004", - "infrastructureFee": "0.001", - "liquidityFee": "0.025" - } - }, - "continuous": { - "tickSize": "0.00001" - } -} -# Note: some fields have been shortened to improve readability -### :example_wait_for_market_response__ diff --git a/propose-netparams/README.md b/propose-netparams/README.md deleted file mode 100644 index 6318bd3..0000000 --- a/propose-netparams/README.md +++ /dev/null @@ -1,29 +0,0 @@ -[![Gitpod ready-to-code](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/vegaprotocol/sample-api-scripts) - -# Sample API scripts - Propose Network Parameter Change - -These scripts talk to a Vega node as well as a Vega wallet to propose a change to network parameters: - -- Login to existing wallet -- Select key-pair -- Find an existing asset with a specific name -- Get current time on Vega blockchain -- Prepare and submit a update-network-parameter proposal -- Wait for proposal to be accepted and processed -- Vote on the proposal -- Wait for voting to be enacted - -Please see the documentation on Vega for further information. - -## Python + requests - -Interact with wallet and node API operations using python3 and the [requests](https://pypi.org/project/requests/) library [REST API]: - -```bash -python3 propose-netparams/propose-vote-enact-netparams.py -``` - ---- - -**[Home](../README.md)** - diff --git a/propose-netparams/propose-vote-enact-netparams.py b/propose-netparams/propose-vote-enact-netparams.py deleted file mode 100644 index 32baa91..0000000 --- a/propose-netparams/propose-vote-enact-netparams.py +++ /dev/null @@ -1,321 +0,0 @@ -#!/usr/bin/python3 - -""" -Script language: Python3 - -Talks to: -- Vega node (REST) -- Vega wallet (REST) - -Apps/Libraries: -- REST: requests (https://pypi.org/project/requests/) -""" - -# Note: this file uses smart-tags in comments to section parts of the code to -# show them as snippets in our documentation. They are not necessary to be -# included when creating your own custom code. -# -# Example of smart-tags: -# __something: -# some code here -# :something__ - -import sys -import requests -import time -import os -import helpers - -node_url_rest = os.getenv("NODE_URL_REST") -if not helpers.check_url(node_url_rest): - print("Error: Invalid or missing NODE_URL_REST environment variable.") - exit(1) - -wallet_server_url = os.getenv("WALLETSERVER_URL") - -wallet_name = os.getenv("WALLET_NAME") -if not helpers.check_var(wallet_name): - print("Error: Invalid or missing WALLET_NAME environment variable.") - exit(1) - -wallet_passphrase = os.getenv("WALLET_PASSPHRASE") -if not helpers.check_var(wallet_passphrase): - print("Error: Invalid or missing WALLET_PASSPHRASE environment variable.") - exit(1) - -# Help guide users against including api version suffix on url -wallet_server_url = helpers.check_wallet_url(wallet_server_url) - -##################################################################################### -# W A L L E T S E R V I C E # -##################################################################################### - -print(f"Logging into wallet: {wallet_name}") - -# __login_wallet: -# Log in to an existing wallet -req = {"wallet": wallet_name, "passphrase": wallet_passphrase} -response = requests.post(f"{wallet_server_url}/api/v1/auth/token", json=req) -helpers.check_response(response) -token = response.json()["token"] -# :login_wallet__ - -assert token -print("Logged in to wallet successfully") - -# __get_pubkey: -# List key pairs and select public key to use -headers = {"Authorization": f"Bearer {token}"} -response = requests.get(f"{wallet_server_url}/api/v1/keys", headers=headers) -helpers.check_response(response) -keys = response.json()["keys"] -pubkey = keys[0]["pub"] -# :get_pubkey__ - -assert pubkey -print("Selected pubkey for signing") - -##################################################################################### -# F I N D A S S E T S # -##################################################################################### - -# __get_assets: -# Request a list of assets available on a Vega network -url = f"{node_url_rest}/assets" -response = requests.get(url) -helpers.check_response(response) -# :get_assets__ - -# Debugging -# print("Assets:\n{}".format( -# json.dumps(response.json(), indent=2, sort_keys=True))) - -##################################################################################### -# G O V E R N A N C E T O K E N C H E C K # -##################################################################################### - -# Get the identifier of the governance asset on the Vega network -assets = response.json()["assets"] -vote_asset_id = next((x["id"] for x in assets if x["details"]["symbol"] == "VEGA"), None) -if vote_asset_id is None: - print("VEGA asset not found on specified Vega network, please symbol name check and try again") - sys.exit(1) - -# Request accounts for party and check governance asset balance -url = f"{node_url_rest}/parties/{pubkey}/accounts" -response = requests.get(url) -helpers.check_response(response) - -# Debugging -# print("Accounts:\n{}".format( -# json.dumps(response.json(), indent=2, sort_keys=True))) - -voting_balance = 0 -accounts = response.json()["accounts"] -for account in accounts: - if account["asset"] == vote_asset_id: - print("Found governance asset account") - print(account) - voting_balance = account["balance"] - break - -if voting_balance == 0: - print(f"Please deposit VEGA asset to public key {pubkey} and try again") - sys.exit(1) - -##################################################################################### -# B L O C K C H A I N T I M E # -##################################################################################### - -# __get_time: -# Request the current blockchain time, and convert to time in seconds -response = requests.get(f"{node_url_rest}/time") -helpers.check_response(response) -blockchain_time = int(response.json()["timestamp"]) -blockchain_time_seconds = int(blockchain_time / 1e9) # Seconds precision -# :get_time__ - -assert blockchain_time > 0 -assert blockchain_time_seconds > 0 -print(f"Blockchain time: {blockchain_time} ({blockchain_time_seconds} seconds past epoch)") - -##################################################################################### -# UPDATE NETWORK PARAMETER # -##################################################################################### - -# Step 1 propose a network parameter update - -parameter = "governance.proposal.asset.minEnact" -value = "2m0s" - -# __prepare_propose_updateNetworkParameter: -# Compose a governance proposal for updating a network parameter -proposal_ref = f"{pubkey}-{helpers.generate_id(30)}" - -# Set closing/enactment and validation timestamps to valid time offsets -# from the current Vega blockchain time -closing_time = blockchain_time_seconds + 172800 -enactment_time = blockchain_time_seconds + 172900 -validation_time = blockchain_time_seconds + 1 - -network_param_update = { - "proposalSubmission": { - "reference": proposal_ref, - "rationale": { - "description": "Update network parameter" - }, - "terms": { - "closingTimestamp": closing_time, - "enactmentTimestamp": enactment_time, - "validationTimestamp": validation_time, - "updateNetworkParameter": { - "changes": { - "key": parameter, - "value": value, - } - }, - } - }, - "pubKey": pubkey, - "propagate": True -} - -# __sign_tx_proposal: -# Sign the network param update proposal transaction -# Note: Setting propagate to true will also submit to a Vega node -url = f"{wallet_server_url}/api/v1/command/sync" -response = requests.post(url, headers=headers, json=network_param_update) -helpers.check_response(response) -# :sign_tx_proposal__ - -print("Signed network parameters proposal and sent to Vega") - -# Debugging -print("Signed transaction:\n", response.json(), "\n") - -# Wait for proposal to be included in a block and to be accepted by Vega network -print("Waiting for blockchain...", end="", flush=True) -proposal_id = None -done = False -while not done: - time.sleep(0.5) - print(".", end="", flush=True) - my_proposals = requests.get(node_url_rest + "/parties/" + pubkey + "/proposals") - if my_proposals.status_code != 200: - continue - - for n in my_proposals.json()["data"]: - if n["proposal"]["reference"] == proposal_ref: - proposal_id = n["proposal"]["id"] - print() - if (n["proposal"]['state'] == 'STATE_REJECTED') or (n["proposal"]['state'] == 'STATE_DECLINED') or ( - n["proposal"]['state'] == 'STATE_FAILED'): - print("Your proposal has been " + n["proposal"]['state'] + "!") - print("Due to: " + n["proposal"]["reason"]) - if ( (n["proposal"]["errorDetails"]) != ''):print("Further details: " + n["proposal"]["errorDetails"]) - exit() - else: - print("Your proposal has been accepted by the network!") - print(n) - done = True - break - -assert proposal_id - -##################################################################################### -# V O T E O N P A R A M E T E R # -##################################################################################### - -# STEP 2 - Let's vote on the market proposal - -# IMPORTANT: When voting for a proposal on the Vega Testnet, typically a single -# YES vote from the proposer will not be enough to vote the market into existence. -# This is because of the network minimum threshold for voting on proposals, this -# threshold for market proposals this is currently a 66% majority vote either YES or NO. -# A proposer should enlist the help/YES votes from other community members, ideally on the -# Community forums (https://community.vega.xyz/c/testnet) or Discord (https://vega.xyz/discord) - -# Further documentation on proposal voting and review here: https://docs.testnet.vega.xyz/docs/api-howtos/proposals/ - -# __prepare_vote: -# Prepare a vote for the proposal -vote = { - "voteSubmission": { - "value": "VALUE_YES", # Can be either VALUE_YES or VALUE_NO - "proposalId": proposal_id, - }, - "pubKey": pubkey, - "propagate": True -} -# :prepare_vote__ - -# Debugging -# print("Prepared vote:\n", prepared_vote, "\n") - -# __sign_tx_vote: -# Sign the vote transaction -# Note: Setting propagate to true will also submit to a Vega node -url = f"{wallet_server_url}/api/v1/command/sync" -response = requests.post(url, headers=headers, json=vote) -helpers.check_response(response) -# :sign_tx_vote__ - -print("Signed vote on proposal and sent to Vega") - -# Debugging -# print("Signed transaction:\n", response.json(), "\n") - -print("Waiting for vote on proposal to succeed or fail...", end="", flush=True) -while True: - time.sleep(0.5) - my_proposals = requests.get( - node_url_rest + "/parties/" + pubkey + "/proposals" - ) - if my_proposals.status_code != 200: - continue - - proposal = next((n["proposal"] for n in my_proposals.json()["data"] if n["proposal"]["reference"] == proposal_ref), None) - - if proposal is None or proposal["state"] == "STATE_OPEN": - continue - - if proposal["state"] == "STATE_PASSED": - print("proposal vote has succeeded, waiting for enactment") - continue - - if proposal["state"] == "STATE_ENACTED": - break - - sys.exit(1) - -############################################################################### -# CHECK THE CHANGE # -############################################################################### - -# STEP 3 - Wait for netparameter change to be enacted - -# IMPORTANT: When voting for a proposal on the Vega Testnet, typically a single -# YES vote from the proposer will not be enough to vote the proposal in. -# As described above in STEP 2, a network parameter change will need community voting -# support to be passed and then enacted. - -# __wait_for_market: -print("Waiting for netparam update to be enacted or failed...", end="", flush=True) -done = False -while not done: - time.sleep(0.5) - print(".", end="", flush=True) - netparams = requests.get(node_url_rest + "/network/parameters") - if netparams.status_code != 200: - continue - - print(netparams.json()) - for n in netparams.json()["networkParameters"]: - if n["key"] == parameter: - print() - print(n) - done = True - break -# :wait_for_market__ - -# Completed. diff --git a/propose-votes/README.md b/propose-votes/README.md deleted file mode 100644 index 3cd0314..0000000 --- a/propose-votes/README.md +++ /dev/null @@ -1,27 +0,0 @@ -[![Gitpod ready-to-code](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/vegaprotocol/sample-api-scripts) - -# Sample API scripts - Proposals - -These scripts talk to a Vega node and list governance proposals. -Please see the documentation on Vega for further information. - -## Shell + graphqurl - -List proposals using shell scripts and [graphqurl](https://github.com/hasura/graphqurl) only [GraphQL API]: - -```bash -bash propose-votes/manage-proposals-gql.sh -``` - -## Python + Vega-API-client - -List proposals using python3 and the [Vega-API-client](https://pypi.org/project/Vega-API-client/) library [gRPC API]: - -```bash -python3 propose-votes/manage-proposals-with-Vega-API-client.py -``` - ---- - -**[Home](../README.md)** - diff --git a/propose-votes/manage-proposals-gql.sh b/propose-votes/manage-proposals-gql.sh deleted file mode 100755 index 27ee9fc..0000000 --- a/propose-votes/manage-proposals-gql.sh +++ /dev/null @@ -1,145 +0,0 @@ -#!/usr/bin/env bash - -# Script language: bash - -# Talks to: -# - Vega node (GraphQL) -# -# Apps/Libraries: -# - GraphQL: graphqurl (https://github.com/hasura/graphqurl) -# - REST: curl - -# Note: this file uses smart-tags in comments to section parts of the code to -# show them as snippets in our documentation. They are not necessary to be -# included when creating your own custom code. -# -# Example of smart-tags: -# __something: -# some code here -# :something__ -# - -source helpers.sh -check_url "NODE_URL_GRAPHQL" || exit 1 - -##################################################################################### -# L I S T P R O P O S A L S # -##################################################################################### - -# __get_proposals: -# Request a list of proposals on a Vega network -cat >query <query <query <query <query <query < 0 -print(f"Blockchain time: {blockchain_time}") - -##################################################################################### -# S U B M I T O R D E R # -##################################################################################### - -# __prepare_submit_order: -# Compose your submit order command, with desired deal ticket information -# Set your own user specific reference to find the order in next step and -# as a foreign key to your local client/trading application -order_ref = f"{pubkey}-{uuid.uuid4()}" -order_data = vac.vega.commands.v1.commands.OrderSubmission( - market_id=marketID, - # price is an integer. For example 123456 is a price of 1.23456, - # assuming 5 decimal places. - price="1", - side=vac.vega.vega.Side.SIDE_BUY, - size=10, - expires_at=expiresAt, - time_in_force=vac.vega.vega.Order.TimeInForce.TIME_IN_FORCE_GTT, - type=vac.vega.vega.Order.Type.TYPE_LIMIT, - reference=order_ref -) -# :prepare_submit_order__ - -# __sign_tx_order: -# Sign the transaction with an order submission command -# Note: Setting propagate to true will also submit to a Vega node -submission = { - "orderSubmission": MessageToDict(order_data), - "pubKey": pubkey, - "propagate": True -} -url = f"{wallet_server_url}/api/v1/command/sync" -response = requests.post(url, headers=headers, json=submission) -helpers.check_response(response) -# :sign_tx_order__ - -print("Signed order and sent to Vega") - -# Wait for order submission to be included in a block -print("Waiting for blockchain...") -time.sleep(4) -order_ref_request = vac.data_node.api.v1.trading_data.OrderByReferenceRequest(reference=order_ref) -response = data_client.OrderByReference(order_ref_request) -orderID = response.order.id -orderStatus = helpers.enum_to_str(vac.vega.vega.Order.Status, response.order.status) -createVersion = response.order.version -orderReason = response.order.reason -print(f"Order processed, ID: {orderID}, Status: {orderStatus}, Version: {createVersion}") -if orderStatus == "STATUS_REJECTED": - print(f"Rejection reason: {orderReason}") - -##################################################################################### -# A M E N D O R D E R # -##################################################################################### - -# __prepare_amend_order: -# Compose your amend order command, with changes to your existing order -amend_data = vac.vega.commands.v1.commands.OrderAmendment( - market_id=marketID, - order_id=orderID, - price=vac.vega.vega.Price(value="2"), - time_in_force=vac.vega.vega.Order.TimeInForce.TIME_IN_FORCE_GTC, -) -# :prepare_amend_order__ - -# __sign_tx_amend: -# Sign the prepared order transaction with an order amendment command -# Note: Setting propagate to true will also submit to a Vega node -amendment = { - "orderAmendment": MessageToDict(amend_data), - "pubKey": pubkey, - "propagate": True -} -url = f"{wallet_server_url}/api/v1/command/sync" -response = requests.post(url, headers=headers, json=amendment) -helpers.check_response(response) -# :sign_tx_amend__ - -print("Signed amendment and sent to Vega") - -# Wait for amendment to be included in a block -print("Waiting for blockchain...") -time.sleep(4) -order_id_request = vac.data_node.api.v1.trading_data.OrderByIDRequest(order_id=orderID) -response = data_client.OrderByID(order_id_request) - -orderID = response.order.id -orderPrice = response.order.price -orderSize = response.order.size -orderTif = helpers.enum_to_str(vac.vega.vega.Order.TimeInForce, response.order.time_in_force) -orderStatus = helpers.enum_to_str(vac.vega.vega.Order.Status, response.order.status) -orderVersion = response.order.version -orderReason = response.order.reason - -print("Amended Order:") -print(f"ID: {orderID}, Status: {orderStatus}, Price(Old): 1, " - f"Price(New): {orderPrice}, Size(Old): 100, Size(New): {orderSize}, " - f"TimeInForce(Old): TIME_IN_FORCE_GTT, TimeInForce(New): {orderTif}, " - f"Version(Old): {createVersion}, Version(new): {orderVersion}") -if orderStatus == "STATUS_REJECTED": - print(f"Rejection reason: {orderReason}") - -##################################################################################### -# C A N C E L O R D E R S # -##################################################################################### - -# Select the mode to cancel orders from the following (comment out others), default = 3 - -# __prepare_cancel_order_req1: -# 1 - Cancel single order for party (pubkey) -cancel_data = vac.vega.commands.v1.commands.OrderCancellation( - # Include party, market and order identifier fields to cancel single order. - market_id=marketID, - order_id=orderID, -) -# :prepare_cancel_order_req1__ - -# __prepare_cancel_order_req2: -# 2 - Cancel all orders on market for party (pubkey) -cancel_data = vac.vega.commands.v1.commands.OrderCancellation( - # Only include market identifier field. - market_id=marketID, -) -# :prepare_cancel_order_req2__ - -# __prepare_cancel_order_req3: -# 3 - Cancel all orders on all markets for party (pubkey) -cancel_data = vac.vega.commands.v1.commands.OrderCancellation( - # No filters, cancel all -) -# :prepare_cancel_order_req3__ - -# __sign_tx_cancel: -# Sign the transaction for cancellation -# Note: Setting propagate to true will also submit to a Vega node -cancellation = { - "orderCancellation": MessageToDict(cancel_data), - "pubKey": pubkey, - "propagate": True -} -url = f"{wallet_server_url}/api/v1/command/sync" -response = requests.post(url, headers=headers, json=cancellation) -helpers.check_response(response) -# :sign_tx_cancel__ - -print("Signed cancellation and sent to Vega") - -# Wait for cancellation to be included in a block -print("Waiting for blockchain...") -time.sleep(4) -order_ref_request = vac.data_node.api.v1.trading_data.OrderByReferenceRequest(reference=order_ref) -response = data_client.OrderByReference(order_ref_request) -orderStatus = helpers.enum_to_str(vac.vega.vega.Order.Status, response.order.status) -orderReason = response.order.reason - -print("Cancelled Order:") -print(f"ID: {orderID}, Status: {orderStatus}") -if orderStatus == "STATUS_REJECTED": - print(f"Rejection reason: {orderReason}") - -# Completed. diff --git a/submit-amend-cancel-orders/submit-amend-cancel-orders.py b/submit-amend-cancel-orders/submit-amend-cancel-orders.py deleted file mode 100644 index 3c0fce7..0000000 --- a/submit-amend-cancel-orders/submit-amend-cancel-orders.py +++ /dev/null @@ -1,294 +0,0 @@ -#!/usr/bin/python3 - -""" -Script language: Python3 - -Talks to: -- Vega wallet (REST) -- Vega node (REST) - -Apps/Libraries: -- REST: requests (https://pypi.org/project/requests/) -""" - -# Note: this file uses smart-tags in comments to section parts of the code to -# show them as snippets in our documentation. They are not necessary to be -# included when creating your own custom code. -# -# Example of smart-tags: -# __something: -# some code here -# :something__ -# - -import os -import requests -import time -import helpers -import uuid -import json - -node_url_rest = os.getenv("NODE_URL_REST") -if not helpers.check_url(node_url_rest): - print("Error: Invalid or missing NODE_URL_REST environment variable.") - exit(1) - -wallet_server_url = os.getenv("WALLETSERVER_URL") -if not helpers.check_url(wallet_server_url): - print("Error: Invalid or missing WALLETSERVER_URL environment variable.") - exit(1) - -wallet_name = os.getenv("WALLET_NAME") -if not helpers.check_var(wallet_name): - print("Error: Invalid or missing WALLET_NAME environment variable.") - exit(1) - -wallet_passphrase = os.getenv("WALLET_PASSPHRASE") -if not helpers.check_var(wallet_passphrase): - print("Error: Invalid or missing WALLET_PASSPHRASE environment variable.") - exit(1) - -# Help guide users against including api version suffix on url -wallet_server_url = helpers.check_wallet_url(wallet_server_url) - -##################################################################################### -# W A L L E T S E R V I C E # -##################################################################################### - -print(f"Logging into wallet: {wallet_name}") - -# __login_wallet: -# Log in to an existing wallet -req = {"wallet": wallet_name, "passphrase": wallet_passphrase} -response = requests.post(f"{wallet_server_url}/api/v1/auth/token", json=req) -helpers.check_response(response) -token = response.json()["token"] -# :login_wallet__ - -assert token != "" -print("Logged in to wallet successfully") - -# __get_pubkey: -# List key pairs and select public key to use -headers = {"Authorization": f"Bearer {token}"} -response = requests.get(f"{wallet_server_url}/api/v1/keys", headers=headers) -helpers.check_response(response) -keys = response.json()["keys"] -pubkey = keys[0]["pub"] -# :get_pubkey__ - -assert pubkey != "" -print("Selected pubkey for signing") - -##################################################################################### -# F I N D M A R K E T # -##################################################################################### - -# __get_market: -# Request the identifier for the market to place on -url = f"{node_url_rest}/markets" -response = requests.get(url) -helpers.check_response(response) -marketID = response.json()["markets"][0]["id"] -# :get_market__ - -assert marketID != "" -marketName = response.json()["markets"][0]["tradableInstrument"]["instrument"]["name"] -print(f"Market found: {marketID} {marketName}") - -##################################################################################### -# B L O C K C H A I N T I M E # -##################################################################################### - -# __get_expiry_time: -# Request the current blockchain time, calculate an expiry time -response = requests.get(f"{node_url_rest}/time") -helpers.check_response(response) -blockchain_time = int(response.json()["timestamp"]) -expiresAt = str(int(blockchain_time + 120 * 1e9)) # expire in 2 minutes -# :get_expiry_time__ - -assert blockchain_time > 0 -print(f"Blockchain time: {blockchain_time}") - -##################################################################################### -# S U B M I T O R D E R # -##################################################################################### - -# __prepare_submit_order: -# Compose your submit order command, with desired deal ticket information -# Set your own user specific reference to find the order in next step and -# as a foreign key to your local client/trading application -order_ref = f"{pubkey}-{uuid.uuid4()}" -submission = { - "orderSubmission": { - "marketId": marketID, - "price": "1", # Note: price is an integer. For example 123456 - "size": "100", # is a price of 1.23456, assuming 5 decimal places. - "side": "SIDE_BUY", - "timeInForce": "TIME_IN_FORCE_GTT", - "expiresAt": expiresAt, - "type": "TYPE_LIMIT", - "reference": order_ref - }, - "pubKey": pubkey, - "propagate": True -} -# :prepare_submit_order__ - -print("Order submission: ", submission) - -# __sign_tx_order: -# Sign the transaction with an order submission command -# Note: Setting propagate to true will also submit to a Vega node -url = f"{wallet_server_url}/api/v1/command/sync" -response = requests.post(url, headers=headers, json=submission) -helpers.check_response(response) -# :sign_tx_order__ - -print(json.dumps(response.json(), indent=4, sort_keys=True)) - -print("Signed order and sent to Vega") - -# Wait for order submission to be included in a block -print("Waiting for blockchain...", end="", flush=True) -url = f"{node_url_rest}/orders/{order_ref}" -response = requests.get(url) -while response.status_code != 200: - time.sleep(0.5) - print(".", end="", flush=True) - response = requests.get(url) - -response_json = response.json() -orderID = response_json["order"]["id"] -orderStatus = response_json["order"]["status"] -createVersion = response_json["order"]["version"] -orderReason = response_json["order"]["reason"] - -print(f"\nOrder processed, ID: {orderID}, Status: {orderStatus}, Version: {createVersion}") -if orderStatus == "STATUS_REJECTED": - print(f"Rejection reason: {orderReason}") - -##################################################################################### -# A M E N D O R D E R # -##################################################################################### - -# __prepare_amend_order: -# Compose your amend order command, with changes to existing order -amendment = { - "orderAmendment": { - "orderId": orderID, - "marketId": marketID, - "price": { - "value": "2" - }, - "sizeDelta": "-25", - "timeInForce": "TIME_IN_FORCE_GTC", - }, - "pubKey": pubkey, - "propagate": True -} -# :prepare_amend_order__ - -print("Order amendment: ", amendment) - -# __sign_tx_amend: -# Sign the transaction with an order amendment command -# Note: Setting propagate to true will also submit to a Vega node -url = f"{wallet_server_url}/api/v1/command/sync" -response = requests.post(url, headers=headers, json=amendment) -helpers.check_response(response) -# :sign_tx_amend__ - -print("Signed amendment and sent to Vega") - -# Wait for amendment to be included in a block -print("Waiting for blockchain...") -time.sleep(3) -url = f"{node_url_rest}/orders/{order_ref}" -response = requests.get(url) -response_json = response.json() -orderID = response_json["order"]["id"] -orderPrice = response_json["order"]["price"] -orderSize = response_json["order"]["size"] -orderTif = response_json["order"]["timeInForce"] -orderStatus = response_json["order"]["status"] -orderVersion = response_json["order"]["version"] -orderReason = response_json["order"]["reason"] - -print("Amended Order:") -print(f"ID: {orderID}, Status: {orderStatus}, Price(Old): 1, " - f"Price(New): {orderPrice}, Size(Old): 100, Size(New): {orderSize}, " - f"TimeInForce(Old): TIME_IN_FORCE_GTT, TimeInForce(New): {orderTif}, " - f"Version(Old): {createVersion}, Version(new): {orderVersion}") -if orderStatus == "STATUS_REJECTED": - print(f"Rejection reason: {orderReason}") - -##################################################################################### -# C A N C E L O R D E R S # -##################################################################################### - -# Select the mode to cancel orders from the following (comment out others), default = 3 - -# __prepare_cancel_order_req1: -# 1 - Cancel single order for party (pubkey) -cancellation = { - "orderCancellation": { - # Include market and order identifier fields to cancel single order. - "marketId": marketID, - "orderId": orderID, - }, - "pubKey": pubkey, - "propagate": True, -} -# :prepare_cancel_order_req1__ - -# __prepare_cancel_order_req2: -# 2 - Cancel all orders on market for party (pubkey) -cancellation = { - "orderCancellation": { - # Only include market identifier field. - "marketId": marketID, - }, - "pubKey": pubkey, - "propagate": True, -} -# :prepare_cancel_order_req2__ - -# __prepare_cancel_order_req3: -# 3 - Cancel all orders on all markets for party (pubkey) -cancellation = { - "orderCancellation": {}, - "pubKey": pubkey, - "propagate": True, -} -# :prepare_cancel_order_req3__ - -print("Order cancellation: ", cancellation) - -# __sign_tx_cancel: -# Sign the transaction for cancellation -# Note: Setting propagate to true will also submit to a Vega node -url = f"{wallet_server_url}/api/v1/command/sync" -response = requests.post(url, headers=headers, json=cancellation) -helpers.check_response(response) -# :sign_tx_cancel__ - -print("Signed cancellation and sent to Vega") - -# Wait for cancellation to be included in a block -print("Waiting for blockchain...") -time.sleep(3) -url = f"{node_url_rest}/orders/{order_ref}" -response = requests.get(url) -response_json = response.json() -orderID = response_json["order"]["id"] -orderStatus = response_json["order"]["status"] -orderReason = response_json["order"]["reason"] - -print("Cancelled Order:") -print(f"ID: {orderID}, Status: {orderStatus}") -if orderStatus == "STATUS_REJECTED": - print(f"Rejection reason: {orderReason}") - -# Completed. diff --git a/submit-amend-cancel-orders/submit-amend-cancel-orders.sh b/submit-amend-cancel-orders/submit-amend-cancel-orders.sh deleted file mode 100755 index 1837f74..0000000 --- a/submit-amend-cancel-orders/submit-amend-cancel-orders.sh +++ /dev/null @@ -1,280 +0,0 @@ -#!/usr/bin/env bash - -# Script language: bash - -# Talks to: -# - Vega wallet (REST) -# - Vega node (REST) -# -# Apps/Libraries: -# - REST: curl - -# Note: this file uses smart-tags in comments to section parts of the code to -# show them as snippets in our documentation. They are not necessary to be -# included when creating your own custom code. -# -# Example of smart-tags: -# __something: -# some code here -# :something__ -# - -source helpers.sh - -check_url "NODE_URL_REST" || exit 1 -check_url "WALLETSERVER_URL" || exit 1 - -check_var "WALLET_NAME" || exit 1 -check_var "WALLET_PASSPHRASE" || exit 1 - -##################################################################################### -# W A L L E T S E R V I C E # -##################################################################################### - -echo "Logging into wallet: $WALLET_NAME" - -# __login_wallet: -# Log in to an existing wallet -req='{"wallet": "'"$WALLET_NAME"'","passphrase": "'"$WALLET_PASSPHRASE"'"}' -url="$WALLETSERVER_URL/api/v1/auth/token" -response="$(curl -s -XPOST -d "$req" "$url")" -token="$(echo "$response" | jq -r .token)" -# :login_wallet__ - -test "$token" == null && exit 1 -echo "Logged in to wallet successfully" - -# __get_pubkey: -# List key pairs and select public key to use -hdr="Authorization: Bearer $token" -url="$WALLETSERVER_URL/api/v1/keys" -response="$(curl -s -XGET -H "$hdr" "$url")" -pubKey="$(echo "$response" | jq -r '.keys[0].pub')" -# :get_pubkey__ - -test -n "$pubKey" || exit 1 -test "$pubKey" == null && exit 1 -echo "Selected pubkey for signing" - -##################################################################################### -# F I N D M A R K E T # -##################################################################################### - -# __get_market: -# Request the identifier for the market to place on -url="$NODE_URL_REST/markets" -response="$(curl -s "$url")" -marketID="$(echo "$response" | jq -r '.markets[0].id')" -# :get_market__ - -echo "Market found: $marketID" - -##################################################################################### -# B L O C K C H A I N T I M E # -##################################################################################### - -# __get_expiry_time: -# Request the current blockchain time, calculate an expiry time -url="$NODE_URL_REST/time" -response="$(curl -s "$url")" -blockchaintime="$(echo "$response" | jq -r .timestamp)" -expiresAt="$((blockchaintime+120*10**9))" # expire in 2 minutes -# :get_expiry_time__ - -echo "Blockchain time: $expiresAt" - -##################################################################################### -# S U B M I T O R D E R # -##################################################################################### - -# __prepare_submit_order: -# Compose your submit order command, with desired deal ticket information -# Set your own user specific reference to find the order in next step and -# as a foreign key to your local client/trading application -orderRef=$pubKey-$(shuf -i 11111111-99999999 -n 1)-$(shuf -i 1111-9999 -n 1)-$(shuf -i 111111111111-999999999999 -n 1) - -# Note: price is an integer. For example 123456 is a price of 1.23456, -# assuming 5 decimal places. -submission=$(cat <<-END -"orderSubmission": { - "marketId": "$marketID", - "price": "1", - "size": "10", - "side": "SIDE_BUY", - "timeInForce": "TIME_IN_FORCE_GTT", - "expiresAt": "$expiresAt", - "type": "TYPE_LIMIT", - "reference": "$orderRef" -} -END -) -# :prepare_submit_order__ - -echo "Order submission: $submission" - -# __sign_tx_order: -# Sign the transaction with an order submission command -# Note: Setting propagate to true will also submit to a Vega node -cat >req.json <req.json <req.json <req.json <req.json <req.json < 0 -print(f"Blockchain time: {blockchain_time}") - -##################################################################################### -# S U B M I T P E G G E D O R D E R # -##################################################################################### - -# __prepare_submit_pegged_order: -# Compose your submit order command with a pegged BUY order -# Set your own user specific reference to find the order in next step and -# as a foreign key to your local client/trading application -order_ref = f"{pubkey}-{uuid.uuid4()}" -order_data = vac.vega.commands.v1.commands.OrderSubmission( - market_id=marketID, - side=vac.vega.vega.Side.SIDE_BUY, - size=50, - expires_at=expiresAt, - time_in_force=vac.vega.vega.Order.TimeInForce.TIME_IN_FORCE_GTT, - type=vac.vega.vega.Order.Type.TYPE_LIMIT, - pegged_order=vac.vega.vega.PeggedOrder( - offset=-5, - reference=vac.vega.vega.PEGGED_REFERENCE_MID - ), - reference=order_ref -) -# :prepare_submit_pegged_order__ - -# __sign_tx_pegged_order: -# Sign the transaction with an order submission command -# Note: Setting propagate to true will also submit to a Vega node -submission = { - "orderSubmission": MessageToDict(order_data), - "pubKey": pubkey, - "propagate": True -} -url = f"{wallet_server_url}/api/v1/command/sync" -response = requests.post(url, headers=headers, json=submission) -helpers.check_response(response) -# :sign_tx_pegged_order__ - -print("Signed pegged order and sent to Vega") - -# Wait for order submission to be included in a block -print("Waiting for blockchain...") -time.sleep(4) -order_ref_request = vac.data_node.api.v1.trading_data.OrderByReferenceRequest(reference=order_ref) -response = data_client.OrderByReference(order_ref_request) -orderID = response.order.id -orderStatus = helpers.enum_to_str(vac.vega.vega.Order.Status, response.order.status) -createVersion = response.order.version -orderReason = response.order.reason - -print(f"\nPegged order processed, ID: {orderID}, Status: {orderStatus}, Version: {createVersion}") - -if orderStatus == "STATUS_REJECTED": - print(f"Rejection reason: {orderReason}") -else: - print(f"Pegged at:\n{response.order.pegged_order}") - -##################################################################################### -# A M E N D P E G G E D O R D E R # -##################################################################################### - -# __prepare_amend_pegged_order: -# Compose your amend order command, with changes to your existing order -amend_data = vac.vega.commands.v1.commands.OrderAmendment( - market_id=marketID, - order_id=orderID, - size_delta=-25, - time_in_force=vac.vega.vega.Order.TimeInForce.TIME_IN_FORCE_GTC, - pegged_reference=vac.vega.vega.PEGGED_REFERENCE_BEST_BID, - pegged_offset=Int64Value(value=-100) -) -# :prepare_amend_pegged_order__ - -print(f"Amendment prepared for order ID: {orderID}") - -# __sign_tx_pegged_amend: -# Sign the prepared order transaction with an order amendment command -# Note: Setting propagate to true will also submit to a Vega node -amendment = { - "orderAmendment": MessageToDict(amend_data), - "pubKey": pubkey, - "propagate": True -} -url = f"{wallet_server_url}/api/v1/command/sync" -response = requests.post(url, headers=headers, json=amendment) -helpers.check_response(response) -# :sign_tx_pegged_amend__ - -print("Signed pegged order amendment and sent to Vega") - -# Wait for amendment to be included in a block -print("Waiting for blockchain...") -time.sleep(4) -order_id_request = vac.data_node.api.v1.trading_data.OrderByIDRequest(order_id=orderID) -response = data_client.OrderByID(order_id_request) -orderID = response.order.id -orderPrice = response.order.status -orderSize = response.order.size -orderTif = helpers.enum_to_str(vac.vega.vega.Order.TimeInForce, response.order.time_in_force) -orderStatus = helpers.enum_to_str(vac.vega.vega.Order.Status, response.order.status) -orderVersion = response.order.version -orderReason = response.order.reason - -print("Amended pegged order:") -print(f"ID: {orderID}, Status: {orderStatus}, " - f"Size(Old): 50, Size(New): {orderSize}, " - f"TimeInForce(Old): TIME_IN_FORCE_GTT, TimeInForce(New): {orderTif}, " - f"Version(Old): {createVersion}, Version(new): {orderVersion}") - -if orderStatus == "STATUS_REJECTED": - print(f"Rejection reason: {orderReason}") -else: - print(f"Pegged at:\n{response.order.pegged_order}") - -# Completed. diff --git a/submit-amend-pegged-order/submit-amend-pegged-order.py b/submit-amend-pegged-order/submit-amend-pegged-order.py deleted file mode 100644 index 35164a6..0000000 --- a/submit-amend-pegged-order/submit-amend-pegged-order.py +++ /dev/null @@ -1,233 +0,0 @@ -#!/usr/bin/python3 - -""" -Script language: Python3 - -Talks to: -- Vega wallet (REST) -- Vega node (REST) - -Apps/Libraries: -- REST: requests (https://pypi.org/project/requests/) -""" - -# Note: this file uses smart-tags in comments to section parts of the code to -# show them as snippets in our documentation. They are not necessary to be -# included when creating your own custom code. -# -# Example of smart-tags: -# __something: -# some code here -# :something__ -# - -import os -import requests -import time -import helpers -import uuid - -node_url_rest = os.getenv("NODE_URL_REST") -if not helpers.check_url(node_url_rest): - print("Error: Invalid or missing NODE_URL_REST environment variable.") - exit(1) - -wallet_server_url = os.getenv("WALLETSERVER_URL") -if not helpers.check_url(wallet_server_url): - print("Error: Invalid or missing WALLETSERVER_URL environment variable.") - exit(1) - -wallet_name = os.getenv("WALLET_NAME") -if not helpers.check_var(wallet_name): - print("Error: Invalid or missing WALLET_NAME environment variable.") - exit(1) - -wallet_passphrase = os.getenv("WALLET_PASSPHRASE") -if not helpers.check_var(wallet_passphrase): - print("Error: Invalid or missing WALLET_PASSPHRASE environment variable.") - exit(1) - -# Help guide users against including api version suffix on url -wallet_server_url = helpers.check_wallet_url(wallet_server_url) - -##################################################################################### -# W A L L E T S E R V I C E # -##################################################################################### - -print(f"Logging into wallet: {wallet_name}") - -# __login_wallet: -# Log in to an existing wallet -req = {"wallet": wallet_name, "passphrase": wallet_passphrase} -response = requests.post(f"{wallet_server_url}/api/v1/auth/token", json=req) -helpers.check_response(response) -token = response.json()["token"] -# :login_wallet__ - -assert token != "" -print("Logged in to wallet successfully") - -# __get_pubkey: -# List key pairs and select public key to use -headers = {"Authorization": f"Bearer {token}"} -response = requests.get(f"{wallet_server_url}/api/v1/keys", headers=headers) -helpers.check_response(response) -keys = response.json()["keys"] -pubkey = keys[0]["pub"] -# :get_pubkey__ - -assert pubkey != "" -print("Selected pubkey for signing") - -##################################################################################### -# F I N D M A R K E T # -##################################################################################### - -# __get_market: -# Request the identifier for the market to place on -url = f"{node_url_rest}/markets" -response = requests.get(url) -helpers.check_response(response) -marketID = response.json()["markets"][0]["id"] -# :get_market__ - -assert marketID != "" -marketName = response.json()["markets"][0]["tradableInstrument"]["instrument"]["name"] -print(f"Market found: {marketID} {marketName}") - -##################################################################################### -# B L O C K C H A I N T I M E # -##################################################################################### - -# __get_expiry_time: -# Request the current blockchain time, calculate an expiry time -response = requests.get(f"{node_url_rest}/time") -helpers.check_response(response) -blockchain_time = int(response.json()["timestamp"]) -expiresAt = str(int(blockchain_time + 120 * 1e9)) # expire in 2 minutes -# :get_expiry_time__ - -assert blockchain_time > 0 -print(f"Blockchain time: {blockchain_time}") - -##################################################################################### -# S U B M I T P E G G E D O R D E R # -##################################################################################### - -# __prepare_submit_pegged_order: -# Compose your submit pegged order command -# Set your own user specific reference to find the order in next step and -# as a foreign key to your local client/trading application -order_ref = f"{pubkey}-{uuid.uuid4()}" -submission = { - "orderSubmission": { - "marketId": marketID, - "size": "50", - "side": "SIDE_BUY", - "timeInForce": "TIME_IN_FORCE_GTT", - "expiresAt": expiresAt, - "type": "TYPE_LIMIT", - "reference": order_ref, - "peggedOrder": { - "offset": "5", - "reference": "PEGGED_REFERENCE_MID" - } - }, - "pubKey": pubkey, - "propagate": True -} -# :prepare_submit_pegged_order__ - -print("Order submission: ", submission) - -# __sign_tx_pegged_order: -# Sign the transaction with a pegged order submission command -# Note: Setting propagate to true will also submit to a Vega node -url = f"{wallet_server_url}/api/v1/command/sync" -response = requests.post(url, headers=headers, json=submission) -helpers.check_response(response) -# :sign_tx_pegged_order__ - -print("Signed pegged order and sent to Vega") - -# Wait for order submission to be included in a block -print("Waiting for blockchain...", end="", flush=True) -url = f"{node_url_rest}/orders/{order_ref}" -response = requests.get(url) -while response.status_code != 200: - time.sleep(0.5) - print(".", end="", flush=True) - response = requests.get(url) - -response_json = response.json() -orderID = response_json["order"]["id"] -orderStatus = response_json["order"]["status"] -orderPegged = response_json["order"]["peggedOrder"] -createVersion = response_json["order"]["version"] -orderReason = response_json["order"]["reason"] -print(f"\nPegged order processed, ID: {orderID}, Status: {orderStatus}, Version: {createVersion}") -if orderStatus == "STATUS_REJECTED": - print(f"Rejection reason: {orderReason}") -else: - print(f"Pegged at: {orderPegged}") - -##################################################################################### -# A M E N D P E G G E D O R D E R # -##################################################################################### - -# __prepare_amend_pegged_order: -# Compose your amend order command, with changes to existing order -amendment = { - "orderAmendment": { - "orderId": orderID, - "marketId": marketID, - "sizeDelta": "25", - "timeInForce": "TIME_IN_FORCE_GTC", - "peggedReference": "PEGGED_REFERENCE_BEST_BID", - "peggedOffset": "-100", - }, - "pubKey": pubkey, - "propagate": True -} -# :prepare_amend_pegged_order__ - -print("Order amendment: ", amendment) - -# __sign_tx_pegged_amend: -# Sign the transaction with a pegged order amendment command -# Note: Setting propagate to true will also submit to a Vega node -url = f"{wallet_server_url}/api/v1/command/sync" -response = requests.post(url, headers=headers, json=amendment) -helpers.check_response(response) -# :sign_tx_pegged_amend__ - -print("Signed pegged order amendment and sent to Vega") - -# Wait for amendment to be included in a block -print("Waiting for blockchain...") -time.sleep(4) -url = f"{node_url_rest}/orders/{order_ref}" -response = requests.get(url) -response_json = response.json() -orderID = response_json["order"]["id"] -orderPrice = response_json["order"]["price"] -orderSize = response_json["order"]["size"] -orderTif = response_json["order"]["timeInForce"] -orderStatus = response_json["order"]["status"] -orderPegged = response_json["order"]["peggedOrder"] -orderVersion = response_json["order"]["version"] -orderReason = response_json["order"]["reason"] - -print("Amended pegged order:") -print(f"ID: {orderID}, Status: {orderStatus}, " - f"Size(Old): 50, Size(New): {orderSize}, " - f"TimeInForce(Old): TIME_IN_FORCE_GTT, TimeInForce(New): {orderTif}, " - f"Version(Old): {createVersion}, Version(new): {orderVersion}") - -if orderStatus == "STATUS_REJECTED": - print(f"Rejection reason: {orderReason}") -else: - print(f"Pegged at: {orderPegged}") - - -# Completed. diff --git a/submit-amend-pegged-order/submit-amend-pegged-order.sh b/submit-amend-pegged-order/submit-amend-pegged-order.sh deleted file mode 100755 index 81ff811..0000000 --- a/submit-amend-pegged-order/submit-amend-pegged-order.sh +++ /dev/null @@ -1,217 +0,0 @@ -#!/usr/bin/env bash - -# Script language: bash - -# Talks to: -# - Vega wallet (REST) -# - Vega node (REST) -# -# Apps/Libraries: -# - REST: curl - -# Note: this file uses smart-tags in comments to section parts of the code to -# show them as snippets in our documentation. They are not necessary to be -# included when creating your own custom code. -# -# Example of smart-tags: -# __something: -# some code here -# :something__ -# - -source helpers.sh - -check_url "NODE_URL_REST" || exit 1 -check_url "WALLETSERVER_URL" || exit 1 - -check_var "WALLET_NAME" || exit 1 -check_var "WALLET_PASSPHRASE" || exit 1 - -##################################################################################### -# W A L L E T S E R V I C E # -##################################################################################### - -echo "Logging into wallet: $WALLET_NAME" - -# __login_wallet: -# Log in to an existing wallet -req='{"wallet": "'"$WALLET_NAME"'","passphrase": "'"$WALLET_PASSPHRASE"'"}' -url="$WALLETSERVER_URL/api/v1/auth/token" -response="$(curl -s -XPOST -d "$req" "$url")" -token="$(echo "$response" | jq -r .token)" -# :login_wallet__ - -test "$token" == null && exit 1 -echo "Logged in to wallet successfully" - -# __get_pubkey: -# List key pairs and select public key to use -hdr="Authorization: Bearer $token" -url="$WALLETSERVER_URL/api/v1/keys" -response="$(curl -s -XGET -H "$hdr" "$url")" -pubKey="$(echo "$response" | jq -r '.keys[0].pub')" -# :get_pubkey__ - -test -n "$pubKey" || exit 1 -test "$pubKey" == null && exit 1 -echo "Selected pubkey for signing" - -##################################################################################### -# F I N D M A R K E T # -##################################################################################### - -# __get_market: -# Request the identifier for the market to place on -url="$NODE_URL_REST/markets" -response="$(curl -s "$url")" -marketID="$(echo "$response" | jq -r '.markets[0].id')" -# :get_market__ - -echo "Market found: $marketID" - -##################################################################################### -# B L O C K C H A I N T I M E # -##################################################################################### - -# __get_expiry_time: -# Request the current blockchain time, calculate an expiry time -url="$NODE_URL_REST/time" -response="$(curl -s "$url")" -blockchaintime="$(echo "$response" | jq -r .timestamp)" -expiresAt="$((blockchaintime+120*10**9))" # expire in 2 minutes -# :get_expiry_time__ - -echo "Blockchain time: $expiresAt" - -##################################################################################### -# S U B M I T P E G G E D O R D E R # -##################################################################################### - -# __prepare_submit_pegged_order: -# Compose your submit pegged order command - -# Set your own user specific reference to find the order in next step and -# as a foreign key to your local client/trading application -orderRef=$pubKey-$(shuf -i 11111111-99999999 -n 1)-$(shuf -i 1111-9999 -n 1)-$(shuf -i 111111111111-999999999999 -n 1) -submission=$(cat <<-END -"orderSubmission": { - "marketId": "$marketID", - "size": "50", - "side": "SIDE_BUY", - "timeInForce": "TIME_IN_FORCE_GTT", - "expiresAt": "$expiresAt", - "type": "TYPE_LIMIT", - "peggedOrder": { - "offset": "5", - "reference": "PEGGED_REFERENCE_MID" - } -} -END -) -# :prepare_submit_pegged_order__ - -echo "Order submission: $submission" - -# __sign_tx_pegged_order: -# Sign the transaction with an order submission command -# Note: Setting propagate to true will also submit to a Vega node -cat >req.json <req.json <req.json <req.json <query <' call" -tx = base64.b64encode(blob).decode("ascii") -req = {"tx": tx, "pubKey": pubkey, "propagate": False} -response = requests.post( - f"{wallet_server_url}/api/v1/messages", headers=headers, json=req -) -helpers.check_response(response) -signedTx = response.json()["signedTx"] -print("Signed transaction:") -print(json.dumps(signedTx, indent=2, sort_keys=True)) -# :sign_tx__ - - -# __logout_wallet: -# Log out of a wallet -headers = {"Authorization": f"Bearer {token}"} -response = requests.delete( - f"{wallet_server_url}/api/v1/auth/token", headers=headers -) -helpers.check_response(response) -# :logout_wallet__ diff --git a/wallet/wallet.sh b/wallet/wallet.sh deleted file mode 100755 index a672630..0000000 --- a/wallet/wallet.sh +++ /dev/null @@ -1,113 +0,0 @@ -#!/usr/bin/env bash - -# Script language: bash -# -# Talks to: -# - Vega wallet (REST) -# -# Apps/Libraries: -# - REST: curl - -# Note: this file uses smart-tags in comments to section parts of the code to -# show them as snippets in our documentation. They are not necessary to be -# included when creating your own custom code. -# -# Example of smart-tags: -# __something: -# some code here -# :something__ - -source helpers.sh - -check_url "NODE_URL_REST" || exit 1 - -wallet_name=$(shuf -i 11111111-99999999 -n 1)-$(shuf -i 1111-9999 -n 1)-$(shuf -i 111111111111-999999999999 -n 1) -wallet_passphrase=$(shuf -i 11111111-99999999 -n 1)-$(shuf -i 1111-9999 -n 1)-$(shuf -i 111111111111-999999999999 -n 1) - -# __create_wallet: -# Create a new wallet: -req='{"wallet": "'"$wallet_name"'","passphrase": "'"$wallet_passphrase"'"}' -url="$WALLETSERVER_URL/api/v1/wallets" -response="$(curl -s -XPOST -d "$req" "$url")" -token="$(echo "$response" | jq -r .token)" -# :create_wallet__ - - -test "$token" == null && exit 1 - - -# The example below uses the credentials we just created -# and in practice you don't need to log in immediately after -# creating a new wallet, as the response already contains the -# token that you need to authenticate with future requests. - - -# __login_wallet: -# Log in to an existing wallet -req='{"wallet": "'"$wallet_name"'","passphrase": "'"$wallet_passphrase"'"}' -url="$WALLETSERVER_URL/api/v1/auth/token" -response="$(curl -s -XPOST -d "$req" "$url")" -token="$(echo "$response" | jq -r .token)" -# :login_wallet__ - - -test "$token" == null && exit 1 - - -# __generate_keypair: -# Generate a new key pair -hdr="Authorization: Bearer $token" -req='{"passphrase":"'"$wallet_passphrase"'","meta":[{"key":"alias","value":"my_key_alias"}]}' -url="$WALLETSERVER_URL/api/v1/keys" -response="$(curl -s -XPOST -H "$hdr" -d "$req" "$url")" -# :generate_keypair__ - - -pubKey="$(echo "$response" | jq -r .key.pub)" -test -n "$pubKey" || exit 1 -test "$pubKey" == null && exit 1 - - -# __get_keys: -# Request all key pairs -hdr="Authorization: Bearer $token"] -url="$WALLETSERVER_URL/api/v1/keys" -response="$(curl -s -XGET -H "$hdr" "$url")" -# :get_keys__ - - -# __get_key: -# Request a single key pair -hdr="Authorization: Bearer $token" -url="$WALLETSERVER_URL/api/v1/keys/$pubKey" -response="$(curl -s -XGET -H "$hdr" "$url")" -pubKey="$(echo "$response" | jq -r '.keys[0].pub')" -# :get_key__ - - -# __sign_tx: -# Sign a transaction - Note: setting "propagate" to true will also submit the tx to Vega node -hdr="Authorization: Bearer $token" -# blob is an example of base64 data returned from a Vega node 'Prepare' call -blob="ZGF0YSByZXR1cm5lZCBmcm9tIGEgVmVnYSBub2RlICdQcmVwYXJlPG9wZXJhdGlvbj4nIGNhbGw=" -test "$blob" == null && exit 1 -cat >req.json < Date: Mon, 21 Nov 2022 10:31:19 +0000 Subject: [PATCH 02/33] Add python v2 rest API examples --- credentials-template | 24 -- credentials-win-template | 11 - rest/date-range.py | 94 +++++ rest/estimate-fees-and-margin.py | 68 ++++ rest/get-accounts.py | 122 ++++++ rest/get-assets.py | 63 +++ rest/get-balances.py | 81 ++++ rest/get-candles.py | 71 ++++ rest/get-checkpoints.py | 30 ++ rest/get-delegations.py | 91 +++++ rest/get-deposits.py | 74 ++++ rest/get-epochs.py | 54 +++ rest/get-governance-proposals.py | 60 +++ rest/get-governance-votes.py | 42 ++ rest/get-key-rotations.py | 33 ++ rest/get-ledger-entries.py | 64 +++ rest/get-liquidity-provisions.py | 75 ++++ rest/get-margin-levels.py | 89 +++++ rest/get-market-data.py | 79 ++++ rest/get-market-depth.py | 39 ++ rest/get-markets.py | 58 +++ rest/get-network-data-and-limits.py | 47 +++ rest/get-network-parameters.py | 53 +++ rest/get-node-data.py | 73 ++++ rest/get-orders.py | 124 ++++++ rest/get-parties.py | 75 ++++ rest/get-positions.py | 44 +++ rest/get-rewards.py | 124 ++++++ rest/get-staking-data.py | 40 ++ rest/get-statistics.py | 32 ++ rest/get-trades.py | 117 ++++++ rest/get-transfers.py | 66 ++++ rest/get-vega-time.py | 32 ++ rest/get-withdrawals.py | 74 ++++ rest/helpers.py | 196 ++++++++++ rest/login.py | 72 ++++ rest/logout.py | 21 + rest/pagination.py | 159 ++++++++ rest/propose-vote-enact-freeform.py | 250 ++++++++++++ rest/propose-vote-enact-network-params.py | 253 ++++++++++++ rest/propose-vote-enact-new-market.py | 364 ++++++++++++++++++ rest/requirements.txt | 3 + rest/stream-market-data.py | 84 ++++ rest/stream-orders.py | 91 +++++ rest/stream-trades.py | 88 +++++ ...ubmit-amend-cancel-liquidity-commitment.py | 200 ++++++++++ rest/submit-amend-cancel-order.py | 242 ++++++++++++ rest/submit-amend-cancel-pegged-order.py | 229 +++++++++++ vega-config | 20 + vega-config-stagnet1 | 20 + vega-config-stagnet3 | 20 + 51 files changed, 4500 insertions(+), 35 deletions(-) delete mode 100644 credentials-template delete mode 100644 credentials-win-template create mode 100644 rest/date-range.py create mode 100644 rest/estimate-fees-and-margin.py create mode 100644 rest/get-accounts.py create mode 100644 rest/get-assets.py create mode 100644 rest/get-balances.py create mode 100644 rest/get-candles.py create mode 100644 rest/get-checkpoints.py create mode 100644 rest/get-delegations.py create mode 100644 rest/get-deposits.py create mode 100644 rest/get-epochs.py create mode 100644 rest/get-governance-proposals.py create mode 100644 rest/get-governance-votes.py create mode 100644 rest/get-key-rotations.py create mode 100644 rest/get-ledger-entries.py create mode 100644 rest/get-liquidity-provisions.py create mode 100644 rest/get-margin-levels.py create mode 100644 rest/get-market-data.py create mode 100644 rest/get-market-depth.py create mode 100644 rest/get-markets.py create mode 100644 rest/get-network-data-and-limits.py create mode 100644 rest/get-network-parameters.py create mode 100644 rest/get-node-data.py create mode 100644 rest/get-orders.py create mode 100644 rest/get-parties.py create mode 100644 rest/get-positions.py create mode 100644 rest/get-rewards.py create mode 100644 rest/get-staking-data.py create mode 100644 rest/get-statistics.py create mode 100644 rest/get-trades.py create mode 100644 rest/get-transfers.py create mode 100644 rest/get-vega-time.py create mode 100644 rest/get-withdrawals.py create mode 100644 rest/helpers.py create mode 100644 rest/login.py create mode 100644 rest/logout.py create mode 100644 rest/pagination.py create mode 100644 rest/propose-vote-enact-freeform.py create mode 100644 rest/propose-vote-enact-network-params.py create mode 100644 rest/propose-vote-enact-new-market.py create mode 100644 rest/requirements.txt create mode 100644 rest/stream-market-data.py create mode 100644 rest/stream-orders.py create mode 100644 rest/stream-trades.py create mode 100644 rest/submit-amend-cancel-liquidity-commitment.py create mode 100644 rest/submit-amend-cancel-order.py create mode 100644 rest/submit-amend-cancel-pegged-order.py create mode 100644 vega-config create mode 100644 vega-config-stagnet1 create mode 100644 vega-config-stagnet3 diff --git a/credentials-template b/credentials-template deleted file mode 100644 index 29cdfd0..0000000 --- a/credentials-template +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/env bash - -WALLET_NAME="example_wallet_name" -WALLET_PASSPHRASE="example_wallet_passphrase" - -VEGA_MARKET="marketID" - -WALLETSERVER_URL="https://wallet.testnet.vega.xyz" -NODE_URL_REST="https://api.n10.testnet.vega.xyz" -NODE_URL_GRAPHQL="https://api.n10.testnet.vega.xyz/graphql" -NODE_URL_GRPC="api.n10.testnet.vega.xyz:3007" - -# Do not edit below this line: -PYTHONPATH=. -export PYTHONPATH -export NODE_URL_GRPC -export NODE_URL_REST -export NODE_URL_GRAPHQL -export WALLETSERVER_URL -export WALLET_NAME -export WALLET_PASSPHRASE -export VEGA_MARKET - -echo Credentials have been configured diff --git a/credentials-win-template b/credentials-win-template deleted file mode 100644 index 9481ba9..0000000 --- a/credentials-win-template +++ /dev/null @@ -1,11 +0,0 @@ -WALLET_NAME=example_wallet_name -WALLET_PASSPHRASE=example_wallet_passphrase -WALLETSERVER_URL=https://wallet.testnet.vega.xyz -NODE_URL_REST=https://api.n10.testnet.vega.xyz -NODE_URL_GRAPHQL=https://api.10.testnet.vega.xyz/graphql -NODE_URL_GRPC=api.n10.testnet.vega.xyz:3007 - -PYTHONPATH=. -VEGA_MARKET=marketID - -echo Credentials have been configured diff --git a/rest/date-range.py b/rest/date-range.py new file mode 100644 index 0000000..75cebe0 --- /dev/null +++ b/rest/date-range.py @@ -0,0 +1,94 @@ +#!/usr/bin/python3 + +############################################################################### +# D A T E / T I M E R A N G E S # +############################################################################### + +# Querying results within a particular date/time range is available on +# selected Vega data node APIs. +# +# For example, a client may need to look at orders within a specific time +# window or only find trades on a particular market from the last week. +# +# The examples shown below illustrate the basic concepts used with data returned +# from most list endpoints in the Vega APIs, including (but not limited to): +# - Trades +# - Orders +# - Parties +# - Candles ( IMPORTANT: to/from candle time window is specified with to/fromTimestamp) +# - Withdrawals +# - Deposits +# - Ledger entries +# - Balance changes +# - Liquidity provisions +# - etc. +# +# The following parameters are typically used to control pagination: +# dateRange.startTimestamp: Starting timestamp in nanoseconds past epoch +# dateRange.endTimestamp: Ending timestamp in nanoseconds past epoch +# +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers +import datetime + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +# Load Vega market ID +market_id = helpers.env_market_id() +assert market_id != "" + +############################################################################### +# T I M E S T A M P G E N E R A T I O N # +############################################################################### + +# The majority of timestamps seen on Vega's APIs are of type RFC3339Nano, an +# integer based representation of the number of nanoseconds that have passed +# since Thursday 1 January 1970 00:00:00 UTC. +# +# When generating timestamps for a time window to be used in API queries the +# caller needs to pay particular attention to the conversion. In most modern +# programming languages a Unix timestamp can be generated relatively easily. +# +# The code example below shows how to convert a time to nanosecond timestamp +# with a delta in seconds (subtract or add a number of seconds from time now): + +seconds_delta = 60 * 60 * 2 # Minus two hours from date/time now +time_now = datetime.datetime.now() +new_dt = time_now - datetime.timedelta(seconds=seconds_delta) +ns_ts_from = str(int(new_dt.replace(tzinfo=datetime.timezone.utc).timestamp())*1000000000) +ns_ts_to = str(int(time_now.replace(tzinfo=datetime.timezone.utc).timestamp())*1000000000) + +print(f"Current Time: {time_now}") +print(f"Offset Time: {new_dt}") +print(f"Current Timestamp: {ns_ts_to}") +print(f"Offset: {ns_ts_from}") + +# Hint: In a decentralised system such as Vega we need to ideally use the time +# provided by Vega's blockchain. It is advised that the caller use vega time +# (see get-vega-time.py) for more information and examples. +# +# When using a date range, the result set will be paginated and the caller will +# need to page the results (see pagination.py) + +############################################################################### +# T R A D E S D A T E / T I M E R A N G E # +############################################################################### + +# __get_trades_by_market_trades_date_range: +# Request a list of trades for a market for the given date/time window +url = f"{data_node_url_rest}/trades?marketId={market_id}" \ + f"&dateRange.startTimestamp={ns_ts_from}" \ + f"&dateRange.endTimestamp={ns_ts_to}" +print(url) +response = requests.get(url) +helpers.check_response(response) +response_json = response.json() +print("Trades filtered by market (date/time range):\n{}".format( + json.dumps(response_json, indent=2, sort_keys=True) +)) +# :get_trades_by_market_trades_date_range__ diff --git a/rest/estimate-fees-and-margin.py b/rest/estimate-fees-and-margin.py new file mode 100644 index 0000000..1d40831 --- /dev/null +++ b/rest/estimate-fees-and-margin.py @@ -0,0 +1,68 @@ +#!/usr/bin/python3 + +############################################################################### +# E S T I M A T E F E E S & M A R G I N # +############################################################################### + +# How to get Vega account information from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is supported [default page size is 1000] +# -> Check out pagination.py for example usage +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, including: +# filter.partyIds: Vega party ids (public keys) +# filter.marketIds: Vega market ids +# filter.assets: Specific assets e.g. tDAI, tBTC, etc +# filter.accountTypes: Account types e.g. infrastructure, general, etc +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers + +# Vega wallet interaction helper, see login.py for detail +from login import pubkey + +# Load Vega data node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +##################################################################################### +# F E E E S T I M A T I O N # +##################################################################################### + +market_id = helpers.env_market_id() +assert market_id != "" + +# __get_fees_estimate: +# Request to estimate trading fees on a Vega network +order_price = "100000" +order_size = "100" +url = f"{data_node_url_rest}/estimate/fee?marketId={market_id}&price={order_price}&size={order_size}" +response = requests.get(url) +helpers.check_response(response) +estimatedFees = response.json() +print("Estimated fee for order:\n{}".format( + json.dumps(estimatedFees, indent=2, sort_keys=True))) +# :get_fees_estimate__ + +##################################################################################### +# M A R G I N E S T I M A T I O N # +##################################################################################### + +# __get_margins_estimate: +# Request to estimate trading margin on a Vega network +order_price = "600000" +order_size = "10" +order_side = "SIDE_BUY" +order_type = "TYPE_LIMIT" + +url = f"{data_node_url_rest}/estimate/margin?marketId={market_id}&partyId={pubkey}" \ + f"&price={order_price}&size={order_size}&side={order_side}&type={order_type}" +response = requests.get(url) +helpers.check_response(response) +estimatedMargin = response.json() +print("Estimated margin for order:\n{}".format( + json.dumps(estimatedMargin, indent=2, sort_keys=True))) +# :get_margins_estimate__ diff --git a/rest/get-accounts.py b/rest/get-accounts.py new file mode 100644 index 0000000..af5122f --- /dev/null +++ b/rest/get-accounts.py @@ -0,0 +1,122 @@ +#!/usr/bin/python3 + +############################################################################### +# G E T A C C O U N T S # +############################################################################### + +# How to get Vega account information from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is supported [default page size is 1000] +# -> Check out pagination.py for example usage +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, including: +# filter.partyIds: Vega party ids (public keys) +# filter.marketIds: Vega market ids +# filter.assets: Specific assets e.g. tDAI, tBTC, etc +# filter.accountTypes: Account types e.g. infrastructure, general, etc +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers + +# Vega wallet interaction helper, see login.py for detail +from login import pubkey + +# Load Vega data node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +############################################################################### +# A C C O U N T S B Y M A R K E T ( 1 ) # +############################################################################### + +market_id = helpers.env_market_id() +assert market_id != "" +print(f"Market found: {market_id}") + +# __get_accounts_by_market: +# Request a list of accounts for a single market (repeat the filter for multiple markets) +url = f"{data_node_url_rest}/accounts?filter.marketIds={market_id}" +response = requests.get(url) +helpers.check_response(response) +print("Accounts filtered by market:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_accounts_by_market__ + +# Hint: Multiple filtering examples further down in this example script + +############################################################################### +# A C C O U N T S B Y P A R T Y ( 1 ) # +############################################################################### + +# __get_accounts_by_party: +# Request a list of accounts for a single party/pubkey (repeat the filter for multiple parties) +url = f"{data_node_url_rest}/accounts?filter.partyIds={pubkey}" +response = requests.get(url) +helpers.check_response(response) +print("Accounts filtered by party:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_accounts_by_party__ + +# Hint: Multiple filtering examples further down in this example script + +############################################################################### +# A C C O U N T S B Y A S S E T # +############################################################################### + +# Request a list of assets and select the first one +url = f"{data_node_url_rest}/assets" +response = requests.get(url) +helpers.check_response(response) +asset_id = response.json()["assets"]["edges"][0]["node"]["id"] + +assert asset_id != "" +print(f"Asset found: {asset_id}") + +# __get_accounts_by_asset: +# Request a list of accounts for a single asset +url = f"{data_node_url_rest}/accounts?filter.assetId={asset_id}" +response = requests.get(url) +helpers.check_response(response) +print("Accounts filtered by asset:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_accounts_by_asset__ + +############################################################################### +# A C C O U N T S B Y M A R K E T ( 2 ) # +############################################################################### + +# __get_accounts_by_market_filtered: +# Request a list of accounts for a market and asset with a specific account type (general) +url = f"{data_node_url_rest}/accounts?" \ + f"filter.marketIds={market_id}" \ + f"&filter.assetId={asset_id}" \ + f"&filter.accountTypes=ACCOUNT_TYPE_GENERAL" +response = requests.get(url) +helpers.check_response(response) +print("Accounts filtered by market and account type:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_accounts_by_market_filtered__ + +############################################################################### +# A C C O U N T S B Y P A R T Y ( 2 ) # +############################################################################### + +# __get_accounts_by_party_filtered: +# Request a list of accounts for a party with a specific account types (general & margin) +url = f"{data_node_url_rest}/accounts?" \ + f"filter.partyIds={pubkey}" \ + f"&filter.accountTypes=ACCOUNT_TYPE_GENERAL" \ + f"&filter.accountTypes=ACCOUNT_TYPE_MARGIN" +response = requests.get(url) +helpers.check_response(response) +print("Accounts filtered by party and account type:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_accounts_by_party_filtered__ diff --git a/rest/get-assets.py b/rest/get-assets.py new file mode 100644 index 0000000..8618b8a --- /dev/null +++ b/rest/get-assets.py @@ -0,0 +1,63 @@ +#!/usr/bin/python3 + +############################################################################### +# G E T A S S E T S # +############################################################################### + +# How to get Vega asset information from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is supported [default page size is 1000] +# -> Check out pagination.py for example usage +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, including: +# assetId: Vega asset id +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers +import sys + +# Load Vega data node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +############################################################################### +# L I S T A S S E T S # +############################################################################### + +# __get_assets: +# Request a list of assets available and select the first one +url = f"{data_node_url_rest}/assets" +response = requests.get(url) +helpers.check_response(response) +print("Assets:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True))) +# :get_assets__ + +# Find asset with name tDAI (available on Fairground Testnet) +asset_id = None +assets = response.json()["assets"]["edges"] +for asset in assets: + if asset["node"]["details"]["symbol"] == "tDAI": + print("Found an asset with symbol tDAI") + asset_id = asset["node"]["id"] + break + +if asset_id is None: + print("tDAI asset not found on specified Vega network" ) + sys.exit(1) + +############################################################################### +# S I N G L E A S S E T # +############################################################################### + +# __get_asset: +# Request a specific asset using a pre-defined asset id +url = f"{data_node_url_rest}/asset/{asset_id}" +response = requests.get(url) +helpers.check_response(response) +print("Asset:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True))) +# :get_asset__ diff --git a/rest/get-balances.py b/rest/get-balances.py new file mode 100644 index 0000000..ba41e1d --- /dev/null +++ b/rest/get-balances.py @@ -0,0 +1,81 @@ +#!/usr/bin/python3 + +############################################################################### +# G E T H I S T O R I C B A L A N C E S # +############################################################################### + +# How to get balance changes for accounts from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is supported [default page size is 1000] +# -> Check out pagination.py for example usage +# Date Range is supported +# -> Check out date-range.py for example usage +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, including: +# filter.assetId: Specific asset id +# filter.partyIds: Vega party ids (public keys) +# filter.marketIds: Vega market ids +# filter.accountTypes: Account types e.g. infrastructure, general, etc +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers + +# Vega wallet interaction helper, see login.py for detail +from login import pubkey + +# Load Vega data node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +############################################################################### +# B A L A N C E S B Y P A R T Y & A C C O U N T T Y P E # +############################################################################### + +# Hint: Include multiple party ids as repeated filter.partyIds=XYZ query params +# The same principle works for account types as shown below: + +# __get_balances_by_party_and_account_type: +# Request a list of historic balance changes for a Vega party id and account types +url = f"{data_node_url_rest}/balance/changes?filter.partyIds={pubkey}" \ + f"&filter.accountTypes=ACCOUNT_TYPE_GENERAL&filter.accountTypes=ACCOUNT_TYPE_MARGIN" +print(url) +response = requests.get(url) +helpers.check_response(response) +response_json = response.json() +print("Historic balance changes filtered by party and account types:\n{}".format( + json.dumps(response_json, indent=2, sort_keys=True) +)) +# :get_balances_by_party_and_account_type__ + +# Load Vega market id +market_id = helpers.env_market_id() +assert market_id != "" + +############################################################################### +# B A L A N C E S B Y M A R K E T & A C C O U N T T Y P E # +############################################################################### + +# Hint: Include multiple market ids as repeated filter.marketIds=XYZ query params +# This is the same principle as in the previous example + +# __get_balances_by_market_and_account_type: +# Request a list of historic balance changes for a Vega party id and account types +url = f"{data_node_url_rest}/balance/changes?filter.marketIds={market_id}" \ + f"&filter.accountTypes=ACCOUNT_TYPE_MARGIN" +print(url) +response = requests.get(url) +helpers.check_response(response) +response_json = response.json() +print("Historic balance changes filtered by market and account types:\n{}".format( + json.dumps(response_json, indent=2, sort_keys=True) +)) +# __get_balances_by_market_and_account_type: + + + + + + diff --git a/rest/get-candles.py b/rest/get-candles.py new file mode 100644 index 0000000..96a8cab --- /dev/null +++ b/rest/get-candles.py @@ -0,0 +1,71 @@ +#!/usr/bin/python3 + +############################################################################### +# G E T C A N D L E S # +############################################################################### + +# How to get Vega candle (ohlc) information from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is supported [default page size is 1000] +# -> Check out pagination.py for example usage +# ---------------------------------------------------------------------- +# The specific candles are obtained using parameters: +# candleId: Vega candle id (contains interval) see List Candle Intervals +# Date range is supported but by using the following required params: +# fromTimestamp: Starting timestamp for candles in nanoseconds since the epoch +# toTimestamp: Ending timestamp for candles in nanoseconds since the epoch +# +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers + +# Load Vega data node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") +market_id = helpers.env_market_id() + +############################################################################### +# L I S T C A N D L E I N T E R V A L S # +############################################################################### + +# Hint: In order to get candles of a suitable bucket size e.g. 5 minutes and +# market id e.g. 13b081fe5bc8fd256b0a374dc04d94b904118312dd0d942e891a5f57ce0c556c +# you should use the list candle intervals API to get back a candle id: + +# __get_candle_intervals: +# Request a list of candle intervals available for a market and select a candle id +url = f"{data_node_url_rest}/candle/intervals?marketId={market_id}" +response = requests.get(url) +helpers.check_response(response) +print("Candle intervals for market:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True))) +# :get_candle_intervals__ + +# Find the first candle id in the list e.g. trades_candle_5_minutes_ etc +candle_id = response.json()["intervalToCandleId"][0]["candleId"] +assert candle_id != "" +print(f"Candle found: {candle_id}") + +############################################################################### +# C A N D L E S ( F I L T E R E D ) # +############################################################################### + +# Calculate the time window for the candles period to return e.g. last 24 hours +time_now = helpers.ts_now() +fromTime = helpers.get_nano_ts(time_now, 24*60*60) # 1 day ago +toTime = helpers.get_nano_ts(time_now, 0) # to now + +# __get_candles_by_id: +# Request specific candles for a market using candle id (from above) +url = f"{data_node_url_rest}/candle?candleId={candle_id}" \ + f"&fromTimestamp={fromTime}" \ + f"&toTimestamp={toTime}" +print(url) +response = requests.get(url) +helpers.check_response(response) +print("Candles for id and ns timestamp window:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True))) +# :get_candles_by_id__ diff --git a/rest/get-checkpoints.py b/rest/get-checkpoints.py new file mode 100644 index 0000000..c936e9c --- /dev/null +++ b/rest/get-checkpoints.py @@ -0,0 +1,30 @@ +#!/usr/bin/python3 + +############################################################################### +# G E T C H E C K P O I N T S # +############################################################################### + +# How to get checkpoint information from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is supported [default page size is 1000] +# -> Check out pagination.py for example usage +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +# __get_checkpoints: +# Request a list of checkpoints for a Vega network +url = f"{data_node_url_rest}/checkpoints" +response = requests.get(url) +helpers.check_response(response) +print("Checkpoints for network:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_checkpoints__ diff --git a/rest/get-delegations.py b/rest/get-delegations.py new file mode 100644 index 0000000..876bbb4 --- /dev/null +++ b/rest/get-delegations.py @@ -0,0 +1,91 @@ +#!/usr/bin/python3 + +############################################################################### +# G E T D E L E G A T I O N S # +############################################################################### + +# How to get delegation (staking) information from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is supported [default page size is 1000] +# -> Check out pagination.py for example usage +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, including: +# partyId: Vega party id (public key) +# nodeId: Vega node id +# epochId: Vega epoch id +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +############################################################################### +# L I S T D E L E G A T I O N S # +############################################################################### + +# __get_delegations: +# Request a list of all delegations for a Vega network +url = f"{data_node_url_rest}/delegations" +response = requests.get(url) +helpers.check_response(response) +print("Delegations for network:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_delegations__ + +# Find the first delegation in the list (above) and set epochId / nodeId vars +first_delegation = helpers.get_nested_response(response, "delegations")[0] +nodeId = first_delegation["node"]["nodeId"] +epochId = first_delegation["node"]["epochSeq"] +partyId = first_delegation["node"]["party"] + +# Tip: You can combine the filters epochId, partyId, and nodeId to refine the +# returned delegation data, for instance, all delegations for party to a node +# Each filter is shown below, but they can be combined as described... + +############################################################################### +# D E L E G A T I O N S B Y P A R T Y # +############################################################################### + +# __get_delegations_by_party: +# Request a list of all delegations for a party (pubkey) +url = f"{data_node_url_rest}/delegations?partyId={partyId}" +response = requests.get(url) +helpers.check_response(response) +print("Delegations filtered by party:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_delegations_by_party__ + +############################################################################### +# D E L E G A T I O N S B Y E P O C H # +############################################################################### + +# __get_delegations_by_epoch: +# Request a list of all delegations for a specific epoch number +url = f"{data_node_url_rest}/delegations?epochId={epochId}" +response = requests.get(url) +helpers.check_response(response) +print("Delegations filtered by epoch:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_delegations_by_epoch__ + +############################################################################### +# D E L E G A T I O N S B Y N O D E # +############################################################################### + +# __get_delegations_by_epoch: +# Request a list of all delegations for a specific Vega node +url = f"{data_node_url_rest}/delegations?nodeId={nodeId}" +response = requests.get(url) +helpers.check_response(response) +print("Delegations filtered by Vega node:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_delegations_by_epoch__ diff --git a/rest/get-deposits.py b/rest/get-deposits.py new file mode 100644 index 0000000..827efa4 --- /dev/null +++ b/rest/get-deposits.py @@ -0,0 +1,74 @@ +#!/usr/bin/python3 + +############################################################################### +# G E T D E P O S I T S # +############################################################################### + +# How to get deposit information from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is supported [default page size is 1000] +# -> Check out pagination.py for example usage +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, including: +# partyId: Vega party id (public key) +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers + +# Vega wallet interaction helper, see login.py for detail +from login import pubkey + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +############################################################################### +# L I S T D E P O S I T S # +############################################################################### + +# __get_deposits: +# Request a list of deposits for a Vega network +url = f"{data_node_url_rest}/deposits" +response = requests.get(url) +helpers.check_response(response) +print("Deposits for network:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_deposits__ + +# Find the first deposit in the list (above) if it exists +deposit_id = "3a834328d835cf79880dfc238a989c238fe32a62562690d717ab1ff42ad5003f" +if helpers.check_nested_response(response, "deposits"): + first_deposit = helpers.get_nested_response(response, "deposits")[0]["node"] + deposit_id = first_deposit["id"] + +############################################################################### +# D E P O S I T S B Y P A R T Y # +############################################################################### + +# __get_deposits_by_party: +# Request a list of deposits for a party on a Vega network +url = f"{data_node_url_rest}/deposits?partyId={pubkey}" +response = requests.get(url) +helpers.check_response(response) +print("Deposits for a specific party:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_deposits_by_party__ + +############################################################################### +# D E P O S I T B Y I D # +############################################################################### + +# __get_deposit_by_id: +# Request a single deposit for deposit id +url = f"{data_node_url_rest}/deposit/{deposit_id}" +response = requests.get(url) +helpers.check_response(response) +print("Deposit for id:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_deposit_by_id__ diff --git a/rest/get-epochs.py b/rest/get-epochs.py new file mode 100644 index 0000000..cf2d6c9 --- /dev/null +++ b/rest/get-epochs.py @@ -0,0 +1,54 @@ +#!/usr/bin/python3 + +############################################################################### +# G E T E P O C H S D A T A # +############################################################################### + +# How to get epoch information from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is NOT supported on this endpoint. +# ---------------------------------------------------------------------- +# The list can be optionally filtered by: +# id: Vega epoch id (also referred to as the epochSeq field) +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +############################################################################### +# L I S T E P O C H S # +############################################################################### + +# __get_epochs: +# Request all epoch data for a Vega network +url = f"{data_node_url_rest}/epoch" +response = requests.get(url) +helpers.check_response(response) +print("Epoch data for network:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_epochs__ + +# Find the first delegation in the list (above) +first_delegation = response.json()["epoch"]["delegations"][0] +epoch_id = first_delegation["epochSeq"] + +############################################################################### +# E P O C H B Y I D # +############################################################################### + +# __get_epochs_by_id: +# Request epoch data for a specific epoch id +url = f"{data_node_url_rest}/epoch?id={epoch_id}" +response = requests.get(url) +helpers.check_response(response) +print("Epoch data for epoch id:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_epochs_by_id__ diff --git a/rest/get-governance-proposals.py b/rest/get-governance-proposals.py new file mode 100644 index 0000000..be6b2a7 --- /dev/null +++ b/rest/get-governance-proposals.py @@ -0,0 +1,60 @@ +#!/usr/bin/python3 + +############################################################################### +# G E T G O V E R N A N C E P R O P O S A L S # +############################################################################### + +# How to get proposals information from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is supported [default page size is 1000] +# -> Check out pagination.py for example usage +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, including: +# proposalState: Proposal state e.g. STATE_OPEN +# proposalType: Proposal type e.g. TYPE_NEW_MARKET +# proposerPartyId: Party id (public key) of a proposer +# proposalReference: Custom proposal reference (set by the proposer) +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +############################################################################### +# L I S T P R O P O S A L S # +############################################################################### + +# __get_proposals: +# Request proposal data for a Vega network +url = f"{data_node_url_rest}/governances" +response = requests.get(url) +helpers.check_response(response) +print("Governance (proposals) data for network:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_proposals__ + +# Find the first delegation in the list (above) +first_proposal = response.json()["connection"]["edges"][0]["node"]["proposal"] +proposal_id = first_proposal["id"] + +############################################################################### +# P R O P O S A L B Y I D # +############################################################################### + +print(f"Governance proposal for id: {proposal_id}") + +# __get_proposal_by_id: +# Request proposal data for a specific proposal id +url = f"{data_node_url_rest}/governance?proposalId={proposal_id}" +response = requests.get(url) +helpers.check_response(response) +print("Proposal:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_proposal_by_id__ diff --git a/rest/get-governance-votes.py b/rest/get-governance-votes.py new file mode 100644 index 0000000..49e2c3d --- /dev/null +++ b/rest/get-governance-votes.py @@ -0,0 +1,42 @@ +#!/usr/bin/python3 + +############################################################################### +# G E T G O V E R N A N C E V O T E S # +############################################################################### + +# How to get votes information from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is supported [default page size is 1000] +# -> Check out pagination.py for example usage +# ---------------------------------------------------------------------- +# The list must be filtered by at least one of the following parameters: +# partyId: Vega party id (public key) +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +############################################################################### +# L I S T V O T E S # +############################################################################### + +# Load Vega party id +party_id = helpers.env_party_id() +assert party_id != "" + +# __get_votes: +# Request vote data for a Vega network +url = f"{data_node_url_rest}/votes?partyId={party_id}" +print(url) +response = requests.get(url) +helpers.check_response(response) +print("Governance (votes) data for network:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_votes__ diff --git a/rest/get-key-rotations.py b/rest/get-key-rotations.py new file mode 100644 index 0000000..d26d38f --- /dev/null +++ b/rest/get-key-rotations.py @@ -0,0 +1,33 @@ +#!/usr/bin/python3 + +############################################################################### +# G E T K E Y R O T A T I O N S # +############################################################################### + +# How to get key rotation information from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is supported [default page size is 1000] +# -> Check out pagination.py for example usage +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, including: +# nodeId: Vega node id +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +# __get_key_rotations: +# Request a list of key rotations for a Vega network +url = f"{data_node_url_rest}/vega/keys/rotations" +response = requests.get(url) +helpers.check_response(response) +print("Key rotations for network:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_key_rotations__ diff --git a/rest/get-ledger-entries.py b/rest/get-ledger-entries.py new file mode 100644 index 0000000..f9a4e4f --- /dev/null +++ b/rest/get-ledger-entries.py @@ -0,0 +1,64 @@ +#!/usr/bin/python3 + +############################################################################### +# G E T L E D G E R E N T R I E S # +############################################################################### + +# How to get ledger entries from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is supported [default page size is 1000] +# -> Check out pagination.py for example usage +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, including: + +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers + +# Vega wallet interaction helper, see login.py for detail +# from login import pubkey + +# Load Vega data node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +############################################################################### +# L I S T L E D G E R E N T R I E S # +############################################################################### + +party_id = helpers.env_party_id() +assert party_id != "" +party_id = "d8742dbe34198241b96381012be71615a48da2b1c60f76f25ae5ed87fea9c500" + +# __get_ledger_entries_from_account: +# List ledger entries with filtering on the sending account (accountFrom...) +url = f"{data_node_url_rest}/ledgerentry/history?filter.accountFromFilter.partyIds={party_id}" +print(url) +response = requests.get(url) +helpers.check_response(response) +response_json = response.json() +print("Ledger entries (sending account):\n{}".format( + json.dumps(response_json, indent=2, sort_keys=True) +)) +# :get_ledger_entries_from_account__ + + +# __get_ledger_entries_to_account: +# List ledger entries with filtering on the receiving account (accountFrom...) +url = f"{data_node_url_rest}/ledgerentry/history?filter.accountToFilter.partyIds={party_id}" +print(url) +response = requests.get(url) +helpers.check_response(response) +response_json = response.json() +print("Ledger entries (receiving account):\n{}".format( + json.dumps(response_json, indent=2, sort_keys=True) +)) +# :get_ledger_entries_to_account__ + +# todo: can also refine further with a particular asset id, market id or account type +# todo: can also refine further with a particular asset id, market id or account type +# todo: list ledger entries with filtering on the sending AND receiving account +# todo: list ledger entries with filtering on the transfer type (on top of above or as a standalone) diff --git a/rest/get-liquidity-provisions.py b/rest/get-liquidity-provisions.py new file mode 100644 index 0000000..42c3bd9 --- /dev/null +++ b/rest/get-liquidity-provisions.py @@ -0,0 +1,75 @@ +#!/usr/bin/python3 + +############################################################################### +# G E T L I Q U I D I T Y P R O V I S I O N S # +############################################################################### + +# How to get LP information from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is supported [default page size is 1000] +# -> Check out pagination.py for example usage +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, including: +# partyId: Vega party id (public key) +# marketId: Vega market id +# reference: A unique/custom reference +# Note that with a reference, a marketId or partyId is also required +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") +market_id = helpers.env_market_id() + +############################################################################### +# L P S B Y M A R K E T # +############################################################################### + +# __get_lps_by_market: +# Request liquidity provisions for a market on a Vega network +url = f"{data_node_url_rest}/liquidity/provisions?marketId={market_id}" +response = requests.get(url) +helpers.check_response(response) +print("Liquidity Provisions for market:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_lps_by_market__ + +# Find the first delegation in the list (above) +first_lp = response.json()["liquidityProvisions"]["edges"][0]["node"] +party_id = first_lp["partyId"] +custom_ref = first_lp["reference"] + +############################################################################### +# L P S B Y P A R T Y # +############################################################################### + +# __get_lps_by_party: +# Request liquidity provisions for a party on a Vega network +url = f"{data_node_url_rest}/liquidity/provisions?partyId={party_id}" +response = requests.get(url) +helpers.check_response(response) +print("Liquidity Provisions for party:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_lps_by_party__ + +############################################################################### +# L P S B Y R E F E R E N C E # +############################################################################### + +# __get_lps_by_reference: +# Request liquidity provisions for a reference on a Vega network +# Note: A partyId or marketId must be supplied with the reference field +url = f"{data_node_url_rest}/liquidity/provisions?marketId={market_id}&reference={custom_ref}" +response = requests.get(url) +helpers.check_response(response) +print("Liquidity Provisions for reference:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_lps_by_reference__ diff --git a/rest/get-margin-levels.py b/rest/get-margin-levels.py new file mode 100644 index 0000000..41ac30c --- /dev/null +++ b/rest/get-margin-levels.py @@ -0,0 +1,89 @@ +#!/usr/bin/python3 + +############################################################################### +# G E T M A R G I N L E V E L S # +############################################################################### + +# How to get margin level information from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is supported [default page size is 1000] +# -> Check out pagination.py for example usage +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, including: +# partyId: Vega party id (public key) +# marketId: Vega market id +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") +market_id = helpers.env_market_id() +party_id = helpers.env_party_id() + +############################################################################### +# L I S T M A R G I N L E V E L S # +############################################################################### + +# __get_margin_levels: +# Request all margin level data for a Vega network +url = f"{data_node_url_rest}/margin/levels" +response = requests.get(url) +helpers.check_response(response) +print("Margin level data for network:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_margin_levels__ + +# Find the first party and market id in the list (above) if they exists +# Hint: Comment out following 4 lines to always use env party/market id values +if helpers.check_nested_response(response, "marginLevels"): + first_level = helpers.get_nested_response(response, "marginLevels")[0]["node"] + party_id = first_level["partyId"] + market_id = first_level["marketId"] + +############################################################################### +# M A R G I N L E V E L S B Y P A R T Y # +############################################################################### + +# __get_margin_levels_by_party: +# Request margin level data for a specific party id (pubkey) +url = f"{data_node_url_rest}/margin/levels?partyId={party_id}" +response = requests.get(url) +helpers.check_response(response) +print("Margin level data for party:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_margin_levels_by_party__ + +############################################################################### +# M A R G I N L E V E L S B Y M A R K E T # +############################################################################### + +# __get_margin_levels_by_market: +# Request margin level data for a specific market id +url = f"{data_node_url_rest}/margin/levels?marketId={market_id}" +response = requests.get(url) +helpers.check_response(response) +print("Margin level data for market:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_margin_levels_by_market__ + +############################################################################### +# M A R G I N L E V E L S B Y M A R K E T & P A R T Y # +############################################################################### + +# __get_margin_levels_by_market_and_party: +# Request margin level data for a specific market and party id +url = f"{data_node_url_rest}/margin/levels?marketId={market_id}&partyId={party_id}" +response = requests.get(url) +helpers.check_response(response) +print("Margin level data for market and party:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_margin_levels_by_market_and_party__ diff --git a/rest/get-market-data.py b/rest/get-market-data.py new file mode 100644 index 0000000..bc573e2 --- /dev/null +++ b/rest/get-market-data.py @@ -0,0 +1,79 @@ +#!/usr/bin/python3 + +############################################################################### +# G E T M A R K E T D A T A # +############################################################################### + +# How to get market data from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is supported [default page size is 1000] +# -> Check out pagination.py for example usage +# Date Range is supported +# -> Check out date-range.py for example usage +# ---------------------------------------------------------------------- +# The following path parameter is required when getting latest data and +# historic data, it is not required for listing market data for all markets: +# marketId: Vega market id +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +# Load Vega market id +market_id = helpers.env_market_id() + +############################################################################### +# M A R K E T D A T A H I S T O R Y # +############################################################################### + +# __get_market_data: +# Calculate the time window for the history period to return e.g. last 24 hours +time_now = helpers.ts_now() +fromTime = helpers.get_nano_ts(time_now, 24*60*60) # 1 day ago +toTime = helpers.get_nano_ts(time_now, 0) # to now + +# Request market data history for a specific market using a market id +# Important! The startTimestamp and endTimestamp are REQUIRED fields +url = f"{data_node_url_rest}/market/data/{market_id}?startTimestamp={fromTime}&endTimestamp={toTime}" +print(url) +response = requests.get(url) +helpers.check_response(response) +print("Market data:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_market_data__ + +############################################################################### +# L A T E S T M A R K E T D A T A # +############################################################################### + +# __get_latest_market_data: +# Request market data for a specific market using a market id +url = f"{data_node_url_rest}/market/data/{market_id}/latest" +response = requests.get(url) +helpers.check_response(response) +print("Market data for market:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_latest_market_data__ + +############################################################################### +# M A R K E T S D A T A # +############################################################################### + +# __get_markets_data: +# Request latest market data for ALL markets on a Vega network +url = f"{data_node_url_rest}/markets/data" +response = requests.get(url) +helpers.check_response(response) +print("Markets data:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_markets_data__ + diff --git a/rest/get-market-depth.py b/rest/get-market-depth.py new file mode 100644 index 0000000..70d60e0 --- /dev/null +++ b/rest/get-market-depth.py @@ -0,0 +1,39 @@ +#!/usr/bin/python3 + +############################################################################### +# G E T M A R K E T D E P T H # +############################################################################### + +# How to get market depth information from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is NOT supported on this endpoint. +# ---------------------------------------------------------------------- +# The following path parameter is required: +# marketId: Vega market id +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, including: +# maxDepth: Maximum number of levels to return +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +# Load Vega market id +market_id = helpers.env_market_id() +assert market_id != "" + +# __get_market_depth: +# Request market depth for a specific market using a pre-defined market id +url = f"{data_node_url_rest}/market/depth/{market_id}/latest?maxDepth=50" +response = requests.get(url) +helpers.check_response(response) +print("Market depth for market:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_market_depth__ diff --git a/rest/get-markets.py b/rest/get-markets.py new file mode 100644 index 0000000..1051859 --- /dev/null +++ b/rest/get-markets.py @@ -0,0 +1,58 @@ +#!/usr/bin/python3 + +############################################################################### +# G E T M A R K E T S # +############################################################################### + +# How to get market information from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is supported [default page size is 1000] +# -> Check out pagination.py for example usage +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +############################################################################### +# L I S T M A R K E T S # +############################################################################### + +# __get_markets: +# Request a list of markets on a Vega network +url = f"{data_node_url_rest}/markets" +print(url) +response = requests.get(url) +helpers.check_response(response) +response_json = response.json() +print("Markets:\n{}".format( + json.dumps(response_json, indent=2, sort_keys=True) +)) +# :get_markets__ + +# Find the first market in the list (above) if it exists +market_id = "6a834328d835ca79880dfc238a989c238fe32a62562690d717ab1ff42ad5004d" +if helpers.check_nested_response(response, "markets"): + first_market = helpers.get_nested_response(response, "markets")[0]["node"] + market_id = first_market["id"] + +############################################################################### +# M A R K E T B Y I D # +############################################################################### + +# Hint: Requesting a market by ID is a different REST route to listing markets +# and therefore it does not have filters or pagination (unlike the above request) + +# __get_market: +# Request a specific market using a pre-defined market id +url = f"{data_node_url_rest}/market/{market_id}" +response = requests.get(url) +helpers.check_response(response) +print("Market:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True))) +# :get_market__ diff --git a/rest/get-network-data-and-limits.py b/rest/get-network-data-and-limits.py new file mode 100644 index 0000000..8c78a05 --- /dev/null +++ b/rest/get-network-data-and-limits.py @@ -0,0 +1,47 @@ +#!/usr/bin/python3 + +############################################################################### +# G E T N E T W O R K D A T A / L I M I T S # +############################################################################### + +# How to get network data/limits information from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is NOT supported on these endpoints. +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +############################################################################### +# N E T W O R K D A T A # +############################################################################### + +# __get_network_data: +# Request all data for a Vega network +url = f"{data_node_url_rest}/network/data" +response = requests.get(url) +helpers.check_response(response) +print("Network data:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_network_data__ + +############################################################################### +# N E T W O R K L I M I T S # +############################################################################### + +# __get_network_limits: +# Request all limits for a Vega network +url = f"{data_node_url_rest}/network/limits" +response = requests.get(url) +helpers.check_response(response) +print("Network limits:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_network_limits__ diff --git a/rest/get-network-parameters.py b/rest/get-network-parameters.py new file mode 100644 index 0000000..51680f4 --- /dev/null +++ b/rest/get-network-parameters.py @@ -0,0 +1,53 @@ +#!/usr/bin/python3 + +############################################################################### +# G E T N E T W O R K P A R A M E T E R S # +############################################################################### + +# How to get Vega network parameters from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is supported [default page size is 1000] +# -> Check out pagination.py for example usage +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import requests +import helpers + +# Load Vega data node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +############################################################################### +# L I S T N E T W O R K P A R A M E T E R S # +############################################################################### + +# __get_network_params: +# Request a list of network parameters configured on a Vega network +url = f"{data_node_url_rest}/network/parameters" +response = requests.get(url) +helpers.check_response(response) +print("Network parameters:\n") +for edge in response.json()['networkParameters']['edges']: + print(edge['node']) +# :get_network_params__ + +parameter_key = response.json()['networkParameters']['edges'][0]['node']['key'] +assert parameter_key != "" + +print() +print(f"Selected parameter key: {parameter_key}") +print() + +############################################################################### +# S I N G L E N E T W O R K P A R A M E T E R # +############################################################################### + +# __get_network_param: +# Request a specific network parameter from those configured on a Vega network +url = f"{data_node_url_rest}/network/parameters/{parameter_key}" +response = requests.get(url) +helpers.check_response(response) +print(f"Network parameter for key {parameter_key}:\n") +print(response.json()) +# :get_network_param__ diff --git a/rest/get-node-data.py b/rest/get-node-data.py new file mode 100644 index 0000000..aa727b2 --- /dev/null +++ b/rest/get-node-data.py @@ -0,0 +1,73 @@ +#!/usr/bin/python3 + +############################################################################### +# G E T V E G A N O D E D A T A # +############################################################################### +# How to get Vega node information from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is supported by list nodes only [default page size is 1000] +# -> Check out pagination.py for example usage +# ---------------------------------------------------------------------- +# The list nodes endpoint can be filtered by the following parameter: +# epochSeq: Epoch number +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import requests +import helpers +import json + +# Load Vega data node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +############################################################################### +# L I S T N O D E S D A T A # +############################################################################### + +# __get_nodes: +# Request a list of information on the set of Vega nodes on a network +url = f"{data_node_url_rest}/nodes" +response = requests.get(url) +helpers.check_response(response) +response_json = response.json() +print("Vega nodes:\n{}".format( + json.dumps(response_json, indent=2, sort_keys=True) +)) +# :get_nodes__ + +node_id = response.json()['nodes']['edges'][0]['node']['id'] +assert node_id != "" + +print() +print(f"Selected node with id: {node_id}") +print() + +############################################################################### +# N O D E D A T A # +############################################################################### + +# __get_node_data: +# Request the node data for an id on a Vega network +url = f"{data_node_url_rest}/node/{node_id}" +response = requests.get(url) +helpers.check_response(response) +print("Node data:\n{}".format( + json.dumps(response_json, indent=2, sort_keys=True) +)) +# :get_node_data__ + +############################################################################### +# N O D E S I G N A T U R E S # +############################################################################### + +# __get_node_signatures: +# Request a list of node signatures on a Vega network +url = f"{data_node_url_rest}/node/signatures?id={node_id}" +response = requests.get(url) +helpers.check_response(response) +response_json = response.json() +print("Vega node signatures:\n{}".format( + json.dumps(response_json, indent=2, sort_keys=True) +)) +# :get_node_signatures__ diff --git a/rest/get-orders.py b/rest/get-orders.py new file mode 100644 index 0000000..3357b0c --- /dev/null +++ b/rest/get-orders.py @@ -0,0 +1,124 @@ +#!/usr/bin/python3 + +############################################################################### +# G E T O R D E R S # +############################################################################### + +# How to get order information from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is supported [default page size is 1000] +# -> Check out pagination.py for example usage +# Date Range is supported +# -> Check out date-range.py for example usage +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, including: +# partyId: Vega party id (public key) +# marketId: Vega market id +# reference: Custom order reference (set by the creator) +# liveOnly: Set to True to return only live orders (not filled etc) +# See below for toggle True/False +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +# Set to True to return only orders that are currently live on the market +# for example, not filled, expired or cancelled +# Set to False to return all orders of all status +live_only = True + +############################################################################### +# O R D E R S B Y M A R K E T # +############################################################################### + +market_id = helpers.env_market_id() +assert market_id != "" + +# __get_orders_by_market: +# Request a list of orders for a market +url = f"{data_node_url_rest}/orders?marketId={market_id}&liveOnly={live_only}" +response = requests.get(url) +helpers.check_response(response) +response_json = response.json() +print("Orders filtered by market:\n{}".format( + json.dumps(response_json, indent=2, sort_keys=True) +)) +# :get_orders_by_market__ + +# Find the first order in the list (above) if it exists +order_id = "6a834328d835ca79880dfc238a989c238fe32a62562690d717ab1ff42ad5004d" +if helpers.check_nested_response(response, "orders"): + first_order = helpers.get_nested_response(response, "orders")[0]["node"] + order_id = first_order["id"] + +############################################################################### +# O R D E R S B Y P A R T Y # +############################################################################### + +party_id = helpers.env_party_id() +assert party_id != "" + +# __get_orders_by_party: +# Request a list of accounts for a party (pubkey) on a Vega network +url = f"{data_node_url_rest}/orders?partyId={party_id}&liveOnly={live_only}" +response = requests.get(url) +helpers.check_response(response) +response_json = response.json() +print("Orders filtered by party:\n{}".format( + json.dumps(response_json, indent=2, sort_keys=True) +)) +# :get_orders_by_party__ + +############################################################################### +# O R D E R S B Y R E F E R E N C E # +############################################################################### + +# __get_orders_by_ref: +custom_ref = "traderbot" +# Request a list of orders with a matching custom reference string +url = f"{data_node_url_rest}/orders?partyId={party_id}&reference={custom_ref}&liveOnly={live_only}" +response = requests.get(url) +helpers.check_response(response) +print("Orders filtered by reference:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True))) +# :get_orders_by_ref__ + +############################################################################### +# O R D E R B Y I D # +############################################################################### + +# Hint: Requesting an order by ID is a different REST route to listing orders +# and therefore it does not have filters or pagination (unlike the above requests) + +# __get_order: +# Request specific order information for an order id +url = f"{data_node_url_rest}/order/{order_id}" +response = requests.get(url) +helpers.check_response(response) +print("Order:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True))) +# :get_order__ + + +############################################################################### +# O R D E R H I S T O R Y # +############################################################################### + +# Hint: This request lists all (if any) revisions to an order in order history +# and not just the current version of the order + +# __get_order_history: +# Request order revision history for an order id +url = f"{data_node_url_rest}/order/versions/{order_id}" +response = requests.get(url) +helpers.check_response(response) +print("Order:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True))) +# :get_order_history__ + diff --git a/rest/get-parties.py b/rest/get-parties.py new file mode 100644 index 0000000..5530019 --- /dev/null +++ b/rest/get-parties.py @@ -0,0 +1,75 @@ +#!/usr/bin/python3 + +############################################################################### +# G E T P A R T I E S # +############################################################################### + +# How to get Vega party information from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is supported [default page size is 1000] +# -> Check out pagination.py for example usage +# ---------------------------------------------------------------------- +# The list can be filtered by the following parameter: +# partyId: Vega party id (public key) +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers + +# Vega wallet interaction helper, see login.py for detail +from login import pubkey + +# Load Vega data node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +############################################################################### +# P A R T I E S B Y M A R K E T # +############################################################################### + +# TODO: this needs implementing in api + +market_id = helpers.env_market_id() +assert market_id != "" + +# __get_parties_by_market: +# Request a list of parties for a single market (repeat the filter for multiple markets) +# url = f"{data_node_url_rest}/accounts?filter.marketIds={market_id}" +# response = requests.get(url) +# helpers.check_response(response) +# response_json = response.json() +# print("Accounts filtered by market:\n{}".format( +# json.dumps(response_json, indent=2, sort_keys=True) +# )) +# :get_parties_by_market__ + +############################################################################### +# L I S T P A R T I E S # +############################################################################### + +# __get_parties: +url = f"{data_node_url_rest}/parties" +response = requests.get(url) +helpers.check_response(response) +print("Parties for network:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_parties__ + +############################################################################### +# P A R T Y B Y I D # +############################################################################### + +party_id = helpers.env_party_id() +assert party_id != "" + +# __get_party: +# Request a specific party using a pre-defined party id (pubkey) +url = f"{data_node_url_rest}/parties?partyId={party_id}" +response = requests.get(url) +helpers.check_response(response) +print("Party:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True))) +# :get_party__ diff --git a/rest/get-positions.py b/rest/get-positions.py new file mode 100644 index 0000000..19dbcc6 --- /dev/null +++ b/rest/get-positions.py @@ -0,0 +1,44 @@ +#!/usr/bin/python3 + +############################################################################### +# G E T P O S I T I O N S # +############################################################################### + +# How to get rewards information from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is supported [default page size is 1000] +# -> Check out pagination.py for example usage +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, including: +# partyId: Vega party id (public key) +# marketId: Vega market id +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +# Load Vega market and party ids +party_id = helpers.env_party_id() +market_id = helpers.env_market_id() +assert party_id != "" +assert market_id != "" + +############################################################################### +# L I S T P O S I T I O N S # +############################################################################### + +# __get_positions: +# Request a list of trading positions for a Vega network +url = f"{data_node_url_rest}/positions?partyId={party_id}&marketId={market_id}" +response = requests.get(url) +helpers.check_response(response) +print("Positions for party:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_positions__ diff --git a/rest/get-rewards.py b/rest/get-rewards.py new file mode 100644 index 0000000..dd4b47f --- /dev/null +++ b/rest/get-rewards.py @@ -0,0 +1,124 @@ +#!/usr/bin/python3 + +############################################################################### +# G E T R E W A R D S # +############################################################################### + +# How to get rewards information from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is supported [default page size is 1000] +# -> Check out pagination.py for example usage +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, including: +# partyId: Vega party id (public key) +# assetId: Vega asset id +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +############################################################################### +# L I S T R E W A R D S # +############################################################################### + +# __get_rewards: +# Request a list of rewards for a Vega network +url = f"{data_node_url_rest}/rewards" +response = requests.get(url) +helpers.check_response(response) +print("Rewards for network:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_rewards__ + +# Find the first reward in the list (above) if it exists +asset_id = "3a834328d835cf79880dfc238a989c238fe32a62562690d717ab1ff42ad5003f" +if helpers.check_nested_response(response, "rewards"): + first_reward = helpers.get_nested_response(response, "rewards")[0]["node"] + asset_id = first_reward["assetId"] + +############################################################################### +# R E W A R D S B Y P A R T Y # +############################################################################### + +party_id = helpers.env_party_id() +assert party_id != "" + +# __get_rewards_by_party: +# Request a list of rewards for a party on a Vega network +url = f"{data_node_url_rest}/deposits?partyId={party_id}" +response = requests.get(url) +helpers.check_response(response) +print("Rewards for a specific party:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_rewards_by_party__ + +############################################################################### +# R E W A R D S B Y A S S E T # +############################################################################### + +# Hint: Combine both rewards by asset and party to refine the query and improve performance + +# __get_rewards_by_asset: +# Request a list of all rewards for an asset on a Vega network +url = f"{data_node_url_rest}/deposits?assetId={asset_id}" +response = requests.get(url) +helpers.check_response(response) +print("Rewards for a specific asset:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_rewards_by_asset__ + +############################################################################### +# L I S T R E W A R D S U M M A R I E S # +############################################################################### + +# Hint: Rewards summaries are rewards grouped by party and asset +# For example, for a party/asset pair this is the sum of all rewards of all types over all time + +# __get_reward_summaries: +# Request a list of all rewards for a Vega network +url = f"{data_node_url_rest}/rewards/summaries" +response = requests.get(url) +helpers.check_response(response) +print("Rewards summaries for network:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_reward_summaries__ + +############################################################################### +# R E W A R D S U M M A R I E S ( F I L T E R S ) # +############################################################################### + +# __get_reward_summaries_by_party: +# Request a list of all rewards for a party on a Vega network +url = f"{data_node_url_rest}/deposits?partyId={party_id}" +response = requests.get(url) +helpers.check_response(response) +print("Rewards summaries for a specific party:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_rewards_by_party__ + +############################################################################### +# R E W A R D S B Y A S S E T # +############################################################################### + +# Hint: Combine both rewards by asset and party to refine the query and improve performance + +# __get_rewards_by_asset: +# Request a list of all rewards for an asset on a Vega network +url = f"{data_node_url_rest}/deposits?assetId={asset_id}" +response = requests.get(url) +helpers.check_response(response) +print("Rewards summaries for a specific asset:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_rewards_by_asset__ diff --git a/rest/get-staking-data.py b/rest/get-staking-data.py new file mode 100644 index 0000000..7af26e6 --- /dev/null +++ b/rest/get-staking-data.py @@ -0,0 +1,40 @@ +#!/usr/bin/python3 + +############################################################################### +# G E T S T A K I N G D A T A # +############################################################################### + +# How to get staking data information from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is supported [default page size is 1000] +# -> Check out pagination.py for example usage +# ---------------------------------------------------------------------- +# The following path parameter is required: +# partyId: Vega party id (public key) +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +############################################################################### +# L I S T S T A K I N G D A T A # +############################################################################### + +party_id = helpers.env_party_id() +assert party_id != "" + +# __get_staking_data: +# Request all staking data for a Vega network +url = f"{data_node_url_rest}/parties/{party_id}/stake" +response = requests.get(url) +helpers.check_response(response) +print("Staking data for party:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_staking_data__ diff --git a/rest/get-statistics.py b/rest/get-statistics.py new file mode 100644 index 0000000..f73b3b1 --- /dev/null +++ b/rest/get-statistics.py @@ -0,0 +1,32 @@ +#!/usr/bin/python3 + +############################################################################### +# V E G A S T A T I S T I C S # +############################################################################### + +# How to get statistics from a Vega Node using REST calls: +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +# Note: The statistics endpoint is proxied from Vega core so we must drop the api +# v2 portion of the url for testnet configurations, other networks might need +# a different url specified here... +node_url_rest = data_node_url_rest.strip("/api/v2") + +# __get_statistics: +# Request statistics for a node on Vega +url = f"{node_url_rest}/statistics" +response = requests.get(url) +helpers.check_response(response) +print("Node statistics:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_statistics__ diff --git a/rest/get-trades.py b/rest/get-trades.py new file mode 100644 index 0000000..f8a5af0 --- /dev/null +++ b/rest/get-trades.py @@ -0,0 +1,117 @@ +#!/usr/bin/python3 + +############################################################################### +# G E T T R A D E S # +############################################################################### + +# How to get trade information from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is supported [default page size is 1000] +# -> Check out pagination.py for example usage +# Date Range is supported +# -> Check out date-range.py for example usage +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, including: +# partyId: Vega party id (public key) +# marketId: Vega market id +# orderId: Vega order id +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers + +# Vega wallet interaction helper, see login.py for detail +from login import pubkey + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +############################################################################### +# T R A D E S B Y M A R K E T # +############################################################################### + +market_id = helpers.env_market_id() +assert market_id != "" + +# __get_trades_by_market: +# Request a list of trades for a market +url = f"{data_node_url_rest}/trades?marketId={market_id}" +response = requests.get(url) +helpers.check_response(response) +response_json = response.json() +print("Trades filtered by market:\n{}".format( + json.dumps(response_json, indent=2, sort_keys=True) +)) +# :get_trades_by_market__ + +# Find the first trade in the list (above) if it exists +trade_id = "6a834328d835ca79880dfc238a989c238fe32a62562690d717ab1ff42ad5004d" +order_id = "165968e2f7d488bc2d55b5da6a9137af207b839c3241352253ef1c2c253eb620" +if helpers.check_nested_response(response, "trades"): + first_trade = helpers.get_nested_response(response, "trades")[0]["node"] + trade_id = first_trade["id"] + order_id = first_trade["buyOrder"] + +############################################################################### +# T R A D E S B Y P A R T Y # +############################################################################### + +# __get_trades_by_party: +# Request a list of trades for a party (pubkey) on a Vega network +url = f"{data_node_url_rest}/trades?partyId={pubkey}" +print(url) +response = requests.get(url) +helpers.check_response(response) +response_json = response.json() +print("Trades filtered by party:\n{}".format( + json.dumps(response_json, indent=2, sort_keys=True) +)) +# :get_trades_by_party__ + +############################################################################### +# T R A D E S B Y O R D E R I D # +############################################################################### + +# __get_trades_by_order: +# Request a list of orders with a matching custom reference string +url = f"{data_node_url_rest}/trades?orderId={order_id}" +print(url) +response = requests.get(url) +helpers.check_response(response) +print("Trades by order:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True))) +# :get_trades_by_order__ + +############################################################################### +# T R A D E B Y I D # +############################################################################### +# todo: uncomment below when work done to add trade by ID to v2 API + +# Note: Requesting a trade by ID is a different REST route to listing trades +# and therefore it does not have filters or pagination (unlike the above requests) + +# __get_trade_by_id: +# Request a specific trade using a pre-defined trade id +# url = f"{data_node_url_rest}/trade/{trade_id}" +# response = requests.get(url) +# helpers.check_response(response) +# print("Trade:\n{}".format( +# json.dumps(response.json(), indent=2, sort_keys=True))) +# :get_trade_by_id__ + +############################################################################### +# L A T E S T T R A D E # +############################################################################### + +# __get_latest_trade: +# Request the latest trade on a given Vega market +url = f"{data_node_url_rest}/market/{market_id}/trade/latest" +response = requests.get(url) +helpers.check_response(response) +print("Latest trade:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True))) +# :get_latest_trade__ + diff --git a/rest/get-transfers.py b/rest/get-transfers.py new file mode 100644 index 0000000..ec416e7 --- /dev/null +++ b/rest/get-transfers.py @@ -0,0 +1,66 @@ +#!/usr/bin/python3 + +############################################################################### +# G E T T R A N S F E R S # +############################################################################### + +# How to get transfer information from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is supported [default page size is 1000] +# -> Check out pagination.py for example usage +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, including: +# pubkey: Vega party id (public key) +# direction: Which direction the transfer took place, e.g. +# TRANSFER_DIRECTION_TRANSFER_FROM +# TRANSFER_DIRECTION_TRANSFER_TO +# TRANSFER_DIRECTION_TRANSFER_TO_OR_FROM +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +############################################################################### +# L I S T T R A N S F E R S # +############################################################################### + +# __get_transfers: +# Request a list of transfers for a Vega network +url = f"{data_node_url_rest}/transfers" +response = requests.get(url) +helpers.check_response(response) +print("Transfers for network:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_transfers__ + +from_pubkey = "e4a81f9e67acee66406a84ace9fe2f70512a775c62301fbeb17eb6ecec83b2b9" +if helpers.check_nested_response(response, "transfers"): + first_transfer = helpers.get_nested_response(response, "transfers")[0]["node"] + from_pubkey = first_transfer["from"] + +# Uncomment the following two lines to use an env specified party id +# from_pubkey = helpers.env_party_id() +# assert from_pubkey != "" + +############################################################################### +# T R A N S F E R S B Y P A R T Y & D I R E C T I O N # +############################################################################### + +# Hint: Both party (pubkey) and direction are required when specifying a pubkey + +# __get_transfers_by_party: +# Request a list of transfers for a party (and direction) on a Vega network +url = f"{data_node_url_rest}/transfers?pubkey={from_pubkey}&direction=TRANSFER_DIRECTION_TRANSFER_TO" +response = requests.get(url) +helpers.check_response(response) +print("Transfers for a specific party and direction (TRANSFER_DIRECTION_TRANSFER_TO):\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_transfers_by_party__ diff --git a/rest/get-vega-time.py b/rest/get-vega-time.py new file mode 100644 index 0000000..9cd63bc --- /dev/null +++ b/rest/get-vega-time.py @@ -0,0 +1,32 @@ +#!/usr/bin/python3 + +############################################################################### +# G E T V E G A T I M E # +############################################################################### + +# How to get vega time (current block time) from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is NOT supported on this endpoint. +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import requests +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +# __get_time: +# Request the latest timestamp in nanoseconds since epoch from the Vega network +url = f"{data_node_url_rest}/vega/time" +response = requests.get(url) +helpers.check_response(response) + +# The "timestamp" field contains the resulting data we need. +vega_time = response.json()["timestamp"] +print("Vega time:\n{}".format(vega_time)) +# :get_time__ + +# Print the human readable value of vega time (timestamp is a nanoseconds since epoch timestamp) +print(helpers.nano_ts_to_human_date(float(vega_time))) diff --git a/rest/get-withdrawals.py b/rest/get-withdrawals.py new file mode 100644 index 0000000..5770f51 --- /dev/null +++ b/rest/get-withdrawals.py @@ -0,0 +1,74 @@ +#!/usr/bin/python3 + +############################################################################### +# G E T W I T H D R A W A L S # +############################################################################### + +# How to get withdrawal information from a Data Node using REST calls: +# ---------------------------------------------------------------------- +# Pagination is supported [default page size is 1000] +# -> Check out pagination.py for example usage +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, including: +# partyId: Vega party id (public key) +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers + +# Vega wallet interaction helper, see login.py for detail +from login import pubkey + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +############################################################################### +# L I S T W I T H D R A W A L S # +############################################################################### + +# __get_withdrawals: +# Request a list of withdrawals for a Vega network +url = f"{data_node_url_rest}/withdrawals" +response = requests.get(url) +helpers.check_response(response) +print("Withdrawals for network:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_withdrawals__ + +# Find the first withdrawal in the list (above) if it exists +withdrawal_id = "3a834328d835cf79880dfc238a989c238fe32a62562690d717ab1ff42ad5003f" +if helpers.check_nested_response(response, "withdrawals"): + first_withdrawal = helpers.get_nested_response(response, "withdrawals")[0]["node"] + withdrawal_id = first_withdrawal["id"] + +############################################################################### +# W I T H D R A W A L S B Y P A R T Y # +############################################################################### + +# __get_withdrawals_by_party: +# Request a list of withdrawals for a party on a Vega network +url = f"{data_node_url_rest}/withdrawals?partyId={pubkey}" +response = requests.get(url) +helpers.check_response(response) +print("Withdrawals for a specific party:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_withdrawals_by_party__ + +############################################################################### +# W I T H D R A W A L B Y I D # +############################################################################### + +# __get_withdrawal_by_id: +# Request a single withdrawal for withdrawal id +url = f"{data_node_url_rest}/withdrawal/{withdrawal_id}" +response = requests.get(url) +helpers.check_response(response) +print("Withdrawal for id:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_withdrawal_by_id__ diff --git a/rest/helpers.py b/rest/helpers.py new file mode 100644 index 0000000..b68d182 --- /dev/null +++ b/rest/helpers.py @@ -0,0 +1,196 @@ +import json +import datetime +import random +import os +import requests +import string +from typing import Any + + +def check_response(r: requests.Response) -> None: + """ + Raise a helpful exception if the HTTP response was not 200. + """ + if r.status_code != 200: + raise Exception(f"{r.url} returned HTTP {r.status_code} {r.text}") + + +def check_var(val: str) -> bool: + """ + Return true if the value is ok. + """ + if val is None or val == "": + return False + if invalid(val): + return False + return True + + +def check_url(url: str) -> bool: + """ + Return true if the URL is ok. + """ + if not check_var(url): + return False + if not any(url.startswith(prefix) for prefix in ["http://", "https://"]): + return False + return True + + +def get_from_env(var_name: str) -> str: + """ + Get a value from an environment variable. Used in CI for testing. + """ + val = os.getenv(var_name, "") + if val == "": + print(f"Error: Missing environment variable {var_name}.") + exit(1) + + return val + + +def invalid(val: str) -> bool: + """ + Return true if none of the invalid strings are found in the value. + """ + bzzt = [">>", "e.g.", "example"] + return any(x in val for x in bzzt) + + +def random_string(length: int = 20) -> str: + """ + Generate a random string, made of letters and digits. + """ + choices = string.ascii_letters + string.digits + return "".join(random.choice(choices) for i in range(length)) + + +def fix_wallet_server_url(url: str) -> str: + """ + Help guide users against including api version suffix in wallet server URL. + """ + for suffix in ["/api/v1/", "/api/v1", "/api/", "/api", "/"]: + if not url.endswith(suffix): + continue + print( + f'There\'s no need to add "{suffix}" to the wallet server URL. ' + "Removing it and continuing..." + ) + url = url[: -len(suffix)] + + return url + + +def enum_to_str(e: Any, val: int) -> str: + return e.keys()[e.values().index(val)] + + +def ts_now(): + return datetime.datetime.now() + + +def get_nano_ts(dt: datetime.datetime, seconds_delta: int): + new_dt = dt - datetime.timedelta(seconds=seconds_delta) + return str(int(new_dt.replace(tzinfo=datetime.timezone.utc).timestamp())*1000000000) + + +def nano_ts_to_human_date(nanos): + dt = datetime.datetime.fromtimestamp(nanos / 1e9) + return '{}{:03.0f}'.format(dt.strftime('%Y-%m-%dT%H:%M:%S.%f'), nanos % 1e3) + + +def env_market_id() -> str: + """ + Get env var for a custom MARKET_ID, will not forcibly reload from API + """ + return env_market_id_from_api(False) + + +def env_market_id_from_api(reload: bool) -> str: + """ + Get env var for a custom MARKET_ID, will find one from API if not specified + """ + market_id = os.getenv("MARKET_ID", "") + perform_reload = False + if len(market_id) > 0: + if reload: + perform_reload = True + else: + perform_reload = True + + if perform_reload: + # Request a list of markets and select the first one + data_node_url_rest = get_from_env("DATA_NODE_URL_REST") + url = f"{data_node_url_rest}/markets" + response = requests.get(url) + check_response(response) + if len(get_nested_response(response, "markets")) == 0: + print(f"No markets found on {url}") + print("Please check and try again...") + exit(1) + else: + market_id = get_nested_response(response, "markets")[0]["node"]["id"] + assert market_id != "" + print(f"MARKET_ID set: {market_id}") + os.environ["MARKET_ID"] = market_id + + return market_id + + +def env_party_id() -> str: + """ + Get env var for a custom PARTY_ID, will not forcibly reload from API + """ + return env_party_id_from_api(False) + + +def env_party_id_from_api(reload: bool) -> str: + """ + Get env var for a custom PARTY_ID, will find one from API if not specified + """ + party_id = os.getenv("PARTY_ID", "") + perform_reload = False + if len(party_id) > 0: + if reload: + perform_reload = True + else: + perform_reload = True + + if perform_reload: + # Request a list of parties and select the first one + data_node_url_rest = get_from_env("DATA_NODE_URL_REST") + url = f"{data_node_url_rest}/parties" + response = requests.get(url) + check_response(response) + if len(get_nested_response(response, "parties")) <= 1: + print(f"No (non network) parties found on {url}") + print("Please check and try again...") + exit(1) + else: + party_id = get_nested_response(response, "parties")[1]["node"]["id"] + assert party_id != "" + print(f"PARTY_ID set: {party_id}") + os.environ["PARTY_ID"] = party_id + + return party_id + + +def get_nested_response(response: json, key: str) -> json: + """ + Get json back from a response string given v2 nesting with edges + """ + return response.json()[key]["edges"] + + +def check_nested_response(response: json, key: str) -> bool: + """ + Check if len > 0 from a response string given v2 nesting with edges + """ + return len(get_nested_response(response, key)) > 0 + + +def generate_id(n :int) -> str: + """ + Generate a semi-random identifier string of length n + """ + return ''.join(random.choices(string.ascii_lowercase + (2 * string.digits), k=n)) \ No newline at end of file diff --git a/rest/login.py b/rest/login.py new file mode 100644 index 0000000..f3509ce --- /dev/null +++ b/rest/login.py @@ -0,0 +1,72 @@ +import requests +import os.path +import json +import sys +import helpers + +ci_args = "--ci" +wallet_server_url = helpers.get_from_env("WALLET_SERVER_URL") + + +def load_token(): + if ci_args in sys.argv: + return perform_login() + # login will call exit with appropriate code + if not os.path.isfile("token.temp"): + print('Error: No token file found: try running "python3 login.py"') + exit(1) + with open("token.temp", "r") as token_file: + return json.load(token_file)["token"] + + +def get_pubkey(token): + auth_headers = {"Authorization": "Bearer " + token} + response = requests.get(wallet_server_url + "/api/v1/keys", + headers=auth_headers) + if response.status_code != 200: + print("Error listing keys: " + response.text) + exit(1) + keys = response.json()["keys"] + if len(keys) < 1: + print("Error: No keys found, use Vega Console" + + " or Vega Wallet CLI to create one") + exit(1) + return keys[0]["pub"], auth_headers + + +def perform_login(): + import getpass + print(f"Using API: {wallet_server_url}") + wallet_name = os.getenv("WALLET_NAME") + wallet_passphrase = os.getenv("WALLET_PASSPHRASE") + valid_user = helpers.check_var(wallet_name) + valid_pass = helpers.check_var(wallet_passphrase) + if ci_args in sys.argv and not valid_user: + print("Error: Missing environment variable WALLET_NAME") + exit(1) + if ci_args in sys.argv and not valid_pass: + print("Error: Missing environment variable WALLET_PASSPHRASE") + exit(1) + if not valid_user or not valid_pass: + wallet_name = input("Enter Vega wallet username: ") + wallet_passphrase = getpass.getpass("Vega wallet passphrase: ") + req = {"wallet": wallet_name, "passphrase": wallet_passphrase} + response = requests.post(wallet_server_url + + "/api/v1/auth/token", json=req) + if response.status_code != 200: + print("Error logging in: " + response.text) + exit(1) + if ci_args not in sys.argv: + with open("token.temp", "w") as token_file: + json.dump(response.json(), token_file) + print('Token saved to "token.temp", done.') + return response.json()["token"] + + +if __name__ == "__main__": + perform_login() + exit(0) + + +token = load_token() +pubkey, auth_headers = get_pubkey(token) diff --git a/rest/logout.py b/rest/logout.py new file mode 100644 index 0000000..70b695b --- /dev/null +++ b/rest/logout.py @@ -0,0 +1,21 @@ +import os +import helpers + +wallet_server_url = helpers.get_from_env("WALLET_SERVER_URL") + + +def perform_logout(): + if os.path.exists("token.temp"): + print(f"Using API: {wallet_server_url}") + os.remove("token.temp") + # Clean up any env vars related to wallet user + os.unsetenv("WALLET_NAME") + os.unsetenv("WALLET_PASSPHRASE") + print("Log out complete (removed token file and environment vars)") + else: + print("The token file does not exist, try `python3 login.py`") + + +if __name__ == "__main__": + perform_logout() + exit(0) \ No newline at end of file diff --git a/rest/pagination.py b/rest/pagination.py new file mode 100644 index 0000000..47c0514 --- /dev/null +++ b/rest/pagination.py @@ -0,0 +1,159 @@ +#!/usr/bin/python3 + +############################################################################### +# P A G I N A T I O N # +############################################################################### + +# Pagination is available and enabled by default on many of the Vega data node +# APIs. +# +# When querying for data the results will be 'paged' into sets of results +# and the default page size is 1000 results (this figure can be overridden). +# +# Vega APIs us a cursor based pagination model (aka key-set pagination). This +# is a common pagination strategy that avoids many of the pitfalls of “offset– +# limit” pagination. For example, with offset–limit pagination, if an item +# from a prior page is deleted while the client is paginating, all subsequent +# results will be shifted forward by one. +# +# Each result returned from an API endpoint will have a 'cursor', example: +# +# "edges": [ +# { +# "cursor": "eyJ2ZWdhX3RpbWUiOiIyMDIyLTExLTExVDE0OjM2OjU4LjE2ODY2OVoifQ==", +# "node": { +# ... +# +# And each result set page will have 'pageInfo', example: +# +# "pageInfo": { +# "endCursor": "eyJ2ZWdhX3RpbWUiOiIyMDIyLTExLTExVDE0OjI2OjQzLjg2MTIxWiJ9", +# "hasNextPage": false, +# "hasPreviousPage": false, +# "startCursor": "eyJ2ZWdhX3RpbWUiOiIyMDIyLTExLTExVDE0OjM2OjU4LjE2ODY2OVoifQ==" +# } +# +# The examples shown below illustrate the basic concepts used with data returned +# from most list endpoints in the Vega APIs, including (but not limited to): +# - Trades +# - Orders +# - Parties +# - Candles +# - Withdrawals +# - Deposits +# - Rewards +# - Ledger entries +# - Balance changes +# - Liquidity provisions +# - Governance +# - etc. +# +# The following parameters are typically used to control pagination: +# pagination.first: Non-negative integer e.g. 100 (forward pagination) +# pagination.after: Cursor value (forward pagination) +# pagination.last: Non-negative integer e.g. 100 (backward pagination) +# pagination.before: Cursor value (backward pagination) +# pagination.newestFirst: Newest records first, older records last, default is true. +# >This effectively reverses the forward/backward direction above. +# +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import json +import requests +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +############################################################################### +# A S C E N D I N G P A G I N A T I O N # +############################################################################### + +market_id = helpers.env_market_id() +assert market_id != "" + +# __get_trades_by_market_basic_pagination_asc: +page_size = 50 +# Request a list of the first trades for a market, limit page size to `50` results (default is 1000) +url = f"{data_node_url_rest}/trades?marketId={market_id}" \ + f"&pagination.first={page_size}" +response = requests.get(url) +helpers.check_response(response) +response_json = response.json() +print("Trades filtered by market (first 50 asc):\n{}".format( + json.dumps(response_json, indent=2, sort_keys=True) +)) +# :get_trades_by_market_basic_pagination_asc__ + +# Find the trades list pageInfo from the query above and collect the page information: +pageInfo = response_json["trades"]["pageInfo"] +startCursor = pageInfo["startCursor"] # The starting cursor string value +endCursor = pageInfo["endCursor"] # The ending cursor string value +hasNextPage = pageInfo["hasNextPage"] # True if has next page (based on page size) +hasPrevPage = pageInfo["hasPreviousPage"] # True if has a previous page (based on page size) + +# Hint: startCursor and endCursor correspond to the first and last nodes in edges, respectively. +# and the endCursor value from the initial page of results is used in the next request... + +if not hasNextPage: + print("Result set returned does not have a next page") +if not hasPrevPage: + print("Result set returned does not have a previous page") + +# __get_trades_by_market_basic_pagination_asc_next_page: +# Request a list of the next page of 50 trades for a market, after the page we returned previously +url = f"{data_node_url_rest}/trades?marketId={market_id}" \ + f"&pagination.first={page_size}" \ + f"&pagination.after={endCursor}" \ + +response = requests.get(url) +helpers.check_response(response) +response_json = response.json() +print("Trades filtered by market (next page, asc):\n{}".format( + json.dumps(response_json, indent=2, sort_keys=True) +)) +# :get_trades_by_market_basic_pagination_asc_next_page__ + +############################################################################### +# D E S C E N D I N G P A G I N A T I O N # +############################################################################### + +# __get_trades_by_market_basic_pagination_desc: +page_size = 25 +# Request a list of the last trades for a market, limit page size to `25` results (default is 1000) +url = f"{data_node_url_rest}/trades?marketId={market_id}" \ + f"&pagination.last={page_size}" +response = requests.get(url) +helpers.check_response(response) +response_json = response.json() +print("Trades filtered by market (last 25, desc):\n{}".format( + json.dumps(response_json, indent=2, sort_keys=True) +)) +# :get_trades_by_market_basic_pagination_desc__ + +# Find the trades list pageInfo from the query above and collect the page information: +pageInfo = response_json["trades"]["pageInfo"] +startCursor = pageInfo["startCursor"] # The starting cursor string value +endCursor = pageInfo["endCursor"] # The ending cursor string value +hasNextPage = pageInfo["hasNextPage"] # True if has next page (based on page size) +hasPrevPage = pageInfo["hasPreviousPage"] # True if has a previous page (based on page size) + +if not hasNextPage: + print("Result set returned does not have a next page") +if not hasPrevPage: + print("Result set returned does not have a previous page") + +# __get_trades_by_market_basic_pagination_desc_next_page: +# Request a list of the next page of 25 trades for a market, before the page we returned previously +url = f"{data_node_url_rest}/trades?marketId={market_id}" \ + f"&pagination.last={page_size}" \ + f"&pagination.before={endCursor}" \ + +response = requests.get(url) +helpers.check_response(response) +response_json = response.json() +print("Trades filtered by market (next page, desc):\n{}".format( + json.dumps(response_json, indent=2, sort_keys=True) +)) +# :get_trades_by_market_basic_pagination_desc_next_page__ diff --git a/rest/propose-vote-enact-freeform.py b/rest/propose-vote-enact-freeform.py new file mode 100644 index 0000000..69e35ad --- /dev/null +++ b/rest/propose-vote-enact-freeform.py @@ -0,0 +1,250 @@ +#!/usr/bin/python3 + +import json +import time +import requests +import helpers + +# Vega wallet interaction helper, see login.py for detail +from login import token, pubkey + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") +# Load Vega wallet server URL, set in same way as above +wallet_server_url = helpers.get_from_env("WALLET_SERVER_URL") + +##################################################################################### +# F I N D A S S E T S # +##################################################################################### + +# __get_assets: +# Request a list of assets available +url = f"{data_node_url_rest}/assets" +response = requests.get(url) +helpers.check_response(response) +# :get_assets__ + + +##################################################################################### +# G O V E R N A N C E T O K E N C H E C K # +##################################################################################### + +# Get the identifier of the governance asset on the Vega network +assets = response.json()["assets"]["edges"] +vote_asset_id = next((x["node"]["id"] for x in assets if x["node"]["details"]["symbol"] == "VEGA"), None) +if vote_asset_id is None: + print("VEGA asset not found on specified Vega network, please symbol name check and try again") + exit(1) + +# Request accounts for party and check governance asset balance +url = f"{data_node_url_rest}/accounts?filter.partyIds={pubkey}" +response = requests.get(url) +helpers.check_response(response) + +# Debugging +# print("Accounts:\n{}".format( +# json.dumps(response.json(), indent=2, sort_keys=True))) + +voting_balance = 0 +accounts = response.json()["accounts"]["edges"] + +for account in accounts: + if account["account"]["asset"] == vote_asset_id: + print("Found governance asset account") + print(account) + voting_balance = account["account"]["balance"] + break + +if voting_balance == 0: + print(f"Please deposit VEGA asset to public key {pubkey} and try again") + exit(1) + +##################################################################################### +# B L O C K C H A I N T I M E # +##################################################################################### + +# __get_time: +# Request the current blockchain time, and convert to time in seconds +response = requests.get(f"{data_node_url_rest}/vega/time") +helpers.check_response(response) +blockchain_time = int(response.json()["timestamp"]) +blockchain_time_seconds = int(blockchain_time / 1e9) # Seconds precision +# :get_time__ + +assert blockchain_time > 0 +assert blockchain_time_seconds > 0 +print(f"Blockchain time: {blockchain_time} ({blockchain_time_seconds} seconds past epoch)") + +##################################################################################### +# F R E E F O R M P R O P O S A L # +##################################################################################### + +# __propose_new_freeform: +# Compose a freeform governance proposal +proposal_ref = f"{pubkey}-{helpers.generate_id(30)}" +# Title is designed to be a short/relatively unique title to help identify the freeform proposal +proposal_title = "An example freeform proposal relating to an IPFS document" +# Description can be a more longer form description of the proposal including links or guidance +proposal_description = "I propose that everyone evaluate the following IPFS document and vote " \ + "Yes if they agree. [bafybeigwwctpv37xdcwacqxvekr6e4kaemqsrv34em6glkbic" \ + "eo3fcy4si](https://dweb.link/ipfs/bafybeigwwctpv37xdcwacqxvekr6e4kaemq" \ + "srv34em6glkbiceo3fcy4si)" + + +# Set closing/enactment and validation timestamps to valid time offsets +# from the current Vega blockchain time +closing_time = blockchain_time_seconds + 60 * 60 * 2 # Two hours from blockchain time + +new_freeform = { + "proposalSubmission": { + "reference": proposal_ref, + "rationale": { + "description": proposal_description, + "title": proposal_title + }, + "terms": { + "closingTimestamp": closing_time, + "newFreeform": {}, + } + }, + "pubKey": pubkey, + "propagate": True +} +# :propose_new_freeform__ + +# __sign_tx_proposal: +# Sign the transaction with a proposal submission command +# Hint: Setting propagate to true will also submit to a Vega node +url = f"{wallet_server_url}/api/v1/command/sync" +headers = {"Authorization": f"Bearer {token}"} +response = requests.post(url, headers=headers, json=new_freeform) +helpers.check_response(response) +# :sign_tx_proposal__ + +print(json.dumps(response.json(), indent=4, sort_keys=True)) +print() +print("Signed freeform proposal and sent to Vega") + +# Wait for proposal to be included in a block and to be accepted by Vega network +print("Waiting for blockchain...", end="", flush=True) +proposal_id = None + +url = f"{data_node_url_rest}/governances?proposerPartyId={pubkey}&proposalReference={proposal_ref}" +response = requests.get(url) +while helpers.check_nested_response(response, "connection") is not True: + time.sleep(0.5) + print(".", end="", flush=True) + response = requests.get(url) + continue + +found_proposal = helpers.get_nested_response(response, "connection")[0]["node"]["proposal"] +proposal_id = found_proposal["id"] +proposal_state = found_proposal["state"] + +print() +if (proposal_state == 'STATE_REJECTED') or ( + proposal_state == 'STATE_DECLINED') or ( + proposal_state == 'STATE_FAILED'): + print(f"Your proposal has been {proposal_state}!") + print("Due to: " + found_proposal["reason"]) + if (found_proposal["errorDetails"]) != '': + print("Further details: " + found_proposal["errorDetails"]) + exit() +else: + print("Your proposal has been accepted by the network!") + print(json.dumps(found_proposal, indent=4, sort_keys=True)) + +assert proposal_id +assert proposal_id != "" + +##################################################################################### +# V O T E O N P A R A M E T E R # +##################################################################################### + +# STEP 2 - Let's vote on the proposal + +# IMPORTANT: When voting for a proposal on the Vega Testnet, typically a single +# YES vote from the proposer will not be enough to vote the proposal into existence. +# This is because of the network minimum threshold for voting on proposals. +# A proposer should enlist the help/YES votes from other community members, ideally on the +# Community forums (https://community.vega.xyz/c/testnet) or Discord (https://vega.xyz/discord) + +# Further documentation on proposal voting and review here: https://docs.testnet.vega.xyz/docs/api-howtos/proposals/ + +# __prepare_vote: +# Prepare a vote for the proposal +vote = { + "voteSubmission": { + "value": "VALUE_YES", # Can be either VALUE_YES or VALUE_NO + "proposalId": proposal_id, + }, + "pubKey": pubkey, + "propagate": True +} +# :prepare_vote__ + +# Debugging +# print("Prepared vote:\n", prepared_vote, "\n") + +# __sign_tx_vote: +# Sign the vote transaction +# Note: Setting propagate to true will also submit to a Vega node +url = f"{wallet_server_url}/api/v1/command/sync" +response = requests.post(url, headers=headers, json=vote) +helpers.check_response(response) +# :sign_tx_vote__ + +print("Signed vote on proposal and sent to Vega") + +# Debugging +# print("Signed transaction:\n", response.json(), "\n") + +##################################################################################### +# V O T E O N F R E E F O R M # +##################################################################################### + +# __vote_submission: +# Prepare a vote for the freeform proposal +vote = { + "voteSubmission": { + "value": "VALUE_YES", # Can be either VALUE_YES or VALUE_NO + "proposalId": proposal_id, + }, + "pubKey": pubkey, + "propagate": True +} +# :vote_submission__ + +# __sign_tx_vote: +# Sign the vote command +# Hint: Setting propagate to true will also submit to a Vega node +url = f"{wallet_server_url}/api/v1/command/sync" +response = requests.post(url, headers=headers, json=vote) +helpers.check_response(response) +# :sign_tx_vote__ + +print(json.dumps(response.json(), indent=4, sort_keys=True)) +print() +print("Signed vote on freeform proposal and sent to Vega") + +print("Waiting for voting on proposal to succeed or fail...", end="", flush=True) +while True: + time.sleep(0.5) + print(".", end="", flush=True) + url = f"{data_node_url_rest}/governances?proposerPartyId={pubkey}&proposalReference={proposal_ref}" + response = requests.get(url) + + found_proposal = helpers.get_nested_response(response, "connection")[0]["node"]["proposal"] + proposal_id = found_proposal["id"] + proposal_state = found_proposal["state"] + + if proposal_state == "STATE_OPEN": + continue + + if proposal_state == "STATE_PASSED": + print("proposal vote has succeeded, waiting for enactment") + continue + + if proposal_state == "STATE_ENACTED": + break diff --git a/rest/propose-vote-enact-network-params.py b/rest/propose-vote-enact-network-params.py new file mode 100644 index 0000000..9e108ca --- /dev/null +++ b/rest/propose-vote-enact-network-params.py @@ -0,0 +1,253 @@ +#!/usr/bin/python3 + +import json +import time +import requests +import helpers + +# Vega wallet interaction helper, see login.py for detail +from login import token, pubkey + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") +# Load Vega wallet server URL, set in same way as above +wallet_server_url = helpers.get_from_env("WALLET_SERVER_URL") + +# Set to True to optionally wait/block until the new parameter change is confirmed +WAIT_FOR_PARAMETER_AFTER_VOTE = False + +##################################################################################### +# F I N D A S S E T S # +##################################################################################### + +# __get_assets: +# Request a list of assets available +url = f"{data_node_url_rest}/assets" +response = requests.get(url) +helpers.check_response(response) +# :get_assets__ + +##################################################################################### +# G O V E R N A N C E T O K E N C H E C K # +##################################################################################### + +# Get the identifier of the governance asset on the Vega network +assets = response.json()["assets"]["edges"] +vote_asset_id = next((x["node"]["id"] for x in assets if x["node"]["details"]["symbol"] == "VEGA"), None) +if vote_asset_id is None: + print("VEGA asset not found on specified Vega network, please symbol name check and try again") + exit(1) + +# Request accounts for party and check governance asset balance +url = f"{data_node_url_rest}/accounts?filter.partyIds={pubkey}" +response = requests.get(url) +helpers.check_response(response) + +# Debugging +# print("Accounts:\n{}".format( +# json.dumps(response.json(), indent=2, sort_keys=True))) + +voting_balance = 0 +accounts = response.json()["accounts"]["edges"] + +for account in accounts: + if account["account"]["asset"] == vote_asset_id: + print("Found governance asset account") + print(account) + voting_balance = account["account"]["balance"] + break + +if voting_balance == 0: + print(f"Please deposit VEGA asset to public key {pubkey} and try again") + exit(1) + +##################################################################################### +# B L O C K C H A I N T I M E # +##################################################################################### + +# __get_time: +# Request the current blockchain time, and convert to time in seconds +response = requests.get(f"{data_node_url_rest}/vega/time") +helpers.check_response(response) +blockchain_time = int(response.json()["timestamp"]) +blockchain_time_seconds = int(blockchain_time / 1e9) # Seconds precision +# :get_time__ + +assert blockchain_time > 0 +assert blockchain_time_seconds > 0 +print(f"Blockchain time: {blockchain_time} ({blockchain_time_seconds} seconds past epoch)") + +##################################################################################### +# P R O P O S E N E T W O R K P A R A M E T E R U P D A T E # +##################################################################################### + +# Set the following network parameter key and value to the pair you are looking +# to change via network parameter update proposal: + +rationale_title = "Update governance.proposal.asset.minEnact" +rationale_desc = "Proposal to update governance.proposal.asset.minEnact to 2 minutes" +parameter = "governance.proposal.asset.minEnact" +value = "2m0s" + +# Hint: for a full list of available network params see get-network-parameters.py + +# __propose_update_network_parameter: +# Compose a governance proposal for updating a network parameter with your custom reference +proposal_ref = f"{pubkey}-{helpers.generate_id(30)}" + +# Set closing/enactment and validation timestamps to valid time offsets +# from the current Vega blockchain time +closing_time = blockchain_time_seconds + 172800 +enactment_time = blockchain_time_seconds + 172900 + +submission = { + "proposalSubmission": { + "reference": proposal_ref, + "rationale": { + "title": rationale_title, + "description": rationale_desc + }, + "terms": { + "closingTimestamp": closing_time, + "enactmentTimestamp": enactment_time, + "updateNetworkParameter": { + "changes": { + "key": parameter, + "value": value, + } + }, + } + }, + "pubKey": pubkey, + "propagate": True +} +# :propose_update_network_parameter__ + +print("Network params update proposal: ", json.dumps(submission, indent=2, sort_keys=True)) +print() + +# __sign_tx_proposal: +# Sign the transaction with a proposal submission command +# Hint: Setting propagate to true will also submit to a Vega node +url = f"{wallet_server_url}/api/v1/command/sync" +headers = {"Authorization": f"Bearer {token}"} +response = requests.post(url, headers=headers, json=submission) +helpers.check_response(response) +# :sign_tx_proposal__ + +print(json.dumps(response.json(), indent=4, sort_keys=True)) + +print() +print("Signed network parameters proposal and sent to Vega") + +# Wait for proposal to be included in a block and to be accepted by Vega network +print("Waiting for blockchain...", end="", flush=True) +proposal_id = None + +url = f"{data_node_url_rest}/governances?proposerPartyId={pubkey}&proposalReference={proposal_ref}" +response = requests.get(url) +while helpers.check_nested_response(response, "connection") is not True: + time.sleep(0.5) + print(".", end="", flush=True) + response = requests.get(url) + continue + +found_proposal = helpers.get_nested_response(response, "connection")[0]["node"]["proposal"] +proposal_id = found_proposal["id"] +proposal_state = found_proposal["state"] + +print() +if (proposal_state == 'STATE_REJECTED') or ( + proposal_state == 'STATE_DECLINED') or ( + proposal_state == 'STATE_FAILED'): + print(f"Your proposal has been {proposal_state}!") + print("Due to: " + found_proposal["reason"]) + if (found_proposal["errorDetails"]) != '': + print("Further details: " + found_proposal["errorDetails"]) + exit() +else: + print("Your proposal has been accepted by the network!") + print(json.dumps(found_proposal, indent=4, sort_keys=True)) + +assert proposal_id + +##################################################################################### +# V O T E O N P A R A M E T E R # +##################################################################################### + +# __vote_submission: +# Prepare a vote for the proposal +vote = { + "voteSubmission": { + "value": "VALUE_YES", # Can be either VALUE_YES or VALUE_NO + "proposalId": proposal_id, + }, + "pubKey": pubkey, + "propagate": True +} +# :vote_submission__ + +# __sign_tx_vote: +# Sign the vote command +# Hint: Setting propagate to true will also submit to a Vega node +url = f"{wallet_server_url}/api/v1/command/sync" +response = requests.post(url, headers=headers, json=vote) +helpers.check_response(response) +# :sign_tx_vote__ + +print(json.dumps(response.json(), indent=4, sort_keys=True)) + +print() +print("Signed vote on proposal and sent to Vega") + +print("Waiting for voting on proposal to succeed or fail...", end="", flush=True) +while True: + time.sleep(0.5) + print(".", end="", flush=True) + url = f"{data_node_url_rest}/governances?proposerPartyId={pubkey}&proposalReference={proposal_ref}" + response = requests.get(url) + + found_proposal = helpers.get_nested_response(response, "connection")[0]["node"]["proposal"] + proposal_id = found_proposal["id"] + proposal_state = found_proposal["state"] + + if proposal_state == "STATE_OPEN": + continue + + if proposal_state == "STATE_PASSED": + print("proposal vote has succeeded, waiting for enactment") + continue + + if proposal_state == "STATE_ENACTED": + break + +# Optional: wait for network parameter change to be visible on network +if WAIT_FOR_PARAMETER_AFTER_VOTE is not True: + exit(1) + +############################################################################### +# W A I T F O R P A R A M E T E R # +############################################################################### + +# IMPORTANT: When voting for a proposal on Vega networks, typically a single +# YES vote from the proposer will not be enough to vote the proposal in. +# As described on docs.vega.xyz, a network parameter change will need community +# voting support to be passed and then enacted. + +# __wait_for_market: +print("Waiting for network parameter update to be completed...", end="", flush=True) +while True: + time.sleep(0.5) + print(".", end="", flush=True) + url = f"{data_node_url_rest}/network/parameters" + response = requests.get(url) + if response.status_code != 200: + continue + + for edge in response.json()["networkParameters"]["edges"]: + if edge["node"]["key"] == parameter and edge["node"]["value"] == value: + print() + print(edge["node"]) + break +# :wait_for_market__ diff --git a/rest/propose-vote-enact-new-market.py b/rest/propose-vote-enact-new-market.py new file mode 100644 index 0000000..2dd1472 --- /dev/null +++ b/rest/propose-vote-enact-new-market.py @@ -0,0 +1,364 @@ +#!/usr/bin/python3 + +import json +import time +import requests +import helpers + +# Vega wallet interaction helper, see login.py for detail +from login import token, pubkey + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") +# Load Vega wallet server URL, set in same way as above +wallet_server_url = helpers.get_from_env("WALLET_SERVER_URL") + +# Set to True to optionally wait/block until the new market proposal is enacted +WAIT_FOR_MARKET_AFTER_VOTE = False + +############################################################################### +# F I N D A S S E T S # +############################################################################### + +# __get_assets: +# Request a list of assets available and select the first one +url = f"{data_node_url_rest}/assets" +response = requests.get(url) +helpers.check_response(response) +# :get_assets__ + +# __find_asset: +# Find settlement asset with name tDAI +found_asset_id = None +assets = response.json()["assets"]["edges"] +for asset in assets: + if asset["node"]["details"]["symbol"] == "tDAI": + print("Found an asset with symbol tDAI") + print(json.dumps(asset["node"], indent=2, sort_keys=True)) + found_asset_id = asset["node"]["id"] + break +# :find_asset__ + +if found_asset_id is None: + print( + "tDAI asset not found on specified Vega network, please propose and " + "create this asset first" + ) + exit(1) + +############################################################################### +# G O V E R N A N C E T O K E N C H E C K # +############################################################################### + +# Get the identifier of the governance asset on the Vega network +vote_asset_id = next((x["node"]["id"] for x in assets if x["node"]["details"]["symbol"] == "VEGA"), None) +if vote_asset_id is None: + print("VEGA asset not found on specified Vega network, please symbol name check and try again") + exit(1) + +# Request accounts for party and check governance asset balance +url = f"{data_node_url_rest}/accounts?filter.partyIds={pubkey}" +response = requests.get(url) +helpers.check_response(response) + +# Debugging +# print("Accounts:\n{}".format( +# json.dumps(response.json(), indent=2, sort_keys=True))) + +voting_balance = 0 +accounts = response.json()["accounts"]["edges"] + +for account in accounts: + if account["account"]["asset"] == vote_asset_id: + print("Found governance asset account") + print(json.dumps(account, indent=2, sort_keys=True)) + voting_balance = account["account"]["balance"] + break + +if voting_balance == 0: + print(f"Please deposit VEGA asset to public key {pubkey} and try again") + exit(1) + +############################################################################### +# B L O C K C H A I N T I M E # +############################################################################### + +# __get_time: +# Request the current blockchain time, and convert to time in seconds +response = requests.get(f"{data_node_url_rest}/vega/time") +helpers.check_response(response) +blockchain_time = int(response.json()["timestamp"]) +blockchain_time_seconds = int(blockchain_time / 1e9) # Seconds precision +# :get_time__ + +assert blockchain_time > 0 +assert blockchain_time_seconds > 0 +print(f"Blockchain time: {blockchain_time} ({blockchain_time_seconds} seconds past epoch)") + +############################################################################### +# P R O P O S E M A R K E T # +############################################################################### + +# Further documentation on creating markets: +# https://docs.vega.xyz/testnet/tutorials/proposals/new-market-proposal + +# Hint: Governance tokens must be associated/staked to propose markets on Vega + +# __propose_market: +# Compose a governance proposal for a new market +proposal_ref = f"{pubkey}-{helpers.generate_id(30)}" + +# Set closing/enactment and validation timestamps to valid time offsets +# from the current Vega blockchain time +closing_time = blockchain_time_seconds + 80000 +enactment_time = blockchain_time_seconds + 86500 +validation_time = blockchain_time_seconds + 1 + +# A market description should be readable and is the human readable string +# for when a market is visible, this must be unique, etc +rationale_title = "New market required for tDAI April 2023 Futures" +rationale_desc = "Proposal to create a new futures market for tDAI terminating in April 2023" + +# The proposal command below contains the configuration for a new market +proposal = { + "proposalSubmission": { + "reference": proposal_ref, + "rationale": { + "title": rationale_title, + "description": rationale_desc, + }, + "terms": { + "closingTimestamp": closing_time, + "enactmentTimestamp": enactment_time, + "newMarket": { + "changes": { + "decimalPlaces": 5, + "instrument": { + "name": "BTC/DAI (2023, tDAI) " + helpers.generate_id(10), + "code": "CRYPTO:BTCDAI/APR23", + "future": { + "dataSourceSpecForSettlementData": { + "external": { + "oracle": { + "signers": [ + { + "pubKey": { + "key": "c77fe74b64b2c97723bac8c3f110e5c3d7fb78f6c6c8915a56cb962968fbcfa7" + } + } + ], + "filters": [ + { + "key": { + "name": "price.BTCDAI.value", + "type": "TYPE_INTEGER" + }, + "conditions": [ + { + "operator": "OPERATOR_GREATER_THAN", + "value": "0" + }, + { + "operator": "OPERATOR_LESS_THAN", + "value": "999999999" + } + ] + } + ] + } + } + }, + "dataSourceSpecForTradingTermination": { + "external": { + "oracle": { + "signers": [ + { + "pubKey": { + "key": "c77fe74b64b2c97723bac8c3f110e5c3d7fb78f6c6c8915a56cb962968fbcfa7" + } + } + ], + "filters": [ + { + "key": { + "name": "trading.terminated.BTCDAI", + "type": "TYPE_BOOLEAN" + }, + "conditions": [ + { + "operator": "OPERATOR_EQUALS", + "value": "true" + } + ] + } + ] + } + } + }, + "dataSourceSpecBinding": { + "settlementDataProperty": "price.BTCDAI.value", + "tradingTerminationProperty": "trading.terminated.BTCDAI" + }, + "quoteName": "tDAI", + "settlementAsset": found_asset_id, + "settlementDataDecimals": 5, + } + }, + "metadata": [ + "base:BTC", + "quote:DAI", + "class:fx/crypto", + "sector:defi", + ], + "priceMonitoringParameters": { + "triggers": [ + { + "horizon": 43200, + "probability": "0.9999999", + "auctionExtension": 300 + } + ] + }, + "liquidityMonitoringParameters": { + "targetStakeParameters": { + "timeWindow": 3600, + "scalingFactor": 10 + }, + "triggeringRatio": 0.5, + "auctionExtension": 1 + }, + "logNormal": { + "riskAversionParameter": 0.001, + "tau": 0.0001140771161, + "params": { + "mu": 0.0, + "r": 0.0, + "sigma": 1.5 + } + } + } + } + } + }, + "pubKey": pubkey, + "propagate": True +} +# :propose_market__ + +print(json.dumps(response.json(), indent=4, sort_keys=True)) + +print() +print("Signed new market proposal and sent to Vega") + +# Wait for proposal to be included in a block and to be accepted by Vega network +print("Waiting for blockchain...", end="", flush=True) +proposal_id = None + +url = f"{data_node_url_rest}/governances?proposerPartyId={pubkey}&proposalReference={proposal_ref}" +response = requests.get(url) +while helpers.check_nested_response(response, "connection") is not True: + time.sleep(0.5) + print(".", end="", flush=True) + response = requests.get(url) + continue + +found_proposal = helpers.get_nested_response(response, "connection")[0]["node"]["proposal"] +proposal_id = found_proposal["id"] +proposal_state = found_proposal["state"] + +print() +if (proposal_state == 'STATE_REJECTED') or ( + proposal_state == 'STATE_DECLINED') or ( + proposal_state == 'STATE_FAILED'): + print(f"Your proposal has been {proposal_state}!") + print("Due to: " + found_proposal["reason"]) + if (found_proposal["errorDetails"]) != '': + print("Further details: " + found_proposal["errorDetails"]) + exit() +else: + print("Your proposal has been accepted by the network!") + print(json.dumps(found_proposal, indent=4, sort_keys=True)) + +assert proposal_id + +############################################################################### +# V O T E O N M A R K E T # +############################################################################### + +# __vote_submission: +# Prepare a vote for the proposal +vote = { + "voteSubmission": { + "value": "VALUE_YES", # Can be either VALUE_YES or VALUE_NO + "proposalId": proposal_id, + }, + "pubKey": pubkey, + "propagate": True +} +# :vote_submission__ + +# __sign_tx_vote: +# Sign the vote command +# Hint: Setting propagate to true will also submit to a Vega node +url = f"{wallet_server_url}/api/v1/command/sync" +response = requests.post(url, headers=headers, json=vote) +helpers.check_response(response) +# :sign_tx_vote__ + +print(json.dumps(response.json(), indent=4, sort_keys=True)) + +print() +print("Signed vote on proposal and sent to Vega") + +print("Waiting for voting on proposal to succeed or fail...", end="", flush=True) +while True: + time.sleep(0.5) + print(".", end="", flush=True) + url = f"{data_node_url_rest}/governances?proposerPartyId={pubkey}&proposalReference={proposal_ref}" + response = requests.get(url) + + found_proposal = helpers.get_nested_response(response, "connection")[0]["node"]["proposal"] + proposal_id = found_proposal["id"] + proposal_state = found_proposal["state"] + + if proposal_state == "STATE_OPEN": + continue + + if proposal_state == "STATE_PASSED": + print("proposal vote has succeeded, waiting for enactment") + continue + + if proposal_state == "STATE_ENACTED": + break + +# Optional: wait for network parameter change to be enacted +if WAIT_FOR_MARKET_AFTER_VOTE is not True: + exit(1) + +############################################################################### +# W A I T F O R M A R K E T # +############################################################################### + +# Hint: When voting for a proposal on the Vega Testnet, typically a single +# YES vote from the proposer will not be enough to vote the market into +# existence. As described above in the previous stage, a market will need +# community voting support to be passed and then enacted. + +# __wait_for_market: +# print("Waiting for proposal to be enacted or failed...", end="", flush=True) +# done = False +# while not done: +# time.sleep(0.5) +# print(".", end="", flush=True) +# markets = requests.get(data_node_url_rest + "/markets") +# if markets.status_code != 200: +# continue +# +# for n in markets.json()["markets"]: +# if n["id"] == proposal_id: +# print() +# print(n) +# done = True +# break +# :wait_for_market__ diff --git a/rest/requirements.txt b/rest/requirements.txt new file mode 100644 index 0000000..f81a2e8 --- /dev/null +++ b/rest/requirements.txt @@ -0,0 +1,3 @@ +requests==2.27.1 +Vega-API-client==0.49.2 +websocket-client==1.3.2 diff --git a/rest/stream-market-data.py b/rest/stream-market-data.py new file mode 100644 index 0000000..773cb5d --- /dev/null +++ b/rest/stream-market-data.py @@ -0,0 +1,84 @@ +#!/usr/bin/python3 + +############################################################################### +# S T R E A M M A R K E T D A T A # +############################################################################### + +# How to stream market data information from a Data Node using Websockets: +# ---------------------------------------------------------------------- +# Pagination and Date Range are not supported, this is a realtime stream. +# ---------------------------------------------------------------------- +# The list has a required filter: +# marketIds: Vega market id (a repeated param) for one or more markets +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import websocket +import threading +import json +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +# Load Vega market id +market_id = helpers.env_market_id() +assert market_id != "" + +# Connect to the data node with a WSS based endpoint, this is not a HTTPS:// url +# Hint: to include data from multiple markets repeat the param `marketIds` +# e.g. marketIds=xxx&marketIds=yyy&marketIds=zzz +url = f"{data_node_url_rest}/stream/markets/data?marketIds={market_id}".replace("https://", "wss://") +res = [] +event = threading.Event() + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +# __stream_market_data_by_markets: +# Request a stream of live market data for one or more market ids on a Vega network + +def on_message(wsa, line): + # Vega data-node v2 returns the json line by line so we need to wait + # for a full structure before we can parse to valid JSON in python + if line == "{": + del res[:] + res.append(line) + elif line == "}": + res.append(line) + obj = json.loads(''.join(res)) + if "marketData" in obj["result"]: + # Result contains each market-data update (may be multiple) + found_market = obj["result"]["marketData"][0]["market"] + print(f"Market data found for {found_market}:") + print(obj["result"]["marketData"]) + else: + res.append(line) + +def on_error(wsa, error): + print(error) + + +def on_close(wsa, close_status_code, close_msg): + print(f"Market-data stream closed: {url}") + + +def on_open(wsa): + print(f"Market-data stream open: {url}") + + +def timeout(): + while not event.wait(timeout=30): + ws.close() + exit(1) + + +thread = threading.Thread(target=timeout) +thread.start() + +ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) +ws.on_open = on_open +ws.run_forever() +# :stream_market_data_by_markets__ diff --git a/rest/stream-orders.py b/rest/stream-orders.py new file mode 100644 index 0000000..245ba34 --- /dev/null +++ b/rest/stream-orders.py @@ -0,0 +1,91 @@ +#!/usr/bin/python3 + +############################################################################### +# S T R E A M O R D E R S # +############################################################################### + +# How to stream order information from a Data Node using Websockets: +# ---------------------------------------------------------------------- +# Pagination is not supported, but the initial snapshot may contain +# multiple pages. Date Range is not supported, this is a realtime stream. +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, including: +# partyId: Vega party id (public key) +# marketId: Vega market id +# > Include none, one or both to refine the stream of data from Vega +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import websocket +import threading +import json +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +# Load Vega market id +market_id = helpers.env_market_id() +assert market_id != "" + +# Connect to the data node with a WSS based endpoint, this is not a HTTPS:// url +# Hint: to include/filter data from a party add the param `partyId` +# e.g. ?marketIds=xxx&partyId=yyy +url = f"{data_node_url_rest}/stream/orders?marketId={market_id}".replace("https://", "wss://") +res = [] +event = threading.Event() + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +# __stream_orders_by_market: +# Request a stream of live orders and updates for a market id on a Vega network + +def on_message(wsa, line): + # Vega data-node v2 returns the json line by line so we need to wait + # for a full structure before we can parse to valid JSON in python + if line == "{": + del res[:] + res.append(line) + elif line == "}": + res.append(line) + obj = json.loads(''.join(res)) + if "snapshot" in obj["result"]: + # An 'initial image' snapshot containing current live orders (may be multiple pages) + print("Snapshot found:") + print(obj["result"]["snapshot"]) + if "updates" in obj["result"]: + # A list of order updates typically from the last block + print("Updates found:") + print(obj["result"]["updates"]) + else: + res.append(line) + + +def on_error(wsa, error): + print(error) + + +def on_close(wsa, close_status_code, close_msg): + print(f"Orders stream closed: {url}") + + +def on_open(wsa): + print(f"Orders stream open: {url}") + + +def timeout(): + while not event.wait(timeout=30): + ws.close() + exit(1) + + +thread = threading.Thread(target=timeout) +thread.start() + +ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) +ws.on_open = on_open +ws.run_forever() +# :stream_orders_by_market__ diff --git a/rest/stream-trades.py b/rest/stream-trades.py new file mode 100644 index 0000000..57540f0 --- /dev/null +++ b/rest/stream-trades.py @@ -0,0 +1,88 @@ +#!/usr/bin/python3 + +############################################################################### +# S T R E A M T R A D E S # +############################################################################### + +# How to stream trade information from a Data Node using Websockets: +# ---------------------------------------------------------------------- +# Pagination is not supported, but the initial snapshot may contain +# multiple pages. Date Range is not supported, this is a realtime stream. +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, including: +# partyId: Vega party id (public key) +# marketId: Vega market id +# > Include none, one or both to refine the stream of data from Vega +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import websocket +import threading +import json +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +# Load Vega market id +market_id = helpers.env_market_id() +assert market_id != "" + +# Connect to the data node with a WSS based endpoint, this is not a HTTPS:// url +# Hint: to include/filter data from a party add the param `partyId` +# e.g. ?marketIds=xxx&partyId=yyy +url = f"{data_node_url_rest}/stream/trades?market_id={market_id}".replace("https://", "wss://") +res = [] +event = threading.Event() + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +# __stream_trades_by_market: +# Request a stream of live trades and updates for a market id on a Vega network + +def on_message(wsa, line): + # Vega data-node v2 returns the json line by line so we need to wait + # for a full structure before we can parse to valid JSON in python + if line == "{": + del res[:] + res.append(line) + elif line == "}": + res.append(line) + obj = json.loads(''.join(res)) + if "trades" in obj["result"]: + # Result contains each trade update (may be multiple) + total_in_update = len(obj["result"]["trades"]) + print(f"Trade data found [{total_in_update}]:") + print(obj["result"]["trades"]) + else: + res.append(line) + + +def on_error(wsa, error): + print(error) + + +def on_close(wsa, close_status_code, close_msg): + print(f"Trades stream closed: {url}") + + +def on_open(wsa): + print(f"Trades stream open: {url}") + + +def timeout(): + while not event.wait(timeout=30): + ws.close() + exit(1) + + +thread = threading.Thread(target=timeout) +thread.start() + +ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) +ws.on_open = on_open +ws.run_forever() +# :stream_trades_by_market__ diff --git a/rest/submit-amend-cancel-liquidity-commitment.py b/rest/submit-amend-cancel-liquidity-commitment.py new file mode 100644 index 0000000..7d03e49 --- /dev/null +++ b/rest/submit-amend-cancel-liquidity-commitment.py @@ -0,0 +1,200 @@ +#!/usr/bin/python3 + +import json +import time +import requests +import helpers + +# Vega wallet interaction helper, see login.py for detail +from login import token, pubkey + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") +# Load Vega wallet server URL, set in same way as above +wallet_server_url = helpers.get_from_env("WALLET_SERVER_URL") + +# Load Vega market id +market_id = helpers.env_market_id() +assert market_id != "" + +# Set to False to ONLY submit/amend a liquidity commitment (no cancellation) +CANCEL_LP_AFTER_SUBMISSION = True + +# Set market id in ENV or uncomment the line below to override market id directly +market_id = "e503cadb437861037cddfd7263d25b69102098a97573db23f8e5fc320cea1ce9" + +##################################################################################### +# S U B M I T L I Q U I D I T Y C O M M I T M E N T # +##################################################################################### + +# Hint: commitmentAmount is an integer. For example 123456 is a price of 1.23456, +# for a market which is configured to have a precision of 5 decimal places. + +# __create_liquidity_commitment: +# Compose your submit liquidity provision command +# Set your own user specific reference to find the commitment by reference and +# as a foreign key to your local client/trading application +liquidity_ref = f"{pubkey}-{helpers.generate_id(30)}" +submission = { + "liquidityProvisionSubmission": { + "marketId": market_id, + "commitmentAmount": "100", + "fee": "0.01", + "buys": [ + { + "offset": "1", + "proportion": "1", + "reference": "PEGGED_REFERENCE_MID" + }, + { + "offset": "2", + "proportion": "2", + "reference": "PEGGED_REFERENCE_MID" + } + ], + "sells": [ + { + "offset": "1", + "proportion": "1", + "reference": "PEGGED_REFERENCE_MID" + }, + { + "offset": "2", + "proportion": "2", + "reference": "PEGGED_REFERENCE_MID" + }, + { + "offset": "3", + "proportion": "5", + "reference": "PEGGED_REFERENCE_MID" + } + ], + "reference": liquidity_ref + }, + "pubKey": pubkey, + "propagate": True +} +# :create_liquidity_commitment__ + +print("Liquidity commitment submission:\n{}".format( + json.dumps(submission, indent=2, sort_keys=True) +)) + +# __sign_tx_liquidity_submit: +# Sign the transaction with an liquidity commitment command +# Hint: Setting propagate to true will also submit to a Vega node +url = f"{wallet_server_url}/api/v1/command/sync" +headers = {"Authorization": f"Bearer {token}"} +response = requests.post(url, headers=headers, json=submission) +helpers.check_response(response) +# :sign_tx_liquidity_submit__ + +print(json.dumps(response.json(), indent=4, sort_keys=True)) +print() + +print("Signed liquidity commitment and sent to Vega") +print() + +# Wait for cancellation to be included in a block +print("Waiting for blockchain...") +time.sleep(3) + +##################################################################################### +# L I S T L I Q U I D I T Y P R O V I S I O N S # +##################################################################################### + +# __get_liquidity_provisions: +# Request liquidity provisions for a party on a Vega network +url = f"{data_node_url_rest}/liquidity/provisions?partyId={pubkey}" +response = requests.get(url) +helpers.check_response(response) +print("Liquidity Provisions for party:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True) +)) +# :get_liquidity_provisions__ + +##################################################################################### +# A M E N D L I Q U I D I T Y C O M M I T M E N T # +##################################################################################### + +# __amend_liquidity_commitment: +# Compose a liquidity commitment order message +# (it will now serve as an amendment request): +# modify fields you want to be amended +submission = { + "liquidityProvisionAmendment": { + "marketId": market_id, + "commitmentAmount": "500000000000000000000", + "fee": "0.005", + "buys": [ + { + "offset": "1", + "proportion": "1", + "reference": "PEGGED_REFERENCE_MID" + } + ], + "sells": [ + { + "offset": "1", + "proportion": "1", + "reference": "PEGGED_REFERENCE_MID" + } + ] + }, + "pubKey": pubkey, + "propagate": True +} +# :amend_liquidity_commitment__ + +print("Liquidity commitment amendment:\n{}".format( + json.dumps(submission, indent=2, sort_keys=True) +)) + +# __sign_tx_liquidity_amend: +# Sign the transaction with an order submission command +# Hint: Setting propagate to true will also submit to a Vega node +url = f"{wallet_server_url}/api/v1/command/sync" +response = requests.post(url, headers=headers, json=submission) +helpers.check_response(response) +# :sign_tx_liquidity_amend__ + +print("Signed liquidity commitment amendment and sent to Vega") + +if CANCEL_LP_AFTER_SUBMISSION is not True: + exit(1) + +##################################################################################### +# C A N C E L L I Q U I D I T Y C O M M I T M E N T # +##################################################################################### + +# __cancel_liquidity_commitment: +# Compose a liquidity commitment cancellation command +# Hint: The transaction may get rejected if removing previously supplied liquidity +# will result in insufficient liquidity for the market to operate +submission = { + "liquidityProvisionCancellation": { + "marketId": market_id, + }, + "pubKey": pubkey, + "propagate": True +} +# :cancel_liquidity_commitment__ + +print("Liquidity commitment cancellation:\n{}".format( + json.dumps(submission, indent=2, sort_keys=True) +)) + +# __sign_tx_liquidity_cancel: +# Sign the transaction with an order submission command +# Hint: Setting propagate to true will also submit to a Vega node +url = f"{wallet_server_url}/api/v1/command/sync" +response = requests.post(url, headers=headers, json=submission) +helpers.check_response(response) +# :sign_tx_liquidity_cancel__ + +print("Signed liquidity commitment cancellation and sent to Vega") + +# Wait for cancellation to be included in a block +print("Waiting for blockchain...") +time.sleep(3) diff --git a/rest/submit-amend-cancel-order.py b/rest/submit-amend-cancel-order.py new file mode 100644 index 0000000..f4bfb1d --- /dev/null +++ b/rest/submit-amend-cancel-order.py @@ -0,0 +1,242 @@ +#!/usr/bin/python3 + +import requests +import time +import helpers +import json + +# Vega wallet interaction helper, see login.py for detail +from login import token, pubkey + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") +# Load Vega wallet server URL, set in same way as above +wallet_server_url = helpers.get_from_env("WALLET_SERVER_URL") + +# Load Vega market id +market_id = helpers.env_market_id() +assert market_id != "" + +# Set to False to ONLY submit/amend an order (no cancellation) +# e.g. orders will remain on the book +CANCEL_ORDER_AFTER_SUBMISSION = True + +# Set market id in ENV or uncomment the line below to override market id directly +# market_id = "e503cadb437861037cddfd7263d25b69102098a97573db23f8e5fc320cea1ce9" + +############################################################################### +# B L O C K C H A I N T I M E # +############################################################################### + +# __get_expiry_time: +# Request the current blockchain time, calculate an expiry time +response = requests.get(f"{data_node_url_rest}/vega/time") +helpers.check_response(response) +blockchain_time = int(response.json()["timestamp"]) +expiresAt = str(int(blockchain_time + 120 * 1e9)) # expire in 2 minutes +# :get_expiry_time__ + +assert blockchain_time > 0 +print(f"Blockchain time: {blockchain_time}") + + +############################################################################### +# S U B M I T O R D E R # +############################################################################### + +# __submit_order: +# Compose your submit order command, with desired deal ticket information +# Set your own user specific reference to find the order in next step and +# as a foreign key to your local client/trading application +order_ref = f"{pubkey}-{helpers.generate_id(30)}" +submission = { + "orderSubmission": { + "marketId": market_id, + "price": "1", # Hint: price is an integer. For example 123456 + "size": "100", # is a price of 1.23456, assuming 5 decimal places. + "side": "SIDE_BUY", + "timeInForce": "TIME_IN_FORCE_GTT", + "expiresAt": expiresAt, + "type": "TYPE_LIMIT", + "reference": order_ref + }, + "pubKey": pubkey, + "propagate": True +} +# :submit_order__ + +print("Order submission: ", json.dumps(submission, indent=2, sort_keys=True)) +print() + +# __sign_tx_order: +# Sign the transaction with an order submission command +# Hint: Setting propagate to true will also submit to a Vega node +url = f"{wallet_server_url}/api/v1/command/sync" +headers = {"Authorization": f"Bearer {token}"} +response = requests.post(url, headers=headers, json=submission) +helpers.check_response(response) +# :sign_tx_order__ + +print(json.dumps(response.json(), indent=4, sort_keys=True)) +print() + +print("Signed order and sent to Vega") + +# Wait for order submission to be included in a block +print("Waiting for blockchain...", end="", flush=True) +url = f"{data_node_url_rest}/orders?partyId={pubkey}&reference={order_ref}" +response = requests.get(url) +while helpers.check_nested_response(response, "orders") is not True: + time.sleep(0.5) + print(".", end="", flush=True) + response = requests.get(url) + +found_order = helpers.get_nested_response(response, "orders")[0]["node"] + +orderID = found_order["id"] +orderStatus = found_order["status"] +createVersion = found_order["version"] + +print() +print(f"\nOrder processed, ID: {orderID}, Status: {orderStatus}, Version: {createVersion}") +if orderStatus == "STATUS_REJECTED": + print("The order was rejected by Vega") + exit(1) # Halt processing at this stage + +##################################################################################### +# A M E N D O R D E R # +##################################################################################### + +# __amend_order: +# Compose your amend order command, with changes to existing order +amendment = { + "orderAmendment": { + "orderId": orderID, + "marketId": market_id, + "price": "2", + "sizeDelta": "-25", + "timeInForce": "TIME_IN_FORCE_GTC", + }, + "pubKey": pubkey, + "propagate": True +} +# :amend_order__ + +print() +print("Order amendment: ", json.dumps(amendment, indent=2, sort_keys=True)) +print() + +# __sign_tx_amend: +# Sign the transaction with an order amendment command +# Hint: Setting propagate to true will also submit to a Vega node +url = f"{wallet_server_url}/api/v1/command/sync" +response = requests.post(url, headers=headers, json=amendment) +helpers.check_response(response) +# :sign_tx_amend__ + +print("Signed amendment and sent to Vega") + +# Wait for amendment to be included in a block +print("Waiting for blockchain...", end="", flush=True) +time.sleep(3) + +url = f"{data_node_url_rest}/orders?partyId={pubkey}&reference={order_ref}" +response = requests.get(url) + +found_order = helpers.get_nested_response(response, "orders")[0]["node"] + +orderID = found_order["id"] +orderPrice = found_order["price"] +orderSize = found_order["size"] +orderTif = found_order["timeInForce"] +orderStatus = found_order["status"] +orderVersion = found_order["version"] + +print() +print("Amended Order:") +print(f"ID: {orderID}, Status: {orderStatus}, Price(Old): 1, " + f"Price(New): {orderPrice}, Size(Old): 100, Size(New): {orderSize}, " + f"TimeInForce(Old): TIME_IN_FORCE_GTT, TimeInForce(New): {orderTif}, " + f"Version(Old): {createVersion}, Version(new): {orderVersion}") +if orderStatus == "STATUS_REJECTED": + print("The order amendment was rejected by Vega") + exit(1) # Halt processing at this stage + +if CANCEL_ORDER_AFTER_SUBMISSION is not True: + exit(1) + +##################################################################################### +# C A N C E L O R D E R S # +##################################################################################### + +# Select the mode to cancel orders from the following (comment out others), default = 3 + +# __cancel_order_req1: +# 1 - Cancel single order for party (pubkey) +cancellation = { + "orderCancellation": { + # Include market and order identifier fields to cancel single order. + "marketId": market_id, + "orderId": orderID, + }, + "pubKey": pubkey, + "propagate": True, +} +# :cancel_order_req1__ + +# __cancel_order_req2: +# 2 - Cancel all orders on market for party (pubkey) +cancellation = { + "orderCancellation": { + # Only include market identifier field. + "marketId": market_id, + }, + "pubKey": pubkey, + "propagate": True, +} +# :cancel_order_req2__ + +# __cancel_order_req3: +# 3 - Cancel all orders on all markets for party (pubkey) +cancellation = { + "orderCancellation": {}, + "pubKey": pubkey, + "propagate": True, +} +# :cancel_order_req3__ + +print() +print("Order cancellation: ", json.dumps(cancellation, indent=2, sort_keys=True)) +print() + +# __sign_tx_cancel: +# Sign the transaction for cancellation +# Hint: Setting propagate to true will also submit to a Vega node +url = f"{wallet_server_url}/api/v1/command/sync" +response = requests.post(url, headers=headers, json=cancellation) +helpers.check_response(response) +# :sign_tx_cancel__ + +print("Signed cancellation and sent to Vega") +print() + +# Wait for cancellation to be included in a block +print("Waiting for blockchain...") +time.sleep(3) + +url = f"{data_node_url_rest}/orders?partyId={pubkey}&reference={order_ref}" +response = requests.get(url) + +found_order = helpers.get_nested_response(response, "orders")[0]["node"] + +orderID = found_order["id"] +orderStatus = found_order["status"] + +print("Cancelled Order(s):") +print(f"ID: {orderID}, Status: {orderStatus}") +if orderStatus == "STATUS_REJECTED": + print("The order cancellation was rejected by Vega") + exit(1) # Halt processing at this stage + +print("Order(s) cancelled") diff --git a/rest/submit-amend-cancel-pegged-order.py b/rest/submit-amend-cancel-pegged-order.py new file mode 100644 index 0000000..73ff28a --- /dev/null +++ b/rest/submit-amend-cancel-pegged-order.py @@ -0,0 +1,229 @@ +#!/usr/bin/python3 + +import requests +import time +import helpers +import json + +# Vega wallet interaction helper, see login.py for detail +from login import token, pubkey + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") +# Load Vega wallet server URL, set in same way as above +wallet_server_url = helpers.get_from_env("WALLET_SERVER_URL") + +# Load Vega market id +market_id = helpers.env_market_id() +assert market_id != "" + +# Set to False to ONLY submit/amend an order (no cancellation) +# e.g. orders will remain on the book +CANCEL_ORDER_AFTER_SUBMISSION = True + +# Set market id in ENV or uncomment the line below to override market id directly +market_id = "e503cadb437861037cddfd7263d25b69102098a97573db23f8e5fc320cea1ce9" + +##################################################################################### +# B L O C K C H A I N T I M E # +##################################################################################### + +# __get_expiry_time: +# Request the current blockchain time, calculate an expiry time +response = requests.get(f"{data_node_url_rest}/vega/time") +helpers.check_response(response) +blockchain_time = int(response.json()["timestamp"]) +expiresAt = str(int(blockchain_time + 120 * 1e9)) # expire in 2 minutes +# :get_expiry_time__ + +assert blockchain_time > 0 +print(f"Blockchain time: {blockchain_time}") + +##################################################################################### +# S U B M I T P E G G E D O R D E R # +##################################################################################### + +# __submit_pegged_order: +# Compose your submit pegged order command +# Set your own user specific reference to find the order in next step and +# as a foreign key to your local client/trading application +order_ref = f"{pubkey}-{helpers.generate_id(30)}" +submission = { + "orderSubmission": { + "marketId": market_id, + "size": "50", + "side": "SIDE_BUY", + "timeInForce": "TIME_IN_FORCE_GTT", + "expiresAt": expiresAt, + "type": "TYPE_LIMIT", + "reference": order_ref, + "peggedOrder": { + "offset": "5", + "reference": "PEGGED_REFERENCE_MID" + } + }, + "pubKey": pubkey, + "propagate": True +} +# :submit_pegged_order__ + +print() +print("Pegged order submission: ", json.dumps(submission, indent=2, sort_keys=True)) +print() + +# __sign_tx_pegged_order: +# Sign the transaction with a pegged order submission command +# Hint: Setting propagate to true will also submit to a Vega node +url = f"{wallet_server_url}/api/v1/command/sync" +headers = {"Authorization": f"Bearer {token}"} +response = requests.post(url, headers=headers, json=submission) +helpers.check_response(response) +# :sign_tx_pegged_order__ + +print(json.dumps(response.json(), indent=4, sort_keys=True)) +print() + +print("Signed pegged order and sent to Vega") + +# Wait for order submission to be included in a block +print("Waiting for blockchain...", end="", flush=True) +url = f"{data_node_url_rest}/orders?partyId={pubkey}&reference={order_ref}" +response = requests.get(url) +while helpers.check_nested_response(response, "orders") is not True: + time.sleep(0.5) + print(".", end="", flush=True) + response = requests.get(url) + +found_order = helpers.get_nested_response(response, "orders")[0]["node"] + +orderID = found_order["id"] +orderStatus = found_order["status"] +createVersion = found_order["version"] +orderPegged = found_order["peggedOrder"] + +print() +print(f"\nPegged order processed, ID: {orderID}, Status: {orderStatus}, Version: {createVersion}") +if orderStatus == "STATUS_REJECTED": + print("The pegged order was rejected by Vega") + exit(1) # Halt processing at this stage +else: + print(f"Pegged at: {orderPegged}") + +##################################################################################### +# A M E N D P E G G E D O R D E R # +##################################################################################### + +# __amend_pegged_order: +# Compose your amend order command, with changes to existing order +amendment = { + "orderAmendment": { + "orderId": orderID, + "marketId": market_id, + "sizeDelta": "25", + "timeInForce": "TIME_IN_FORCE_GTC", + "peggedReference": "PEGGED_REFERENCE_BEST_BID", + "peggedOffset": "-100", + }, + "pubKey": pubkey, + "propagate": True +} +# :amend_pegged_order__ + +print() +print("Pegged order amendment: ", json.dumps(amendment, indent=2, sort_keys=True)) +print() + +# __sign_tx_pegged_amend: +# Sign the transaction with a pegged order amendment command +# Note: Setting propagate to true will also submit to a Vega node +url = f"{wallet_server_url}/api/v1/command/sync" +response = requests.post(url, headers=headers, json=amendment) +helpers.check_response(response) +# :sign_tx_pegged_amend__ + +print("Signed pegged order amendment and sent to Vega") + +# Wait for order amendment to be included in a block +print("Waiting for blockchain...") +time.sleep(3) + +url = f"{data_node_url_rest}/orders?partyId={pubkey}&reference={order_ref}" +response = requests.get(url) + +found_order = helpers.get_nested_response(response, "orders")[0]["node"] + +orderID = found_order["id"] +orderStatus = found_order["status"] +orderVersion = found_order["version"] +orderPegged = found_order["peggedOrder"] +orderPrice = found_order["price"] +orderSize = found_order["size"] +orderTif = found_order["timeInForce"] + +print() +print("Amended pegged order:") +print(f"ID: {orderID}, Status: {orderStatus}, " + f"Size(Old): 50, Size(New): {orderSize}, " + f"TimeInForce(Old): TIME_IN_FORCE_GTT, TimeInForce(New): {orderTif}, " + f"Version(Old): {createVersion}, Version(new): {orderVersion}") + +if orderStatus == "STATUS_REJECTED": + print("The pegged order amendment was rejected by Vega") + exit(1) # Halt processing at this stage +else: + print(f"Pegged at: {orderPegged}") + +##################################################################################### +# C A N C E L P E G G E D O R D E R # +##################################################################################### + +# Hint: For a full example with combinations please see submit-amend-cancel-order.py + +# __cancel_pegged_order: +# # Cancellation command for the specific order +cancellation = { + "orderCancellation": { + # Include market and order identifier fields to cancel single order. + "marketId": market_id, + "orderId": orderID, + }, + "pubKey": pubkey, + "propagate": True, +} +# :cancel_pegged_order__ + +print() +print("Pegged order cancellation: ", json.dumps(cancellation, indent=2, sort_keys=True)) +print() + +# __sign_tx_pegged_cancel: +# Sign the transaction for cancellation +# Hint: Setting propagate to true will also submit to a Vega node +url = f"{wallet_server_url}/api/v1/command/sync" +response = requests.post(url, headers=headers, json=cancellation) +helpers.check_response(response) +# :sign_tx_pegged_cancel__ + +print("Signed pegged cancellation and sent to Vega") +print() + +# Wait for cancellation to be included in a block +print("Waiting for blockchain...") +time.sleep(3) + +url = f"{data_node_url_rest}/orders?partyId={pubkey}&reference={order_ref}" +response = requests.get(url) + +found_order = helpers.get_nested_response(response, "orders")[0]["node"] + +orderID = found_order["id"] +orderStatus = found_order["status"] + +print("Cancelled pegged order:") +print(f"ID: {orderID}, Status: {orderStatus}") +if orderStatus == "STATUS_REJECTED": + print("The pegged order cancellation was rejected by Vega") + exit(1) # Halt processing at this stage + +print("Pegged order cancelled") diff --git a/vega-config b/vega-config new file mode 100644 index 0000000..beec1ad --- /dev/null +++ b/vega-config @@ -0,0 +1,20 @@ +#!/usr/bin/env bash + +# Default server configuration used by REST/GRPC/GRAPHQL examples + +DATA_NODE_URL_REST="https://api.n06.testnet.vega.xyz/api/v2" +DATA_NODE_URL_GRAPHQL="https://api.n07.testnet.vega.xyz/graphql" +DATA_NODE_URL_GRPC="n07.testnet.vega.xyz:3007" +WALLET_SERVER_URL="https://wallet.testnet.vega.xyz" +MARKET_ID="" +PARTY_ID="" +ASSET_ID="" + +export DATA_NODE_URL_GRPC +export DATA_NODE_URL_REST +export DATA_NODE_URL_GRAPHQL +export WALLET_SERVER_URL + +export MARKET_ID +export PARTY_ID +export ASSET_ID diff --git a/vega-config-stagnet1 b/vega-config-stagnet1 new file mode 100644 index 0000000..31b6de6 --- /dev/null +++ b/vega-config-stagnet1 @@ -0,0 +1,20 @@ +#!/usr/bin/env bash + +# Default server configuration used by REST/GRPC/GRAPHQL examples + +DATA_NODE_URL_REST="https://api.n00.stagnet1.vega.xyz/api/v2" +DATA_NODE_URL_GRAPHQL="https://api.n00.stagnet1.vega.xyz/graphql" +DATA_NODE_URL_GRPC="n00.stagnet1.vega.xyz:3007" +WALLET_SERVER_URL="localhost:1127" +MARKET_ID="" +PARTY_ID="" +ASSET_ID="" + +export DATA_NODE_URL_GRPC +export DATA_NODE_URL_REST +export DATA_NODE_URL_GRAPHQL +export WALLET_SERVER_URL + +export MARKET_ID +export PARTY_ID +export ASSET_ID diff --git a/vega-config-stagnet3 b/vega-config-stagnet3 new file mode 100644 index 0000000..d266dba --- /dev/null +++ b/vega-config-stagnet3 @@ -0,0 +1,20 @@ +#!/usr/bin/env bash + +# Default server configuration used by REST/GRPC/GRAPHQL examples + +DATA_NODE_URL_REST="https://api.n01.stagnet3.vega.xyz/api/v2" +DATA_NODE_URL_GRAPHQL="https://api.n01.stagnet3.vega.xyz/graphql" +DATA_NODE_URL_GRPC="n01.stagnet3.vega.xyz:3007" +WALLET_SERVER_URL="localhost:1127" +MARKET_ID="" +PARTY_ID="" +ASSET_ID="" + +export DATA_NODE_URL_GRPC +export DATA_NODE_URL_REST +export DATA_NODE_URL_GRAPHQL +export WALLET_SERVER_URL + +export MARKET_ID +export PARTY_ID +export ASSET_ID From 17b80af6b16d0cfb840db19da4e36f82eb87bea5 Mon Sep 17 00:00:00 2001 From: Sunny Dasgupta Date: Mon, 21 Nov 2022 14:02:15 +0000 Subject: [PATCH 03/33] Get assets --- graphql/get-asset.graphql | 19 +++++++++++-------- graphql/get-assets.graphql | 19 +++++++++++-------- 2 files changed, 22 insertions(+), 16 deletions(-) diff --git a/graphql/get-asset.graphql b/graphql/get-asset.graphql index 09783f9..d931173 100644 --- a/graphql/get-asset.graphql +++ b/graphql/get-asset.graphql @@ -1,11 +1,14 @@ -query getAsset { - asset(assetId:"6d9d35f657589e40ddfb448b7ad4a7463b66efb307527fedd2aa7df1bbd5ea61"){ - name - symbol - totalSupply - decimals - source{ - __typename +{ + assetsConnection (id: "b340c130096819428a62e5df407fd6abe66e444b89ad64f670beb98621c9c663"){ + edges { + node { + id + name + symbol + decimals + quantum + status + } } } } \ No newline at end of file diff --git a/graphql/get-assets.graphql b/graphql/get-assets.graphql index a3e6b71..0ec11ea 100644 --- a/graphql/get-assets.graphql +++ b/graphql/get-assets.graphql @@ -1,11 +1,14 @@ -query getAsset { - assets{ - name - symbol - totalSupply - decimals - source{ - __typename +{ + assetsConnection { + edges { + node { + id + name + symbol + decimals + quantum + status + } } } } \ No newline at end of file From 3603a35d15a6d3b419fa1803efa2612faa1594f8 Mon Sep 17 00:00:00 2001 From: Sunny Dasgupta Date: Mon, 21 Nov 2022 14:07:03 +0000 Subject: [PATCH 04/33] Get markets --- graphql/Get-Market.graphql | 38 +++++++++++++++++++--------- graphql/Get-Markets.graphql | 50 +++++++++++++++++++------------------ 2 files changed, 52 insertions(+), 36 deletions(-) diff --git a/graphql/Get-Market.graphql b/graphql/Get-Market.graphql index 7293586..20782a5 100644 --- a/graphql/Get-Market.graphql +++ b/graphql/Get-Market.graphql @@ -1,16 +1,30 @@ -query GetMarker( - $marketID: ID! = "9b358cb36b63001ae74b9f815c30a58f1db258fa11b17ba082a66abebed75951" -){ - market(id:$marketID){ - name - tradableInstrument{ - instrument{ - name +{ + marketsConnection (id: "e9ec6d5c46a7e7bcabf9ba7a893fa5a5eeeec08b731f06f7a6eb7bf0e605b829") { + edges { + node { + id + tradingMode + marketTimestamps { + proposed + pending + open + close + } + depth { + buy { + volume + numberOfOrders + } + sell { + volume + numberOfOrders + } + lastTrade { + price + size + } + } } } - orders(first:10){ - id - price - } } } \ No newline at end of file diff --git a/graphql/Get-Markets.graphql b/graphql/Get-Markets.graphql index dd56349..65238e2 100644 --- a/graphql/Get-Markets.graphql +++ b/graphql/Get-Markets.graphql @@ -1,28 +1,30 @@ -query GetMarkets{ - markets{ - id - name - tradingMode - marketTimestamps{ - proposed - pending - open - close - } - depth { - buy{ - volume - numberOfOrders - } - sell{ - volume - numberOfOrders +{ + marketsConnection { + edges { + node { + id + tradingMode + marketTimestamps { + proposed + pending + open + close + } + depth { + buy { + volume + numberOfOrders + } + sell { + volume + numberOfOrders + } + lastTrade { + price + size + } + } } - lastTrade{ - price - size - } } - } } \ No newline at end of file From e7dcad273fa3ad492361ef691f2066afe659bd33 Mon Sep 17 00:00:00 2001 From: Sunny Dasgupta Date: Mon, 21 Nov 2022 14:14:56 +0000 Subject: [PATCH 05/33] Add query names --- graphql/Get-Market.graphql | 2 +- graphql/Get-Markets.graphql | 2 +- graphql/get-asset.graphql | 2 +- graphql/get-assets.graphql | 2 +- graphql/get-network-parameters.graphql | 12 ++++++++---- graphql/get-vega-time.graphql | 2 +- 6 files changed, 13 insertions(+), 9 deletions(-) diff --git a/graphql/Get-Market.graphql b/graphql/Get-Market.graphql index 20782a5..9eff562 100644 --- a/graphql/Get-Market.graphql +++ b/graphql/Get-Market.graphql @@ -1,4 +1,4 @@ -{ +query getMarket { marketsConnection (id: "e9ec6d5c46a7e7bcabf9ba7a893fa5a5eeeec08b731f06f7a6eb7bf0e605b829") { edges { node { diff --git a/graphql/Get-Markets.graphql b/graphql/Get-Markets.graphql index 65238e2..42deca9 100644 --- a/graphql/Get-Markets.graphql +++ b/graphql/Get-Markets.graphql @@ -1,4 +1,4 @@ -{ +query getMarkets { marketsConnection { edges { node { diff --git a/graphql/get-asset.graphql b/graphql/get-asset.graphql index d931173..e7a074f 100644 --- a/graphql/get-asset.graphql +++ b/graphql/get-asset.graphql @@ -1,4 +1,4 @@ -{ +query getAsset { assetsConnection (id: "b340c130096819428a62e5df407fd6abe66e444b89ad64f670beb98621c9c663"){ edges { node { diff --git a/graphql/get-assets.graphql b/graphql/get-assets.graphql index 0ec11ea..0c8c2f7 100644 --- a/graphql/get-assets.graphql +++ b/graphql/get-assets.graphql @@ -1,4 +1,4 @@ -{ +query getAssets { assetsConnection { edges { node { diff --git a/graphql/get-network-parameters.graphql b/graphql/get-network-parameters.graphql index 3a87452..13a5b49 100644 --- a/graphql/get-network-parameters.graphql +++ b/graphql/get-network-parameters.graphql @@ -1,6 +1,10 @@ -query GetNetworkParameters{ - networkParameters{ - key - value +query getNetworkParameters { + networkParametersConnection { + edges { + node { + key + value + } + } } } \ No newline at end of file diff --git a/graphql/get-vega-time.graphql b/graphql/get-vega-time.graphql index 730efa5..484ccc1 100644 --- a/graphql/get-vega-time.graphql +++ b/graphql/get-vega-time.graphql @@ -1,5 +1,5 @@ query GetVegaTime { - statistics{ + statistics { vegaTime } } \ No newline at end of file From 49c738451ef3d33a5fa319f1e8c6e30727668722 Mon Sep 17 00:00:00 2001 From: Sunny Dasgupta Date: Mon, 21 Nov 2022 14:30:42 +0000 Subject: [PATCH 06/33] Orders --- graphql/get-orderbyreference.graphql | 6 ++-- .../get-orders-and-trades-for-market.graphql | 34 +++++++++++-------- .../get-orders-and-trades-for-party.graphql | 32 ++++++++++------- 3 files changed, 42 insertions(+), 30 deletions(-) diff --git a/graphql/get-orderbyreference.graphql b/graphql/get-orderbyreference.graphql index 08ebfcf..3b6c13c 100644 --- a/graphql/get-orderbyreference.graphql +++ b/graphql/get-orderbyreference.graphql @@ -1,14 +1,14 @@ query GetOrderByID( - $orderID: ID! = "V0000021536-0000000059" + $orderID: ID! = "7e862ff63b4d70380b0b78ea5762e346ac1e711ec2516bc9994f92c7c19a3af6" ){ - orderByID(orderId:$orderID){ + orderByID(id:$orderID){ id price timeInForce side size market{ - name + id } updatedAt } diff --git a/graphql/get-orders-and-trades-for-market.graphql b/graphql/get-orders-and-trades-for-market.graphql index a620b93..f84d581 100644 --- a/graphql/get-orders-and-trades-for-market.graphql +++ b/graphql/get-orders-and-trades-for-market.graphql @@ -1,17 +1,23 @@ -query GetOrderTradesForMarket ( - $marketId: ID! = "" -){ - market(id:$marketId){ - name - orders{ - id - price - side - status - trades { - id - price - size +query GetOrderTradesForMarket($marketId: ID! = "ad2e531441c2e8a43e85423db399a4acc8f9a8a2376304a4c377d0da8eb31e80") { + market(id: $marketId) { + id + ordersConnection { + edges { + node { + id + price + side + status + tradesConnection { + edges { + node { + id + price + size + } + } + } + } } } } diff --git a/graphql/get-orders-and-trades-for-party.graphql b/graphql/get-orders-and-trades-for-party.graphql index 4c4efba..e2133fd 100644 --- a/graphql/get-orders-and-trades-for-party.graphql +++ b/graphql/get-orders-and-trades-for-party.graphql @@ -1,17 +1,23 @@ -query GetOrderTradesForParty ( - $partyId: ID! = "38b36ca0ca7076a02bde23f08765158bf6efaef409b9a98966f2f5e3eb07042d" -){ - party(id:$partyId){ +query GetOrderTradesForParty($partyId: ID! = "644a1a8bb2fba612612dd6a5d400c49eb469d91dff777b0eda3f4cd554296759") { + party(id: $partyId) { id - orders{ - id - price - side - status - trades { - id - price - size + ordersConnection { + edges { + node { + id + price + side + status + tradesConnection { + edges { + node { + id + price + size + } + } + } + } } } } From 9f0ae669279e7fac064203b41be2bac4e24640ca Mon Sep 17 00:00:00 2001 From: Sunny Dasgupta Date: Mon, 21 Nov 2022 15:14:17 +0000 Subject: [PATCH 07/33] Parties accounts and trades for order --- graphql/get-parties-accounts.graphql | 31 +++++++++++++++++----------- graphql/get-trades-for-order.graphql | 18 +++++++++------- 2 files changed, 29 insertions(+), 20 deletions(-) diff --git a/graphql/get-parties-accounts.graphql b/graphql/get-parties-accounts.graphql index 435308f..6022d89 100644 --- a/graphql/get-parties-accounts.graphql +++ b/graphql/get-parties-accounts.graphql @@ -1,17 +1,24 @@ query getParties { - parties{ - id - accounts{ - balance - asset { + partiesConnection { + edges { + node { id - name - symbol - } - type - market { - id - name + accountsConnection { + edges { + node { + balance + asset { + id + name + symbol + } + type + market { + id + } + } + } + } } } } diff --git a/graphql/get-trades-for-order.graphql b/graphql/get-trades-for-order.graphql index 9e11720..495a229 100644 --- a/graphql/get-trades-for-order.graphql +++ b/graphql/get-trades-for-order.graphql @@ -1,11 +1,13 @@ -query GetTradesForOrder( - $orderId: ID! = "" -) { - order(id: $orderId) { - trades { - id - price - size +query GetTradesForOrder($orderId: ID! = "7e862ff63b4d70380b0b78ea5762e346ac1e711ec2516bc9994f92c7c19a3af6") { + orderByID(id: $orderId) { + tradesConnection { + edges { + node { + id + price + size + } + } } } } From 65c68ef2b088c6790d78fab8d3dc364ff455df04 Mon Sep 17 00:00:00 2001 From: Sunny Dasgupta Date: Mon, 21 Nov 2022 15:22:53 +0000 Subject: [PATCH 08/33] Subscriptions --- graphql/stream-events.graphql | 63 +++++++++++++--------- graphql/stream-market-data.graphql | 4 +- graphql/stream-orders-by-reference.graphql | 6 +-- graphql/stream-orders.graphql | 5 +- graphql/stream-trades.graphql | 8 ++- 5 files changed, 46 insertions(+), 40 deletions(-) diff --git a/graphql/stream-events.graphql b/graphql/stream-events.graphql index 6302c2c..92fe82b 100644 --- a/graphql/stream-events.graphql +++ b/graphql/stream-events.graphql @@ -1,29 +1,42 @@ -subscription { busEvents(batchSize: 0, types: [Order], marketID: "'$marketID'" ) { - type - event - { - ... on Order { +subscription { + busEvents(batchSize: 0, types: [Order], marketId: "'$marketID'") { + type + event { + ... on Order { + id + side + price + timeInForce + side + market { + id + } + size + remaining + party { + id + } + createdAt + expiresAt + status + reference + tradesConnection { + edges { + node { id - side - price - timeInForce - side - market { id } size - remaining - party { id } - createdAt - expiresAt - status - reference - trades { id, size, aggressor } - type - rejectionReason - version - updatedAt - } - ... on TimeUpdate { - timestamp + aggressor + } + } } + type + rejectionReason + version + updatedAt + } + ... on TimeUpdate { + timestamp + } } -}} \ No newline at end of file + } +} \ No newline at end of file diff --git a/graphql/stream-market-data.graphql b/graphql/stream-market-data.graphql index af66f13..e7bcebf 100644 --- a/graphql/stream-market-data.graphql +++ b/graphql/stream-market-data.graphql @@ -1,7 +1,7 @@ subscription StreamMarketData ( - $marketID: ID! = "9b358cb36b63001ae74b9f815c30a58f1db258fa11b17ba082a66abebed75951", + $marketID: [ID!] = "e9ec6d5c46a7e7bcabf9ba7a893fa5a5eeeec08b731f06f7a6eb7bf0e605b829", ){ - marketData(marketId:$marketID){ + marketsData(marketIds:$marketID){ bestBidPrice bestBidVolume bestOfferPrice diff --git a/graphql/stream-orders-by-reference.graphql b/graphql/stream-orders-by-reference.graphql index 55af68b..4e092dd 100644 --- a/graphql/stream-orders-by-reference.graphql +++ b/graphql/stream-orders-by-reference.graphql @@ -1,14 +1,12 @@ subscription StreamOrdersByReference( - $partyId:ID!="ed20dab0d670b22a6bfb9d0eb21580289ac67ae5e10ebbca1b6dface9dfa6b22" + $partyId:ID!="644a1a8bb2fba612612dd6a5d400c49eb469d91dff777b0eda3f4cd554296759" ){ orders(partyId:$partyId){ id price timeInForce side - market{ - name - } + marketId size } } \ No newline at end of file diff --git a/graphql/stream-orders.graphql b/graphql/stream-orders.graphql index 8adc0bd..78141b6 100644 --- a/graphql/stream-orders.graphql +++ b/graphql/stream-orders.graphql @@ -4,10 +4,7 @@ subscription StreamOrders{ price timeInForce side - market{ - name - } + marketId size } -} } \ No newline at end of file diff --git a/graphql/stream-trades.graphql b/graphql/stream-trades.graphql index 661b6fa..4c59d1e 100644 --- a/graphql/stream-trades.graphql +++ b/graphql/stream-trades.graphql @@ -1,9 +1,7 @@ -subscription StreamTrades{ - trades{ +subscription StreamTrades { + trades { id - market{ - name - } + marketId buyOrder sellOrder } From 221af2220d20ea1ee15ad52a602ce0a2e7391354 Mon Sep 17 00:00:00 2001 From: cdm Date: Mon, 21 Nov 2022 17:17:50 +0000 Subject: [PATCH 09/33] Added configs and readme updates --- README.md | 155 +++++++++++++++--------------------------- requirements.txt | 3 - rest/README.md | 34 +++++++++ rest/get-accounts.py | 1 - rest/requirements.txt | 1 - setenv.bat | 3 + setup.bat | 3 - vega-config | 5 ++ vega-config-stagnet1 | 2 + vega-config-stagnet3 | 2 + vega-config-win | 14 ++++ 11 files changed, 116 insertions(+), 107 deletions(-) delete mode 100644 requirements.txt create mode 100644 setenv.bat delete mode 100644 setup.bat create mode 100644 vega-config-win diff --git a/README.md b/README.md index a4b25bc..c68eb61 100644 --- a/README.md +++ b/README.md @@ -1,38 +1,50 @@ -[![Gitpod ready-to-code](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/vegaprotocol/sample-api-scripts) -# Sample API scripts +# Sample API Scripts -This repo contains sample scripts in various languages. These scripts use the -Vega core and wallet APIs to interact with Vega core nodes and wallet servers. +This repo contains Vega code examples in Python. These scripts use the Vega data-node and wallet APIs to interact with a Vega network. -# Gitpod +With Vega users can consume APIs on the network using three different options (navigate through to your desired set of scripts): + + * **[REST](./rest)** + * **[GraphQL](./graphql)** + * gRPC - *coming soon!* + +The purpose of these samples is to give simple and clear code that can be used to illustrate how to do something via Vega's APIs. -Get started with the sample API scripts with zero configuration. Click on the -"Gitpod ready-to-code" button above. +For example; show me a list of trades on a particular market, stream my latest orders or submit a new liquidity commitment, etc. -# Getting started for Unix based systems (Mac OS & Linux) -1. Clone this repo onto your local machine so you have access to all the files and can change them as you need. +If these scripts do not provide what you're looking for there are even more tutorials, code and further examples on how to integrate with Vega (including API reference docs) at **https://docs.vega.xyz** + +## Gitpod + +This repo has been designed to be quick for a user to get started with. If you do not want to clone the code locally, you can use [Gitpod](https://gitpod.io/) to get started with zero configuration in your browser. + +[![Gitpod ready-to-code](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/vegaprotocol/sample-api-scripts) + +Click on the "Gitpod ready-to-code" button above to load a browser based linux development environment and start experimenting straight away. + +## Getting started for Unix based systems (Gitpod, Mac OS & Linux) + +1. Load up a Gitpod environment (above) OR Clone this repo onto your local machine so you have access to all the files and can change them as you need. ```bash git clone https://github.com/vegaprotocol/sample-api-scripts.git ``` - This should create you a folder named `sample-api-scripts` that you will use for the rest of this README. -1. Copy or rename the `credentials-template` file as `credentials`. + This should create you a folder named `sample-api-scripts` that you will use for the rest of this README. *Note: When running on Gitpod this is already done for you.* - ```bash - cp credentials-template credentials - ``` -1. Edit the `credentials` file. (`nano` and `vim` are installed, or use the built-in Gitpod text editor.) - ```bash - nano credentials - (press Ctrl-O, Enter, Ctrl-X to save and exit) - ``` -1. The URL values will already be set up correctly for testnet including using the testnet hosted wallet. You will need to update your wallet credentials, near the top of the file. If you are going to use the scripts on mainnet, the URL details can be found in your wallet connections file of your local wallet server or in the Vega Wallet desktop app. If you are uncomfortable placing your wallet password into the credentials file, you can directly set the value using the export command: - ```bash - export WALLET_PASSPHRASE="" - ``` - -1. Import the credentials into your local environment: `source credentials` - + +1. Import the appropriate `vega-config` into your local environment for the network you want to test against (default is Fairground testnet). + ``` + source vega-config + ``` + Pre-defined configs are available for testnet (vega-config *hosted wallet*), stagnet1 (vega-config-stagnet1 *local wallet*) and stagnet3 (vega-config-stagnet3 *local wallet*). You can define, copy or edit your own configurations. Out of the box, the vega-config file is included for ease and defaults to the Fairground testnet with hosted wallet configuration. *Node: Don't forget to source your configs after making any changes.* + +1. Navigate to the API transport you would like to explore, for example: + ``` + cd ./rest + ``` + +1. Follow the sub-folder README.md information on how to run the samples. + # Getting started for Windows 1. Clone this repo onto your local machine so you have access to all the files and can change them as you need. @@ -40,80 +52,25 @@ Get started with the sample API scripts with zero configuration. Click on the git clone git@github.com:vegaprotocol/sample-api-scripts.git ``` This should create you a folder named `sample-api-scripts` that you will use for the rest of this README. -1. Copy or rename the `credentials-win-template` file as `credentials-win`. - ```bash - copy credentials-win-template credentials-win - ``` -1. Edit the `credentials-win` file. - ```bash - notepad credentials-win - ``` -1. The URL values will already be set up correctly for testnet including using the testnet hosted wallet. You will need to update your wallet credentials, near the top of the file. If you are going to use the scripts on mainnet, the URL details can be found in your wallet connections file of your local wallet server or in the Vega Wallet desktop app. If you are uncomfortable placing your wallet password into the credentials file, you can directly set the value using the export command: - ```bash - set WALLET_PASSPHRASE="" - ``` -1. Run the setup batch script to import the credentials into your local environment: `setup.bat` - - -# Prerequisites - -The following tools or applications are required for these scripts to work. Here are the commands to check they are installed on your system: - -1. python3 - ```bash - python3 --version - ``` -1. pip3 - ```bash - pip3 --version - ``` - To make sure we have all the correct libraries you can use pip with the requirements.txt to install them all - ```bash - pip3 install -r requirements.txt - ``` -1. gq (https://github.com/hasura/graphqurl) - ```bash - gq --version - ``` +1. Import the appropriate `vega-config-win` into your local environment for the network you want to test against (default is Fairground testnet). + ``` + source vega-config-win + ``` + You can define, copy or edit your own configurations. Out of the box, the vega-config-win file is included for ease and defaults to the Fairground testnet with hosted wallet configuration. *Node: Don't forget to source your configs after making any changes.* + +1. Run the setup batch script on your command prompt/terminal to import the vega-config into your local environment: + ``` + setenv.bat + ``` + +1. Navigate to the API transport you would like to explore, for example: + ``` + cd ./rest + ``` + +1. Follow the sub-folder README.md information on how to run the samples. -To make sure you have all the tools required and have setup your environment correctly, it is best to try out the most basic `vega-time` script. - -```bash -python3 vega-time/get-time.py -``` - -If this correctly gets the time then you have everything you need to use the other scripts. If the script fails to run, check out the trouble shooting guide at the bottom of this page. - - -And you're good to go. Now choose a sample program to run from the following (see the link in the **Folder** column to learn how to run each sample script): - -# Sample scripts - -| Script description | Languages | API transport | Folder & README | -| :----------------- | :------- | :------------------------------ | :---------- | -| Get Asset | python3 | Vega node [GraphQL, REST, gRPC] | / [get-assets](get-assets) | -| Orders by reference | bash, python3 | Vega node [GraphQL, REST, gRPC] | / [get-by-reference](get-by-reference) | -| List market details and market data | bash, python3 | Vega node [GraphQL, REST, gRPC] | / [get-markets-and-market-data](get-markets-and-market-data) | -| List Vega network parameters | bash, python3 | Vega node [GraphQL, REST, gRPC] | / [get-network-parameters](get-network-parameters) | -| List orders and trades | bash, python3 | Vega node [GraphQL, REST, gRPC] | / [get-orders-and-trades](get-orders-and-trades) | -| Vega statistics | bash, python3 | Vega node [GraphQL, REST, gRPC] | / [get-statistics](get-statistics) | -| List parties and accounts | bash, python3 | Vega node [REST, gRPC] | / [parties-and-accounts](parties-and-accounts) | -| Stream market data | python3 | Vega node [GraphQL] | / [stream-marketdata](stream-marketdata) | -| Stream orders and trades | python3 | Vega node [GraphQL] | / [stream-orders-and-trades](stream-orders-and-trades) | -| Interact with Vega wallet API | bash, python3 | Vega wallet [REST] | / [wallet](wallet) | -| Submit, amend and cancel orders | bash, python3 | Vega wallet [REST], Vega node [REST, gRPC] | / [submit-amend-cancel-orders](submit-amend-cancel-orders) | -| Submit and amend pegged orders | bash, python3 | Vega wallet [REST], Vega node [REST, gRPC] | / [submit-amend-pegged-order](submit-amend-pegged-order) | -| Vega/blockchain time | bash, python3 | Vega node [GraphQL, REST, gRPC] | / [vega-time](vega-time) | -| Streaming events | bash, python3 | Vega node [GraphQL, REST, gRPC] | / [stream-events](stream-events) | -| Fees and margins estimation | bash, python3 | Vega node [REST, gRPC] | / [fees-margins-estimation](fees-margins-estimation) | -| Propose, vote and enact new markets | python3 | Vega node [REST] | / [propose-markets](propose-markets) | -| Propose, vote and enact network parameters update | python3 | Vega node [REST] | / [propose-netparams](propose-netparams) | -| Propose, vote and enact new freeform proposal | python3 | Vega node [REST] | / [propose-freeform](propose-freeform) | -| List proposals | bash, python3 | Vega node [GraphQL, gRPC] | / [propose-votes](propose-votes) | -| Submit create liquidity provision | bash, python3 | Data node [GraphQL, gRPC] | / [submit-create-liquidity-provision](submit-create-liquidity-provision) | -| Submit amend liquidity provision | bash, python3 | Data node [GraphQL, gRPC] | / [submit-amend-liquidity-provision](submit-amend-liquidity-provision) | -| Submit cancel liquidity provision | bash, python3 | Data node [GraphQL, gRPC] | / [submit-cancel-liquidity-provision](submit-cancel-liquidity-provision) | # Troubleshooting @@ -121,6 +78,6 @@ Python/terminal: If you get `No module named 'helpers'...`, you should enter `so # Contributing or raising issues -Please reach out to us on the [community forums](https://community.vega.xyz/c/testnet/) or [Discord chat](https://discord.gg/bkAF3Tu) to enquire further about how to get involved with Vega. +Please reach out to us on the [Discord chat](https://discord.gg/bkAF3Tu) to enquire further about how to get involved with Vega. If you have found an issue or would like to suggest an improvement with our public code samples, please raise an issue in the [Sample-API-Scripts](https://github.com/vegaprotocol/sample-api-scripts/) repository. If you'd like to submit a PR we welcome additional sample code. diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index f81a2e8..0000000 --- a/requirements.txt +++ /dev/null @@ -1,3 +0,0 @@ -requests==2.27.1 -Vega-API-client==0.49.2 -websocket-client==1.3.2 diff --git a/rest/README.md b/rest/README.md index e69de29..5e685c4 100644 --- a/rest/README.md +++ b/rest/README.md @@ -0,0 +1,34 @@ +# REST API samples in Python + +The files here represent how to call various aspects of the Vega data-node REST APIs and Wallet APIs programmatically using Python. + +**REFERENCE APIs:** Reference API documentation for the REST APIs can be found at: https://docs.vega.xyz/ + + +## Prerequisites + +*Ensure you have set up `vega-config` on your environment as explained in the main [Getting Started](../) guides.* + +The following tools or applications are required for these scripts to work. Here are the commands to check they are installed on your system: + +1. python3 + ```bash + python3 --version + ``` +1. pip3 + ```bash + pip3 --version + ``` + To make sure we have all the correct libraries you can use pip with the requirements.txt to install them all + ```bash + pip3 install -r requirements.txt + ``` + +To make sure you have all the tools required and have setup your environment correctly, it is best to try out the most basic `vega-time` script. + +```bash +python3 get-vega-time.py +``` + +If this correctly gets the Vega blockchain time then you have everything you need to use the other scripts. If the script fails to run, check out the trouble shooting guide at the bottom of this page. + diff --git a/rest/get-accounts.py b/rest/get-accounts.py index af5122f..3a482b4 100644 --- a/rest/get-accounts.py +++ b/rest/get-accounts.py @@ -34,7 +34,6 @@ market_id = helpers.env_market_id() assert market_id != "" -print(f"Market found: {market_id}") # __get_accounts_by_market: # Request a list of accounts for a single market (repeat the filter for multiple markets) diff --git a/rest/requirements.txt b/rest/requirements.txt index f81a2e8..ee911e0 100644 --- a/rest/requirements.txt +++ b/rest/requirements.txt @@ -1,3 +1,2 @@ requests==2.27.1 -Vega-API-client==0.49.2 websocket-client==1.3.2 diff --git a/setenv.bat b/setenv.bat new file mode 100644 index 0000000..439af6f --- /dev/null +++ b/setenv.bat @@ -0,0 +1,3 @@ +FOR /F %%A in (vega-config-windows) DO ( + SET %%A) +PAUSE \ No newline at end of file diff --git a/setup.bat b/setup.bat deleted file mode 100644 index 869302d..0000000 --- a/setup.bat +++ /dev/null @@ -1,3 +0,0 @@ -FOR /F %%A in (credentials-win) DO ( - SET %%A) -PAUSE \ No newline at end of file diff --git a/vega-config b/vega-config index beec1ad..e1bec8f 100644 --- a/vega-config +++ b/vega-config @@ -2,6 +2,9 @@ # Default server configuration used by REST/GRPC/GRAPHQL examples +# See other vega-config-XXXX scripts for other examples of network configurations or +# update the URLs below to your desired network and wallet setup: + DATA_NODE_URL_REST="https://api.n06.testnet.vega.xyz/api/v2" DATA_NODE_URL_GRAPHQL="https://api.n07.testnet.vega.xyz/graphql" DATA_NODE_URL_GRPC="n07.testnet.vega.xyz:3007" @@ -10,6 +13,8 @@ MARKET_ID="" PARTY_ID="" ASSET_ID="" +# Do not edit below this line + export DATA_NODE_URL_GRPC export DATA_NODE_URL_REST export DATA_NODE_URL_GRAPHQL diff --git a/vega-config-stagnet1 b/vega-config-stagnet1 index 31b6de6..130faf1 100644 --- a/vega-config-stagnet1 +++ b/vega-config-stagnet1 @@ -10,6 +10,8 @@ MARKET_ID="" PARTY_ID="" ASSET_ID="" +# Do not edit below this line + export DATA_NODE_URL_GRPC export DATA_NODE_URL_REST export DATA_NODE_URL_GRAPHQL diff --git a/vega-config-stagnet3 b/vega-config-stagnet3 index d266dba..aad45a5 100644 --- a/vega-config-stagnet3 +++ b/vega-config-stagnet3 @@ -10,6 +10,8 @@ MARKET_ID="" PARTY_ID="" ASSET_ID="" +# Do not edit below this line + export DATA_NODE_URL_GRPC export DATA_NODE_URL_REST export DATA_NODE_URL_GRAPHQL diff --git a/vega-config-win b/vega-config-win new file mode 100644 index 0000000..4028794 --- /dev/null +++ b/vega-config-win @@ -0,0 +1,14 @@ +REM Default server configuration used by REST/GRPC/GRAPHQL examples on WINDOWS + +REM See other vega-config-XXXX scripts for other examples of network configurations or +REM update the URLs below to your desired network and wallet setup: + +DATA_NODE_URL_REST=https://api.n06.testnet.vega.xyz/api/v2 +DATA_NODE_URL_GRAPHQL=https://api.n07.testnet.vega.xyz/graphql +DATA_NODE_URL_GRPC=n07.testnet.vega.xyz:3007 +WALLET_SERVER_URL=https://wallet.testnet.vega.xyz +MARKET_ID= +PARTY_ID= +ASSET_ID= + +echo vega-config has been configured From 370577f42e12ad4dc2cb059552eba10ad98cb22d Mon Sep 17 00:00:00 2001 From: Sunny Dasgupta Date: Mon, 21 Nov 2022 17:32:35 +0000 Subject: [PATCH 10/33] accounts, balances and governance votes --- graphql/get-accounts.graphql | 24 ++++++++++++++++++++++++ graphql/get-balances.graphql | 22 ++++++++++++++++++++++ graphql/get-governance-votes.graphql | 20 ++++++++++++++++++++ 3 files changed, 66 insertions(+) create mode 100644 graphql/get-accounts.graphql create mode 100644 graphql/get-balances.graphql create mode 100644 graphql/get-governance-votes.graphql diff --git a/graphql/get-accounts.graphql b/graphql/get-accounts.graphql new file mode 100644 index 0000000..ccdaaf0 --- /dev/null +++ b/graphql/get-accounts.graphql @@ -0,0 +1,24 @@ +{ + partiesConnection { + edges { + node { + id + accountsConnection { + edges { + node { + balance + asset { + id + } + type + market { + id + } + + } + } + } + } + } + } +} \ No newline at end of file diff --git a/graphql/get-balances.graphql b/graphql/get-balances.graphql new file mode 100644 index 0000000..13db910 --- /dev/null +++ b/graphql/get-balances.graphql @@ -0,0 +1,22 @@ +{ + partiesConnection { + edges { + node { + id + accountsConnection { + edges { + node { + asset { + id + symbol + decimals + } + balance + type + } + } + } + } + } + } +} \ No newline at end of file diff --git a/graphql/get-governance-votes.graphql b/graphql/get-governance-votes.graphql new file mode 100644 index 0000000..13da143 --- /dev/null +++ b/graphql/get-governance-votes.graphql @@ -0,0 +1,20 @@ + { + partiesConnection (id: "644a1a8bb2fba612612dd6a5d400c49eb469d91dff777b0eda3f4cd554296759") { + edges { + node { + id + votesConnection { + edges { + node { + proposalId + vote { + value + datetime + } + } + } + } + } + } + } +} \ No newline at end of file From 4153e5acb3626d4193d5e9cc04aac57745695d77 Mon Sep 17 00:00:00 2001 From: Sunny Dasgupta Date: Mon, 21 Nov 2022 17:44:01 +0000 Subject: [PATCH 11/33] Comments and new structure added --- graphql/get-accounts.graphql | 3 +++ 1 file changed, 3 insertions(+) diff --git a/graphql/get-accounts.graphql b/graphql/get-accounts.graphql index ccdaaf0..a82cb89 100644 --- a/graphql/get-accounts.graphql +++ b/graphql/get-accounts.graphql @@ -1,3 +1,6 @@ +############################################################################### +# A L L A C C O U N T S # +############################################################################### { partiesConnection { edges { From 920c9e91fc9e5f3bfd34d02594b38f7cd40307c0 Mon Sep 17 00:00:00 2001 From: Sunny Dasgupta Date: Tue, 22 Nov 2022 11:38:15 +0000 Subject: [PATCH 12/33] get assets --- graphql/get-asset.graphql | 14 -------------- graphql/get-assets.graphql | 23 +++++++++++++++++++++++ 2 files changed, 23 insertions(+), 14 deletions(-) delete mode 100644 graphql/get-asset.graphql diff --git a/graphql/get-asset.graphql b/graphql/get-asset.graphql deleted file mode 100644 index e7a074f..0000000 --- a/graphql/get-asset.graphql +++ /dev/null @@ -1,14 +0,0 @@ -query getAsset { - assetsConnection (id: "b340c130096819428a62e5df407fd6abe66e444b89ad64f670beb98621c9c663"){ - edges { - node { - id - name - symbol - decimals - quantum - status - } - } - } -} \ No newline at end of file diff --git a/graphql/get-assets.graphql b/graphql/get-assets.graphql index 0c8c2f7..ab8f2ff 100644 --- a/graphql/get-assets.graphql +++ b/graphql/get-assets.graphql @@ -1,3 +1,7 @@ +############################################################################### +# L I S T A L L A S S E T S # +############################################################################### + query getAssets { assetsConnection { edges { @@ -11,4 +15,23 @@ query getAssets { } } } +} + +############################################################################### +# S I N G L E A S S E T # +############################################################################### + +query getAsset { + assetsConnection (id: "b340c130096819428a62e5df407fd6abe66e444b89ad64f670beb98621c9c663"){ + edges { + node { + id + name + symbol + decimals + quantum + status + } + } + } } \ No newline at end of file From 49c6508ae34168005afd0e222ae8401418b50b41 Mon Sep 17 00:00:00 2001 From: Sunny Dasgupta Date: Tue, 22 Nov 2022 11:40:13 +0000 Subject: [PATCH 13/33] get markets --- graphql/Get-Market.graphql | 30 ---------------------------- graphql/Get-Markets.graphql | 39 +++++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 30 deletions(-) delete mode 100644 graphql/Get-Market.graphql diff --git a/graphql/Get-Market.graphql b/graphql/Get-Market.graphql deleted file mode 100644 index 9eff562..0000000 --- a/graphql/Get-Market.graphql +++ /dev/null @@ -1,30 +0,0 @@ -query getMarket { - marketsConnection (id: "e9ec6d5c46a7e7bcabf9ba7a893fa5a5eeeec08b731f06f7a6eb7bf0e605b829") { - edges { - node { - id - tradingMode - marketTimestamps { - proposed - pending - open - close - } - depth { - buy { - volume - numberOfOrders - } - sell { - volume - numberOfOrders - } - lastTrade { - price - size - } - } - } - } - } -} \ No newline at end of file diff --git a/graphql/Get-Markets.graphql b/graphql/Get-Markets.graphql index 42deca9..d2df45b 100644 --- a/graphql/Get-Markets.graphql +++ b/graphql/Get-Markets.graphql @@ -1,3 +1,7 @@ +############################################################################### +# L I S T M A R K E T S # +############################################################################### + query getMarkets { marketsConnection { edges { @@ -27,4 +31,39 @@ query getMarkets { } } } +} + +############################################################################### +# M A R K E T B Y I D # +############################################################################### + +query getMarket { + marketsConnection (id: "e9ec6d5c46a7e7bcabf9ba7a893fa5a5eeeec08b731f06f7a6eb7bf0e605b829") { + edges { + node { + id + tradingMode + marketTimestamps { + proposed + pending + open + close + } + depth { + buy { + volume + numberOfOrders + } + sell { + volume + numberOfOrders + } + lastTrade { + price + size + } + } + } + } + } } \ No newline at end of file From 9495de10743c8d9bead06296ac0b787d02bf7735 Mon Sep 17 00:00:00 2001 From: Sunny Dasgupta Date: Tue, 22 Nov 2022 15:39:19 +0000 Subject: [PATCH 14/33] Everything up to markets --- graphql/get-accounts.graphql | 57 +++++++++++++++++++++++- graphql/get-balances.graphql | 65 ++++++++++++++++++++++++++++ graphql/get-governance-votes.graphql | 4 ++ 3 files changed, 125 insertions(+), 1 deletion(-) diff --git a/graphql/get-accounts.graphql b/graphql/get-accounts.graphql index a82cb89..2724d5c 100644 --- a/graphql/get-accounts.graphql +++ b/graphql/get-accounts.graphql @@ -24,4 +24,59 @@ } } } -} \ No newline at end of file +} + +############################################################################### +# A C C O U N T S B Y P A R T Y # +############################################################################### +{ + partiesConnection (id: "644a1a8bb2fba612612dd6a5d400c49eb469d91dff777b0eda3f4cd554296759") { + edges { + node { + id + accountsConnection { + edges { + node { + balance + asset { + id + } + type + market { + id + } + + } + } + } + } + } + } +} + + + + +############################################################################### +# A C C O U N T S B Y M A R K E T # +############################################################################### + +{ + marketsConnection (id: "e9ec6d5c46a7e7bcabf9ba7a893fa5a5eeeec08b731f06f7a6eb7bf0e605b829") { + edges { + node { + accountsConnection { + edges { + node { + balance + asset { + id + } + type + } + } + } + } + } + } +} diff --git a/graphql/get-balances.graphql b/graphql/get-balances.graphql index 13db910..6802f3c 100644 --- a/graphql/get-balances.graphql +++ b/graphql/get-balances.graphql @@ -1,3 +1,8 @@ +############################################################################### +# L I S T A L L B A L A N C E S # +############################################################################### + + { partiesConnection { edges { @@ -19,4 +24,64 @@ } } } +} + + +############################################################################### +# B A L A N C E S B Y A S S E T # +############################################################################### + +query ($assetId: ID) { + partiesConnection { + edges { + node { + id + accountsConnection(assetId: $assetId) { + edges { + node { + asset { + id + symbol + decimals + } + balance + type + } + } + } + } + } + } + } + + + + +############################################################################### +# B A L A N C E S B Y P A R T Y # +############################################################################### + +{ + partiesConnection( + id: "644a1a8bb2fba612612dd6a5d400c49eb469d91dff777b0eda3f4cd554296759" + ) { + edges { + node { + id + accountsConnection { + edges { + node { + asset { + id + symbol + decimals + } + balance + type + } + } + } + } + } + } } \ No newline at end of file diff --git a/graphql/get-governance-votes.graphql b/graphql/get-governance-votes.graphql index 13da143..5d730fb 100644 --- a/graphql/get-governance-votes.graphql +++ b/graphql/get-governance-votes.graphql @@ -1,3 +1,7 @@ + ############################################################################### +# L I S T V O T E S # +############################################################################### + { partiesConnection (id: "644a1a8bb2fba612612dd6a5d400c49eb469d91dff777b0eda3f4cd554296759") { edges { From 1f9fb62977f5f39895a2d0f855c1e53f5e40fc70 Mon Sep 17 00:00:00 2001 From: cdm Date: Tue, 22 Nov 2022 15:45:08 +0000 Subject: [PATCH 15/33] Update README.md --- README.md | 17 ++++++----------- rest/README.md | 43 ++++++++++++++++++++++++++++++++++++++++--- vega-config-stagnet1 | 22 ---------------------- vega-config-stagnet3 | 22 ---------------------- 4 files changed, 46 insertions(+), 58 deletions(-) delete mode 100644 vega-config-stagnet1 delete mode 100644 vega-config-stagnet3 diff --git a/README.md b/README.md index c68eb61..7b7d79e 100644 --- a/README.md +++ b/README.md @@ -5,13 +5,13 @@ This repo contains Vega code examples in Python. These scripts use the Vega data With Vega users can consume APIs on the network using three different options (navigate through to your desired set of scripts): - * **[REST](./rest)** - * **[GraphQL](./graphql)** + * **[REST](./rest#readme)** + * **[GraphQL](./graphql#readme)** * gRPC - *coming soon!* The purpose of these samples is to give simple and clear code that can be used to illustrate how to do something via Vega's APIs. -For example; show me a list of trades on a particular market, stream my latest orders or submit a new liquidity commitment, etc. +For example, show me a list of trades on a particular market, stream my latest orders or submit a new liquidity commitment, etc. If these scripts do not provide what you're looking for there are even more tutorials, code and further examples on how to integrate with Vega (including API reference docs) at **https://docs.vega.xyz** @@ -32,11 +32,11 @@ Click on the "Gitpod ready-to-code" button above to load a browser based linux d This should create you a folder named `sample-api-scripts` that you will use for the rest of this README. *Note: When running on Gitpod this is already done for you.* -1. Import the appropriate `vega-config` into your local environment for the network you want to test against (default is Fairground testnet). +1. Import the appropriate `vega-config` into your local environment for the network you want to test against (default vega-config is Fairground testnet). ``` source vega-config ``` - Pre-defined configs are available for testnet (vega-config *hosted wallet*), stagnet1 (vega-config-stagnet1 *local wallet*) and stagnet3 (vega-config-stagnet3 *local wallet*). You can define, copy or edit your own configurations. Out of the box, the vega-config file is included for ease and defaults to the Fairground testnet with hosted wallet configuration. *Node: Don't forget to source your configs after making any changes.* + You can define, copy or edit your own configurations. Out of the box, the vega-config file is included for ease and defaults to the Fairground testnet with hosted wallet configuration. *Node: Don't forget to source your configs after making any changes.* 1. Navigate to the API transport you would like to explore, for example: ``` @@ -66,16 +66,11 @@ Click on the "Gitpod ready-to-code" button above to load a browser based linux d 1. Navigate to the API transport you would like to explore, for example: ``` - cd ./rest + cd rest ``` 1. Follow the sub-folder README.md information on how to run the samples. - -# Troubleshooting - -Python/terminal: If you get `No module named 'helpers'...`, you should enter `source credentials` and check with `echo "$PYTHONPATH"` than it shows `"."`. - # Contributing or raising issues Please reach out to us on the [Discord chat](https://discord.gg/bkAF3Tu) to enquire further about how to get involved with Vega. diff --git a/rest/README.md b/rest/README.md index 5e685c4..3854d30 100644 --- a/rest/README.md +++ b/rest/README.md @@ -23,12 +23,49 @@ The following tools or applications are required for these scripts to work. Here ```bash pip3 install -r requirements.txt ``` + + To make sure you have all the tools required and have setup your environment correctly, it is best to try out the most basic `vega-time` script. + + ```bash + python3 get-vega-time.py + ``` + +1. wallet + + If this correctly gets the Vega blockchain time then next we need to authenticate with the Vega wallet API so that the scripts can sign transactions. + + ```bash + python3 login.py + ``` + + Run the login script, enter your wallet username and passphrase to authenticate and store a token for use in scripts such as submit-amend-cancel-order.py + + To logout or remove the token, simply run the logout script or delete `token.temp` + + ```bash + python3 logout.py + ``` + +## How to run a script + +All the source files are named logically so that the caller can read the file tree and understand the actions performed within. +Hint: If you do not require all of the actions within a script, simply comment them out. + +If the prerequisites are installed and set up correctly you can run a simple query or 'read' action script as follows: + +```bash +python3 get-statistics.py +``` -To make sure you have all the tools required and have setup your environment correctly, it is best to try out the most basic `vega-time` script. +To run a 'write' action, sending a command into Vega, make sure you are authenticated first and have edited the file to your requirements: ```bash -python3 get-vega-time.py +python3 submit-amend-cancel-order.py ``` -If this correctly gets the Vega blockchain time then you have everything you need to use the other scripts. If the script fails to run, check out the trouble shooting guide at the bottom of this page. +Finally to run a streaming action (the code is set to exit after 30 seconds): + +```bash +python3 stream-market-data.py +``` diff --git a/vega-config-stagnet1 b/vega-config-stagnet1 deleted file mode 100644 index 130faf1..0000000 --- a/vega-config-stagnet1 +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env bash - -# Default server configuration used by REST/GRPC/GRAPHQL examples - -DATA_NODE_URL_REST="https://api.n00.stagnet1.vega.xyz/api/v2" -DATA_NODE_URL_GRAPHQL="https://api.n00.stagnet1.vega.xyz/graphql" -DATA_NODE_URL_GRPC="n00.stagnet1.vega.xyz:3007" -WALLET_SERVER_URL="localhost:1127" -MARKET_ID="" -PARTY_ID="" -ASSET_ID="" - -# Do not edit below this line - -export DATA_NODE_URL_GRPC -export DATA_NODE_URL_REST -export DATA_NODE_URL_GRAPHQL -export WALLET_SERVER_URL - -export MARKET_ID -export PARTY_ID -export ASSET_ID diff --git a/vega-config-stagnet3 b/vega-config-stagnet3 deleted file mode 100644 index aad45a5..0000000 --- a/vega-config-stagnet3 +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env bash - -# Default server configuration used by REST/GRPC/GRAPHQL examples - -DATA_NODE_URL_REST="https://api.n01.stagnet3.vega.xyz/api/v2" -DATA_NODE_URL_GRAPHQL="https://api.n01.stagnet3.vega.xyz/graphql" -DATA_NODE_URL_GRPC="n01.stagnet3.vega.xyz:3007" -WALLET_SERVER_URL="localhost:1127" -MARKET_ID="" -PARTY_ID="" -ASSET_ID="" - -# Do not edit below this line - -export DATA_NODE_URL_GRPC -export DATA_NODE_URL_REST -export DATA_NODE_URL_GRAPHQL -export WALLET_SERVER_URL - -export MARKET_ID -export PARTY_ID -export ASSET_ID From f49f03857f0d0bb6c1f8a8d3b0a33b05e68925b9 Mon Sep 17 00:00:00 2001 From: Sunny Dasgupta Date: Tue, 22 Nov 2022 15:54:41 +0000 Subject: [PATCH 16/33] Get candles --- graphql/get-candles.graphql | 56 +++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 graphql/get-candles.graphql diff --git a/graphql/get-candles.graphql b/graphql/get-candles.graphql new file mode 100644 index 0000000..cc6d89d --- /dev/null +++ b/graphql/get-candles.graphql @@ -0,0 +1,56 @@ +############################################################################### +# G E T C A N D L E S # +############################################################################### + + +{ + marketsConnection { + edges { + node { + candlesConnection( + since: "2022-11-12T15:49:00.69896836Z" + interval: INTERVAL_I1H + ) { + edges { + node { + high + low + open + close + volume + } + } + } + } + } + } +} + + +############################################################################### +# G E T C A N D L E S F O R M A R K E T # +############################################################################### + + +{ + marketsConnection (id:"e9ec6d5c46a7e7bcabf9ba7a893fa5a5eeeec08b731f06f7a6eb7bf0e605b829") { + edges { + node { + candlesConnection( + since: "2022-11-12T15:49:00.69896836Z" + interval: INTERVAL_I1H + ) { + edges { + node { + high + low + open + close + volume + } + } + } + } + } + } +} \ No newline at end of file From 40fa98387f6c3790602b9d29cf8023a8dbd89937 Mon Sep 17 00:00:00 2001 From: Sunny Dasgupta Date: Wed, 23 Nov 2022 17:02:13 +0000 Subject: [PATCH 17/33] Get deposits --- graphql/get-checkpoints.graphql | 0 graphql/get-delegations.graphql | 70 +++++++++++++++++++++++++++++++++ graphql/get-deposits.graphql | 68 ++++++++++++++++++++++++++++++++ 3 files changed, 138 insertions(+) create mode 100644 graphql/get-checkpoints.graphql create mode 100644 graphql/get-delegations.graphql create mode 100644 graphql/get-deposits.graphql diff --git a/graphql/get-checkpoints.graphql b/graphql/get-checkpoints.graphql new file mode 100644 index 0000000..e69de29 diff --git a/graphql/get-delegations.graphql b/graphql/get-delegations.graphql new file mode 100644 index 0000000..5418f8b --- /dev/null +++ b/graphql/get-delegations.graphql @@ -0,0 +1,70 @@ + +############################################################################### +# L I S T D E L E G A T I O N S # +############################################################################### + +{ +nodesConnection { + edges { + node { + delegationsConnection { + edges { + node { + amount + party { + id + } + node { + id + } + epoch + } + } + } + } + } +} +} + +############################################################################### +# D E L E G A T I O N S B Y P A R T Y # +############################################################################### + +{ + nodesConnection { + edges { + node { + id + delegationsConnection( + partyId: "644a1a8bb2fba612612dd6a5d400c49eb469d91dff777b0eda3f4cd554296759" + ) { + edges { + node { + amount + party { + id + } + node { + id + } + epoch + } + } + } + } + } + } +} + + +############################################################################### +# D E L E G A T I O N S B Y E P O C H # +############################################################################### + + + +############################################################################### +# D E L E G A T I O N S B Y N O D E # +############################################################################### + + diff --git a/graphql/get-deposits.graphql b/graphql/get-deposits.graphql new file mode 100644 index 0000000..f0b327e --- /dev/null +++ b/graphql/get-deposits.graphql @@ -0,0 +1,68 @@ +############################################################################### +# L I S T D E P O S I T S # +############################################################################### +{ + partiesConnection { + edges { + node { + id + depositsConnection { + edges { + node { + id + amount + createdTimestamp + creditedTimestamp + status + asset { + id + symbol + source { + __typename + } + } + } + } + } + } + } + } +} + +############################################################################### +# D E P O S I T B Y I D # +############################################################################### + + + + +############################################################################### +# D E P O S I T S B Y P A R T Y # +############################################################################### + +{ + partiesConnection (id:"644a1a8bb2fba612612dd6a5d400c49eb469d91dff777b0eda3f4cd554296759") { + edges { + node { + id + depositsConnection { + edges { + node { + id + amount + createdTimestamp + creditedTimestamp + status + asset { + id + symbol + source { + __typename + } + } + } + } + } + } + } + } \ No newline at end of file From 51c5985cfa19d1871be4833bfa78f8491efe0238 Mon Sep 17 00:00:00 2001 From: Sunny Dasgupta Date: Wed, 23 Nov 2022 17:12:44 +0000 Subject: [PATCH 18/33] transfers and withdrawals --- graphql/get-transfers.graphql | 60 +++++++++++++++++++++++++++++ graphql/get-withdrawals.graphql | 67 +++++++++++++++++++++++++++++++++ 2 files changed, 127 insertions(+) create mode 100644 graphql/get-transfers.graphql create mode 100644 graphql/get-withdrawals.graphql diff --git a/graphql/get-transfers.graphql b/graphql/get-transfers.graphql new file mode 100644 index 0000000..426ea0f --- /dev/null +++ b/graphql/get-transfers.graphql @@ -0,0 +1,60 @@ +############################################################################### +# L I S T T R A N S F E R S # +############################################################################### + +{ + partiesConnection { + edges { + node { + id + transfersConnection { + edges { + node { + id + fromAccountType + toAccountType + from + amount + timestamp + asset { + id + name + } + } + } + } + } + } + } + } + +############################################################################### +# T R A N S F E R S B Y P A R T Y & D I R E C T I O N # +############################################################################### + + +{ + partiesConnection { + edges { + node { + id + transfersConnection { + edges { + node { + id + fromAccountType + toAccountType + from + amount + timestamp + asset { + id + name + } + } + } + } + } + } + } + } \ No newline at end of file diff --git a/graphql/get-withdrawals.graphql b/graphql/get-withdrawals.graphql new file mode 100644 index 0000000..51c7c63 --- /dev/null +++ b/graphql/get-withdrawals.graphql @@ -0,0 +1,67 @@ + +############################################################################### +# L I S T W I T H D R A W A L S # +############################################################################### + + + partiesConnection { + edges { + node { + id + withdrawalsConnection { + edges { + node { + amount + createdTimestamp + createdTimestamp + status + asset { + id + symbol + source { + __typename + } + } + } + } + } + } + } + } + } + +############################################################################### +# W I T H D R A W A L S B Y P A R T Y # +############################################################################### + +partiesConnection (id: "644a1a8bb2fba612612dd6a5d400c49eb469d91dff777b0eda3f4cd554296759") { + edges { + node { + id + withdrawalsConnection { + edges { + node { + amount + createdTimestamp + createdTimestamp + status + asset { + id + symbol + source { + __typename + } + } + } + } + } + } + } + } + } + + +############################################################################### +# W I T H D R A W A L B Y I D # +############################################################################### + From ae3f9c34d5ed8b062c0fa30215b124aa710692a1 Mon Sep 17 00:00:00 2001 From: Sunny Dasgupta Date: Thu, 24 Nov 2022 15:34:48 +0000 Subject: [PATCH 19/33] Get margin levels --- graphql/get-governance-proposals.graphql | 41 +++++++ graphql/get-key-rotations.graphql | 16 +++ graphql/get-ledger-entries.graphql | 20 ++++ graphql/get-liquidity-provisions.graphql | 80 +++++++++++++ graphql/get-margin-levels.graphql | 137 +++++++++++++++++++++++ 5 files changed, 294 insertions(+) create mode 100644 graphql/get-governance-proposals.graphql create mode 100644 graphql/get-key-rotations.graphql create mode 100644 graphql/get-ledger-entries.graphql create mode 100644 graphql/get-liquidity-provisions.graphql create mode 100644 graphql/get-margin-levels.graphql diff --git a/graphql/get-governance-proposals.graphql b/graphql/get-governance-proposals.graphql new file mode 100644 index 0000000..59d57c2 --- /dev/null +++ b/graphql/get-governance-proposals.graphql @@ -0,0 +1,41 @@ +############################################################################### +# L I S T P R O P O S A L S # +############################################################################### + + +{ + proposalsConnection { + edges { + node { + id + reference + party { + id + } + state + datetime + rationale { + description + } + terms { + closingDatetime + enactmentDatetime + } + votes { + yes { + totalNumber + totalWeight + totalTokens + } + no { + totalNumber + totalWeight + totalTokens + } + } + rejectionReason + errorDetails + } + } + } +} \ No newline at end of file diff --git a/graphql/get-key-rotations.graphql b/graphql/get-key-rotations.graphql new file mode 100644 index 0000000..b0f5473 --- /dev/null +++ b/graphql/get-key-rotations.graphql @@ -0,0 +1,16 @@ +############################################################################### +# G E T K E Y R O T A T I O N S # +############################################################################### + +{ + keyRotationsConnection { + edges { + node { + nodeId + oldPubKey + newPubKey + blockHeight + } + } + } +} \ No newline at end of file diff --git a/graphql/get-ledger-entries.graphql b/graphql/get-ledger-entries.graphql new file mode 100644 index 0000000..7886600 --- /dev/null +++ b/graphql/get-ledger-entries.graphql @@ -0,0 +1,20 @@ +############################################################################### +# L I S T L E D G E R E N T R I E S # +############################################################################### + +{ + ledgerEntries( + filter: {AccountToFilter: {partyIds: "644a1a8bb2fba612612dd6a5d400c49eb469d91dff777b0eda3f4cd554296759"}} + ) { + edges { + node { + vegaTime + quantity + partyId + assetId + marketId + accountType + } + } + } +} \ No newline at end of file diff --git a/graphql/get-liquidity-provisions.graphql b/graphql/get-liquidity-provisions.graphql new file mode 100644 index 0000000..0684cbf --- /dev/null +++ b/graphql/get-liquidity-provisions.graphql @@ -0,0 +1,80 @@ +############################################################################### +# L P S B Y P A R T Y # +############################################################################### + +{ + partiesConnection { + edges { + node { + liquidityProvisionsConnection { + edges { + node { + id + market { + id + } + commitmentAmount + createdAt + reference + buys { + liquidityOrder { + reference + proportion + offset + } + } + sells { + liquidityOrder { + reference + proportion + offset + } + } + } + } + } + } + } + } +} + + +############################################################################### +# L P S B Y M A R K E T # +############################################################################### + +{ + marketsConnection { + edges { + node { + liquidityProvisionsConnection { + edges { + node { + id + market { + id + } + commitmentAmount + createdAt + reference + buys { + liquidityOrder { + reference + proportion + offset + } + } + sells { + liquidityOrder { + reference + proportion + offset + } + } + } + } + } + } + } + } +} \ No newline at end of file diff --git a/graphql/get-margin-levels.graphql b/graphql/get-margin-levels.graphql new file mode 100644 index 0000000..cff719c --- /dev/null +++ b/graphql/get-margin-levels.graphql @@ -0,0 +1,137 @@ +############################################################################### +# L I S T M A R G I N L E V E L S # +############################################################################### + +{ + partiesConnection { + edges { + node { + marginsConnection { + edges { + node { + market { + id + } + asset { + id + } + party { + id + } + maintenanceLevel + searchLevel + initialLevel + collateralReleaseLevel + timestamp + } + } + } + } + } + } +} + +############################################################################### +# M A R G I N L E V E L S B Y P A R T Y # +############################################################################### + +{ + partiesConnection (id: "e3ac4e601d5492b8282f04a82043b4ea3003ea17c6f206db01a988df2512a799") { + edges { + node { + marginsConnection { + edges { + node { + market { + id + } + asset { + id + } + party { + id + } + maintenanceLevel + searchLevel + initialLevel + collateralReleaseLevel + timestamp + } + } + } + } + } + } +} + + +############################################################################### +# M A R G I N L E V E L S B Y M A R K E T # +############################################################################### + +{ + partiesConnection { + edges { + node { + marginsConnection(marketId: "ad2e531441c2e8a43e85423db399a4acc8f9a8a2376304a4c377d0da8eb31e80") { + edges { + node { + market { + id + } + asset { + id + } + party { + id + } + maintenanceLevel + searchLevel + initialLevel + collateralReleaseLevel + timestamp + } + } + } + } + } + } +} + +############################################################################### +# M A R G I N L E V E L S B Y M A R K E T & P A R T Y # +############################################################################### + + +{ + partiesConnection( + id: "1ceebc1232635235fb5d4a1d18a7fa06519a03df9fbac2a36a5ca3adc168d1d1" + ) { + edges { + node { + marginsConnection( + marketId: "ad2e531441c2e8a43e85423db399a4acc8f9a8a2376304a4c377d0da8eb31e80" + ) { + edges { + node { + market { + id + } + asset { + id + } + party { + id + } + maintenanceLevel + searchLevel + initialLevel + collateralReleaseLevel + timestamp + } + } + } + } + } + } +} \ No newline at end of file From b16ae73d4609eae94e7bebcc04d4cd721ee23687 Mon Sep 17 00:00:00 2001 From: Sunny Dasgupta Date: Thu, 24 Nov 2022 16:02:09 +0000 Subject: [PATCH 20/33] Node data --- graphql/get-market-data.graphql | 80 ++++++++++++++++++++++++++++++ graphql/get-network-limits.graphql | 30 +++++++++++ graphql/get-node-data.graphql | 12 +++++ 3 files changed, 122 insertions(+) create mode 100644 graphql/get-market-data.graphql create mode 100644 graphql/get-network-limits.graphql create mode 100644 graphql/get-node-data.graphql diff --git a/graphql/get-market-data.graphql b/graphql/get-market-data.graphql new file mode 100644 index 0000000..0f1942a --- /dev/null +++ b/graphql/get-market-data.graphql @@ -0,0 +1,80 @@ +############################################################################### +# M A R K E T D A T A H I S T O R Y # +############################################################################### + + +{ + getMarketDataHistoryConnectionByID( + id: "e9ec6d5c46a7e7bcabf9ba7a893fa5a5eeeec08b731f06f7a6eb7bf0e605b829" + ) { + edges { + node { + market { + id + } + markPrice + bestBidPrice + bestBidVolume + bestOfferPrice + bestOfferVolume + bestStaticBidPrice + bestStaticBidVolume + bestStaticOfferPrice + bestStaticOfferVolume + midPrice + staticMidPrice + timestamp + openInterest + auctionEnd + auctionStart + indicativePrice + indicativeVolume + marketTradingMode + trigger + extensionTrigger + targetStake + suppliedStake + commitments { + buys { + order { + id + price + timeInForce + side + size + remaining + party { + id + } + } + } + sells { + order { + id + price + timeInForce + side + size + remaining + party { + id + } + } + } + } + priceMonitoringBounds { + minValidPrice + maxValidPrice + } + marketValueProxy + liquidityProviderFeeShare { + party { + id + } + equityLikeShare + averageEntryValuation + } + } + } + } +} \ No newline at end of file diff --git a/graphql/get-network-limits.graphql b/graphql/get-network-limits.graphql new file mode 100644 index 0000000..85f75ed --- /dev/null +++ b/graphql/get-network-limits.graphql @@ -0,0 +1,30 @@ + +############################################################################### +# N E T W O R K D A T A # +############################################################################### + + + + + + + +############################################################################### +# N E T W O R K L I M I T S # +############################################################################### + + + +{ + networkLimits { + canProposeMarket + canProposeAsset + bootstrapFinished + proposeMarketEnabled + proposeAssetEnabled + bootstrapBlockCount + genesisLoaded + proposeMarketEnabledFrom + proposeAssetEnabledFrom + } +} \ No newline at end of file diff --git a/graphql/get-node-data.graphql b/graphql/get-node-data.graphql new file mode 100644 index 0000000..c5b98e0 --- /dev/null +++ b/graphql/get-node-data.graphql @@ -0,0 +1,12 @@ +############################################################################### +# L I S T N O D E S D A T A # +############################################################################### +{ + nodeData { + stakedTotal + totalNodes + inactiveNodes + validatingNodes + uptime + } +} \ No newline at end of file From cba8957c9a289911ba9c0d8f315329525a42f104 Mon Sep 17 00:00:00 2001 From: Sunny Dasgupta Date: Fri, 25 Nov 2022 11:47:00 +0000 Subject: [PATCH 21/33] New format pt 1 --- graphql/get-accounts-for-markets.graphql | 27 ++++++ graphql/get-accounts-for-parties.graphql | 33 ++++++++ graphql/get-accounts.graphql | 82 ------------------ graphql/get-assets.graphql | 30 ++----- graphql/get-balances.graphql | 72 ++-------------- graphql/get-candles.graphql | 40 ++------- graphql/get-delegations.graphql | 54 ++---------- graphql/get-deposits.graphql | 52 +++--------- graphql/get-governance-proposals.graphql | 12 ++- graphql/get-governance-votes.graphql | 14 +++- graphql/get-key-rotations.graphql | 9 +- graphql/get-ledger-entries.graphql | 8 +- graphql/get-withdrawals.graphql | 102 ++++++++--------------- 13 files changed, 168 insertions(+), 367 deletions(-) create mode 100644 graphql/get-accounts-for-markets.graphql create mode 100644 graphql/get-accounts-for-parties.graphql delete mode 100644 graphql/get-accounts.graphql diff --git a/graphql/get-accounts-for-markets.graphql b/graphql/get-accounts-for-markets.graphql new file mode 100644 index 0000000..fb5da31 --- /dev/null +++ b/graphql/get-accounts-for-markets.graphql @@ -0,0 +1,27 @@ +# How to get account information for a Market from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, like so: +# marketsConnection (id: "MARKET_ID") +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz +query GetAccountsByMarket { + marketsConnection { + edges { + node { + accountsConnection { + edges { + node { + balance + asset { + id + } + type + } + } + } + } + } + } +} diff --git a/graphql/get-accounts-for-parties.graphql b/graphql/get-accounts-for-parties.graphql new file mode 100644 index 0000000..4a6511f --- /dev/null +++ b/graphql/get-accounts-for-parties.graphql @@ -0,0 +1,33 @@ +# How to get account information for a Party from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, like so: +# partiesConnection (id: "PUBLIC_KEY") +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz + +query GetAccountsByParty { + partiesConnection { + edges { + node { + id + accountsConnection { + edges { + node { + balance + asset { + id + } + type + market { + id + } + + } + } + } + } + } + } +} \ No newline at end of file diff --git a/graphql/get-accounts.graphql b/graphql/get-accounts.graphql deleted file mode 100644 index 2724d5c..0000000 --- a/graphql/get-accounts.graphql +++ /dev/null @@ -1,82 +0,0 @@ -############################################################################### -# A L L A C C O U N T S # -############################################################################### -{ - partiesConnection { - edges { - node { - id - accountsConnection { - edges { - node { - balance - asset { - id - } - type - market { - id - } - - } - } - } - } - } - } -} - -############################################################################### -# A C C O U N T S B Y P A R T Y # -############################################################################### -{ - partiesConnection (id: "644a1a8bb2fba612612dd6a5d400c49eb469d91dff777b0eda3f4cd554296759") { - edges { - node { - id - accountsConnection { - edges { - node { - balance - asset { - id - } - type - market { - id - } - - } - } - } - } - } - } -} - - - - -############################################################################### -# A C C O U N T S B Y M A R K E T # -############################################################################### - -{ - marketsConnection (id: "e9ec6d5c46a7e7bcabf9ba7a893fa5a5eeeec08b731f06f7a6eb7bf0e605b829") { - edges { - node { - accountsConnection { - edges { - node { - balance - asset { - id - } - type - } - } - } - } - } - } -} diff --git a/graphql/get-assets.graphql b/graphql/get-assets.graphql index ab8f2ff..07b984a 100644 --- a/graphql/get-assets.graphql +++ b/graphql/get-assets.graphql @@ -1,6 +1,11 @@ -############################################################################### -# L I S T A L L A S S E T S # -############################################################################### +# How to get information on assets from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, like so: +# assetsConnection (id: "ASSET_ID") +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz query getAssets { assetsConnection { @@ -15,23 +20,4 @@ query getAssets { } } } -} - -############################################################################### -# S I N G L E A S S E T # -############################################################################### - -query getAsset { - assetsConnection (id: "b340c130096819428a62e5df407fd6abe66e444b89ad64f670beb98621c9c663"){ - edges { - node { - id - name - symbol - decimals - quantum - status - } - } - } } \ No newline at end of file diff --git a/graphql/get-balances.graphql b/graphql/get-balances.graphql index 6802f3c..87f0c80 100644 --- a/graphql/get-balances.graphql +++ b/graphql/get-balances.graphql @@ -1,6 +1,12 @@ -############################################################################### -# L I S T A L L B A L A N C E S # -############################################################################### +# How to get information on asset balances from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, like so: +# partiesConnection (id: "PUBLIC_KEY") +# accountsConnection (assetId: "ASSET_ID") +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz { @@ -24,64 +30,4 @@ } } } -} - - -############################################################################### -# B A L A N C E S B Y A S S E T # -############################################################################### - -query ($assetId: ID) { - partiesConnection { - edges { - node { - id - accountsConnection(assetId: $assetId) { - edges { - node { - asset { - id - symbol - decimals - } - balance - type - } - } - } - } - } - } - } - - - - -############################################################################### -# B A L A N C E S B Y P A R T Y # -############################################################################### - -{ - partiesConnection( - id: "644a1a8bb2fba612612dd6a5d400c49eb469d91dff777b0eda3f4cd554296759" - ) { - edges { - node { - id - accountsConnection { - edges { - node { - asset { - id - symbol - decimals - } - balance - type - } - } - } - } - } - } } \ No newline at end of file diff --git a/graphql/get-candles.graphql b/graphql/get-candles.graphql index cc6d89d..995c5be 100644 --- a/graphql/get-candles.graphql +++ b/graphql/get-candles.graphql @@ -1,6 +1,11 @@ -############################################################################### -# G E T C A N D L E S # -############################################################################### +# How to get information on candles from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, like so: +# marketsConnection (id: "MARKET_ID") +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz { @@ -24,33 +29,4 @@ } } } -} - - -############################################################################### -# G E T C A N D L E S F O R M A R K E T # -############################################################################### - - -{ - marketsConnection (id:"e9ec6d5c46a7e7bcabf9ba7a893fa5a5eeeec08b731f06f7a6eb7bf0e605b829") { - edges { - node { - candlesConnection( - since: "2022-11-12T15:49:00.69896836Z" - interval: INTERVAL_I1H - ) { - edges { - node { - high - low - open - close - volume - } - } - } - } - } - } } \ No newline at end of file diff --git a/graphql/get-delegations.graphql b/graphql/get-delegations.graphql index 5418f8b..ad07588 100644 --- a/graphql/get-delegations.graphql +++ b/graphql/get-delegations.graphql @@ -1,7 +1,11 @@ - -############################################################################### -# L I S T D E L E G A T I O N S # -############################################################################### +# How to get information on delegations from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, like so: +# delegationsConnection(partyId: "PUBLIC_KEY") +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz { nodesConnection { @@ -26,45 +30,3 @@ nodesConnection { } } -############################################################################### -# D E L E G A T I O N S B Y P A R T Y # -############################################################################### - -{ - nodesConnection { - edges { - node { - id - delegationsConnection( - partyId: "644a1a8bb2fba612612dd6a5d400c49eb469d91dff777b0eda3f4cd554296759" - ) { - edges { - node { - amount - party { - id - } - node { - id - } - epoch - } - } - } - } - } - } -} - - -############################################################################### -# D E L E G A T I O N S B Y E P O C H # -############################################################################### - - - -############################################################################### -# D E L E G A T I O N S B Y N O D E # -############################################################################### - - diff --git a/graphql/get-deposits.graphql b/graphql/get-deposits.graphql index f0b327e..b79be8f 100644 --- a/graphql/get-deposits.graphql +++ b/graphql/get-deposits.graphql @@ -1,6 +1,12 @@ -############################################################################### -# L I S T D E P O S I T S # -############################################################################### +# How to get deposit information for a Party from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, like so: +# partiesConnection (id: "PUBLIC_KEY") +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz + { partiesConnection { edges { @@ -27,42 +33,4 @@ } } } -} - -############################################################################### -# D E P O S I T B Y I D # -############################################################################### - - - - -############################################################################### -# D E P O S I T S B Y P A R T Y # -############################################################################### - -{ - partiesConnection (id:"644a1a8bb2fba612612dd6a5d400c49eb469d91dff777b0eda3f4cd554296759") { - edges { - node { - id - depositsConnection { - edges { - node { - id - amount - createdTimestamp - creditedTimestamp - status - asset { - id - symbol - source { - __typename - } - } - } - } - } - } - } - } \ No newline at end of file +} \ No newline at end of file diff --git a/graphql/get-governance-proposals.graphql b/graphql/get-governance-proposals.graphql index 59d57c2..2e8adff 100644 --- a/graphql/get-governance-proposals.graphql +++ b/graphql/get-governance-proposals.graphql @@ -1,7 +1,11 @@ -############################################################################### -# L I S T P R O P O S A L S # -############################################################################### - +# How to get information on governance proposals from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, like so: +# proposalsConnection (proposalType: "PROPOSAL_TYPE") +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz { proposalsConnection { diff --git a/graphql/get-governance-votes.graphql b/graphql/get-governance-votes.graphql index 5d730fb..403a02e 100644 --- a/graphql/get-governance-votes.graphql +++ b/graphql/get-governance-votes.graphql @@ -1,7 +1,13 @@ - ############################################################################### -# L I S T V O T E S # -############################################################################### - +# How to get information on governance votes from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, like so: +# partiesConnection (id: "PUBLIC_KEY") +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz + + { partiesConnection (id: "644a1a8bb2fba612612dd6a5d400c49eb469d91dff777b0eda3f4cd554296759") { edges { diff --git a/graphql/get-key-rotations.graphql b/graphql/get-key-rotations.graphql index b0f5473..c3e1d0e 100644 --- a/graphql/get-key-rotations.graphql +++ b/graphql/get-key-rotations.graphql @@ -1,6 +1,9 @@ -############################################################################### -# G E T K E Y R O T A T I O N S # -############################################################################### +# How to get information on key rotations from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz + { keyRotationsConnection { diff --git a/graphql/get-ledger-entries.graphql b/graphql/get-ledger-entries.graphql index 7886600..0d952de 100644 --- a/graphql/get-ledger-entries.graphql +++ b/graphql/get-ledger-entries.graphql @@ -1,6 +1,8 @@ -############################################################################### -# L I S T L E D G E R E N T R I E S # -############################################################################### +# How to get information on ledger entries from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz { ledgerEntries( diff --git a/graphql/get-withdrawals.graphql b/graphql/get-withdrawals.graphql index 51c7c63..0035003 100644 --- a/graphql/get-withdrawals.graphql +++ b/graphql/get-withdrawals.graphql @@ -1,67 +1,37 @@ - -############################################################################### -# L I S T W I T H D R A W A L S # -############################################################################### - - - partiesConnection { - edges { - node { - id - withdrawalsConnection { - edges { - node { - amount - createdTimestamp - createdTimestamp - status - asset { - id - symbol - source { - __typename - } - } - } - } - } - } - } - } - } - -############################################################################### -# W I T H D R A W A L S B Y P A R T Y # -############################################################################### - -partiesConnection (id: "644a1a8bb2fba612612dd6a5d400c49eb469d91dff777b0eda3f4cd554296759") { - edges { - node { - id - withdrawalsConnection { - edges { - node { - amount - createdTimestamp - createdTimestamp - status - asset { - id - symbol - source { - __typename - } - } - } - } - } - } - } - } - } - - -############################################################################### -# W I T H D R A W A L B Y I D # -############################################################################### +# How to get withdrawal information from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, like so: +# partiesConnection (id: "PUBLIC_KEY") +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz + + +query { + partiesConnection { + edges { + node { + id + withdrawalsConnection { + edges { + node { + amount + createdTimestamp + createdTimestamp + status + asset { + id + symbol + source { + __typename + } + } + } + } + } + } + } + } +} From bd6d50dd4daf24ccf71a469d2850cd417ab1f3b2 Mon Sep 17 00:00:00 2001 From: Sunny Dasgupta Date: Fri, 25 Nov 2022 11:53:17 +0000 Subject: [PATCH 22/33] New format pt 2 --- graphql/get-accounts-for-markets.graphql | 1 + .../get-liquidity-provisions-by party.graphql | 43 +++++++ ...get-liquidity-provisions-by-market.graphql | 45 +++++++ graphql/get-liquidity-provisions.graphql | 80 ------------ graphql/get-margin-levels.graphql | 117 ++---------------- graphql/get-market-data.graphql | 11 +- 6 files changed, 106 insertions(+), 191 deletions(-) create mode 100644 graphql/get-liquidity-provisions-by party.graphql create mode 100644 graphql/get-liquidity-provisions-by-market.graphql delete mode 100644 graphql/get-liquidity-provisions.graphql diff --git a/graphql/get-accounts-for-markets.graphql b/graphql/get-accounts-for-markets.graphql index fb5da31..5f26c35 100644 --- a/graphql/get-accounts-for-markets.graphql +++ b/graphql/get-accounts-for-markets.graphql @@ -6,6 +6,7 @@ # marketsConnection (id: "MARKET_ID") # ---------------------------------------------------------------------- # For full details see the GraphQL Reference API docs at https://docs.vega.xyz + query GetAccountsByMarket { marketsConnection { edges { diff --git a/graphql/get-liquidity-provisions-by party.graphql b/graphql/get-liquidity-provisions-by party.graphql new file mode 100644 index 0000000..2d6843e --- /dev/null +++ b/graphql/get-liquidity-provisions-by party.graphql @@ -0,0 +1,43 @@ +# How to get liquidity provision information for a Party from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, like so: +# partiesConnection (id: "PUBLIC_KEY") +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz +{ + partiesConnection { + edges { + node { + liquidityProvisionsConnection { + edges { + node { + id + market { + id + } + commitmentAmount + createdAt + reference + buys { + liquidityOrder { + reference + proportion + offset + } + } + sells { + liquidityOrder { + reference + proportion + offset + } + } + } + } + } + } + } + } +} \ No newline at end of file diff --git a/graphql/get-liquidity-provisions-by-market.graphql b/graphql/get-liquidity-provisions-by-market.graphql new file mode 100644 index 0000000..4920c7e --- /dev/null +++ b/graphql/get-liquidity-provisions-by-market.graphql @@ -0,0 +1,45 @@ +# How to get liqudity provision information for a Market from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, like so: +# marketsConnection (id: "MARKET_ID") +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz + + +{ + marketsConnection { + edges { + node { + liquidityProvisionsConnection { + edges { + node { + id + market { + id + } + commitmentAmount + createdAt + reference + buys { + liquidityOrder { + reference + proportion + offset + } + } + sells { + liquidityOrder { + reference + proportion + offset + } + } + } + } + } + } + } + } +} \ No newline at end of file diff --git a/graphql/get-liquidity-provisions.graphql b/graphql/get-liquidity-provisions.graphql deleted file mode 100644 index 0684cbf..0000000 --- a/graphql/get-liquidity-provisions.graphql +++ /dev/null @@ -1,80 +0,0 @@ -############################################################################### -# L P S B Y P A R T Y # -############################################################################### - -{ - partiesConnection { - edges { - node { - liquidityProvisionsConnection { - edges { - node { - id - market { - id - } - commitmentAmount - createdAt - reference - buys { - liquidityOrder { - reference - proportion - offset - } - } - sells { - liquidityOrder { - reference - proportion - offset - } - } - } - } - } - } - } - } -} - - -############################################################################### -# L P S B Y M A R K E T # -############################################################################### - -{ - marketsConnection { - edges { - node { - liquidityProvisionsConnection { - edges { - node { - id - market { - id - } - commitmentAmount - createdAt - reference - buys { - liquidityOrder { - reference - proportion - offset - } - } - sells { - liquidityOrder { - reference - proportion - offset - } - } - } - } - } - } - } - } -} \ No newline at end of file diff --git a/graphql/get-margin-levels.graphql b/graphql/get-margin-levels.graphql index cff719c..90728e6 100644 --- a/graphql/get-margin-levels.graphql +++ b/graphql/get-margin-levels.graphql @@ -1,6 +1,12 @@ -############################################################################### -# L I S T M A R G I N L E V E L S # -############################################################################### +# How to get information on margin levels from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, like so: +# partiesConnection (id: "PUBLIC_KEY") +# marketsConnection (assetId: "MARKET_ID") +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz { partiesConnection { @@ -29,109 +35,4 @@ } } } -} - -############################################################################### -# M A R G I N L E V E L S B Y P A R T Y # -############################################################################### - -{ - partiesConnection (id: "e3ac4e601d5492b8282f04a82043b4ea3003ea17c6f206db01a988df2512a799") { - edges { - node { - marginsConnection { - edges { - node { - market { - id - } - asset { - id - } - party { - id - } - maintenanceLevel - searchLevel - initialLevel - collateralReleaseLevel - timestamp - } - } - } - } - } - } -} - - -############################################################################### -# M A R G I N L E V E L S B Y M A R K E T # -############################################################################### - -{ - partiesConnection { - edges { - node { - marginsConnection(marketId: "ad2e531441c2e8a43e85423db399a4acc8f9a8a2376304a4c377d0da8eb31e80") { - edges { - node { - market { - id - } - asset { - id - } - party { - id - } - maintenanceLevel - searchLevel - initialLevel - collateralReleaseLevel - timestamp - } - } - } - } - } - } -} - -############################################################################### -# M A R G I N L E V E L S B Y M A R K E T & P A R T Y # -############################################################################### - - -{ - partiesConnection( - id: "1ceebc1232635235fb5d4a1d18a7fa06519a03df9fbac2a36a5ca3adc168d1d1" - ) { - edges { - node { - marginsConnection( - marketId: "ad2e531441c2e8a43e85423db399a4acc8f9a8a2376304a4c377d0da8eb31e80" - ) { - edges { - node { - market { - id - } - asset { - id - } - party { - id - } - maintenanceLevel - searchLevel - initialLevel - collateralReleaseLevel - timestamp - } - } - } - } - } - } } \ No newline at end of file diff --git a/graphql/get-market-data.graphql b/graphql/get-market-data.graphql index 0f1942a..be7d7e4 100644 --- a/graphql/get-market-data.graphql +++ b/graphql/get-market-data.graphql @@ -1,6 +1,11 @@ -############################################################################### -# M A R K E T D A T A H I S T O R Y # -############################################################################### +# How to get market data historyt from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# The query must contain an id argument: +# getMarketDataHistoryConnectionByID(id: "MARKET_ID") +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz { From 21ac754a56df9fafa6f0e02bc3e285bba5edd9ae Mon Sep 17 00:00:00 2001 From: Sunny Dasgupta Date: Fri, 25 Nov 2022 12:44:54 +0000 Subject: [PATCH 23/33] New format pt3 --- graphql/Get-Markets.graphql | 48 ++++--------------- ...get-liquidity-provisions-by-party.graphql} | 0 graphql/get-market-data.graphql | 2 +- graphql/get-network-limits.graphql | 21 +++----- graphql/get-network-parameters.graphql | 7 +++ graphql/get-node-data.graphql | 12 +++-- graphql/get-order-by-reference.graphql | 25 ++++++++++ graphql/get-orderbyreference.graphql | 15 ------ .../get-orders-and-trades-for-market.graphql | 11 +++++ .../get-orders-and-trades-for-party.graphql | 10 ++++ graphql/get-parties-accounts.graphql | 9 ++++ graphql/get-statistics.graphql | 7 +++ graphql/get-vega-time.graphql | 7 +++ 13 files changed, 101 insertions(+), 73 deletions(-) rename graphql/{get-liquidity-provisions-by party.graphql => get-liquidity-provisions-by-party.graphql} (100%) create mode 100644 graphql/get-order-by-reference.graphql delete mode 100644 graphql/get-orderbyreference.graphql diff --git a/graphql/Get-Markets.graphql b/graphql/Get-Markets.graphql index d2df45b..e16e781 100644 --- a/graphql/Get-Markets.graphql +++ b/graphql/Get-Markets.graphql @@ -1,6 +1,13 @@ -############################################################################### -# L I S T M A R K E T S # -############################################################################### +# How to get information on markets from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, like so: +# marketsConnection (id: "MARKET_KEY") +# accountsConnection (assetId: "ASSET_ID") +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz + query getMarkets { marketsConnection { @@ -31,39 +38,4 @@ query getMarkets { } } } -} - -############################################################################### -# M A R K E T B Y I D # -############################################################################### - -query getMarket { - marketsConnection (id: "e9ec6d5c46a7e7bcabf9ba7a893fa5a5eeeec08b731f06f7a6eb7bf0e605b829") { - edges { - node { - id - tradingMode - marketTimestamps { - proposed - pending - open - close - } - depth { - buy { - volume - numberOfOrders - } - sell { - volume - numberOfOrders - } - lastTrade { - price - size - } - } - } - } - } } \ No newline at end of file diff --git a/graphql/get-liquidity-provisions-by party.graphql b/graphql/get-liquidity-provisions-by-party.graphql similarity index 100% rename from graphql/get-liquidity-provisions-by party.graphql rename to graphql/get-liquidity-provisions-by-party.graphql diff --git a/graphql/get-market-data.graphql b/graphql/get-market-data.graphql index be7d7e4..45cbf0e 100644 --- a/graphql/get-market-data.graphql +++ b/graphql/get-market-data.graphql @@ -1,4 +1,4 @@ -# How to get market data historyt from a Data Node using GraphQL calls: +# How to get market data history from a Data Node using GraphQL calls: # ---------------------------------------------------------------------- # Cursor pagination is supported # ---------------------------------------------------------------------- diff --git a/graphql/get-network-limits.graphql b/graphql/get-network-limits.graphql index 85f75ed..67f9fa1 100644 --- a/graphql/get-network-limits.graphql +++ b/graphql/get-network-limits.graphql @@ -1,21 +1,12 @@ -############################################################################### -# N E T W O R K D A T A # -############################################################################### +# How to get information on network limits from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz - - - - - -############################################################################### -# N E T W O R K L I M I T S # -############################################################################### - - - -{ +query getNetworkLimits { networkLimits { canProposeMarket canProposeAsset diff --git a/graphql/get-network-parameters.graphql b/graphql/get-network-parameters.graphql index 13a5b49..1ff5f27 100644 --- a/graphql/get-network-parameters.graphql +++ b/graphql/get-network-parameters.graphql @@ -1,3 +1,10 @@ + +# How to get information on network parameters from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz + query getNetworkParameters { networkParametersConnection { edges { diff --git a/graphql/get-node-data.graphql b/graphql/get-node-data.graphql index c5b98e0..07f992e 100644 --- a/graphql/get-node-data.graphql +++ b/graphql/get-node-data.graphql @@ -1,7 +1,11 @@ -############################################################################### -# L I S T N O D E S D A T A # -############################################################################### -{ + +# How to get information on nodes from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz + +query getNodeData { nodeData { stakedTotal totalNodes diff --git a/graphql/get-order-by-reference.graphql b/graphql/get-order-by-reference.graphql new file mode 100644 index 0000000..29f26fb --- /dev/null +++ b/graphql/get-order-by-reference.graphql @@ -0,0 +1,25 @@ +# How to get information on an order from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# The query must contain an id argument: +# orderByID(id: "ORDER_ID") +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz + + +query GetOrderByID( + $orderID: ID! = "7e862ff63b4d70380b0b78ea5762e346ac1e711ec2516bc9994f92c7c19a3af6" +){ + orderByID(id:$orderID){ + id + price + timeInForce + side + size + market{ + id + } + updatedAt + } +} \ No newline at end of file diff --git a/graphql/get-orderbyreference.graphql b/graphql/get-orderbyreference.graphql deleted file mode 100644 index 3b6c13c..0000000 --- a/graphql/get-orderbyreference.graphql +++ /dev/null @@ -1,15 +0,0 @@ -query GetOrderByID( - $orderID: ID! = "7e862ff63b4d70380b0b78ea5762e346ac1e711ec2516bc9994f92c7c19a3af6" -){ - orderByID(id:$orderID){ - id - price - timeInForce - side - size - market{ - id - } - updatedAt - } -} \ No newline at end of file diff --git a/graphql/get-orders-and-trades-for-market.graphql b/graphql/get-orders-and-trades-for-market.graphql index f84d581..88d1109 100644 --- a/graphql/get-orders-and-trades-for-market.graphql +++ b/graphql/get-orders-and-trades-for-market.graphql @@ -1,3 +1,14 @@ +# How to get information on an orders and trades on a market from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# The query must contain an id argument on the market field: +# market(id: "MARKET_ID") +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz + + + query GetOrderTradesForMarket($marketId: ID! = "ad2e531441c2e8a43e85423db399a4acc8f9a8a2376304a4c377d0da8eb31e80") { market(id: $marketId) { id diff --git a/graphql/get-orders-and-trades-for-party.graphql b/graphql/get-orders-and-trades-for-party.graphql index e2133fd..fc0eb7c 100644 --- a/graphql/get-orders-and-trades-for-party.graphql +++ b/graphql/get-orders-and-trades-for-party.graphql @@ -1,3 +1,13 @@ +# How to get information on an orders and trades for a party from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# The query must contain an id argument on the market field: +# party(id: "PUBKEY") +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz + + query GetOrderTradesForParty($partyId: ID! = "644a1a8bb2fba612612dd6a5d400c49eb469d91dff777b0eda3f4cd554296759") { party(id: $partyId) { id diff --git a/graphql/get-parties-accounts.graphql b/graphql/get-parties-accounts.graphql index 6022d89..24f91ca 100644 --- a/graphql/get-parties-accounts.graphql +++ b/graphql/get-parties-accounts.graphql @@ -1,3 +1,12 @@ +# How to get account information for a Party from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, like so: +# partiesConnection (id: "PUBLIC_KEY") +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz + query getParties { partiesConnection { edges { diff --git a/graphql/get-statistics.graphql b/graphql/get-statistics.graphql index 1196157..8e29f9e 100644 --- a/graphql/get-statistics.graphql +++ b/graphql/get-statistics.graphql @@ -1,3 +1,10 @@ +# How to get information on key statistics from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz + + query getStatistics { statistics { chainVersion diff --git a/graphql/get-vega-time.graphql b/graphql/get-vega-time.graphql index 484ccc1..daed706 100644 --- a/graphql/get-vega-time.graphql +++ b/graphql/get-vega-time.graphql @@ -1,3 +1,10 @@ +# How to get Vega Time from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz + + query GetVegaTime { statistics { vegaTime From b33b64bfc6902c8467dac687f45640ffbd0b27e6 Mon Sep 17 00:00:00 2001 From: Sunny Dasgupta Date: Fri, 25 Nov 2022 12:58:06 +0000 Subject: [PATCH 24/33] New Format pt 4 --- graphql/get-trades-for-order.graphql | 10 ++++++ graphql/get-transfers.graphql | 41 +++++----------------- graphql/stream-events.graphql | 14 +++++++- graphql/stream-market-data.graphql | 14 ++++++-- graphql/stream-orders-by-reference.graphql | 11 ++++++ graphql/stream-orders.graphql | 7 ++++ graphql/stream-trades.graphql | 7 ++++ 7 files changed, 67 insertions(+), 37 deletions(-) diff --git a/graphql/get-trades-for-order.graphql b/graphql/get-trades-for-order.graphql index 495a229..d730e6c 100644 --- a/graphql/get-trades-for-order.graphql +++ b/graphql/get-trades-for-order.graphql @@ -1,3 +1,13 @@ +# How to get information on trades for an order from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# The query must contain an id argument: +# orderByID(id: "ORDER_ID") +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz + + query GetTradesForOrder($orderId: ID! = "7e862ff63b4d70380b0b78ea5762e346ac1e711ec2516bc9994f92c7c19a3af6") { orderByID(id: $orderId) { tradesConnection { diff --git a/graphql/get-transfers.graphql b/graphql/get-transfers.graphql index 426ea0f..6211b5d 100644 --- a/graphql/get-transfers.graphql +++ b/graphql/get-transfers.graphql @@ -1,6 +1,11 @@ -############################################################################### -# L I S T T R A N S F E R S # -############################################################################### +# How to get withdrawal information from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, like so: +# partiesConnection (id: "PUBLIC_KEY") +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz { partiesConnection { @@ -28,33 +33,3 @@ } } -############################################################################### -# T R A N S F E R S B Y P A R T Y & D I R E C T I O N # -############################################################################### - - -{ - partiesConnection { - edges { - node { - id - transfersConnection { - edges { - node { - id - fromAccountType - toAccountType - from - amount - timestamp - asset { - id - name - } - } - } - } - } - } - } - } \ No newline at end of file diff --git a/graphql/stream-events.graphql b/graphql/stream-events.graphql index 92fe82b..bc2672a 100644 --- a/graphql/stream-events.graphql +++ b/graphql/stream-events.graphql @@ -1,4 +1,16 @@ -subscription { +# How to stream events from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# There can be various arguments passed into busEvents, such as: +# batchSize +# marketId +# partyId +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz + + +subscription StreamEvents { busEvents(batchSize: 0, types: [Order], marketId: "'$marketID'") { type event { diff --git a/graphql/stream-market-data.graphql b/graphql/stream-market-data.graphql index e7bcebf..af43ed3 100644 --- a/graphql/stream-market-data.graphql +++ b/graphql/stream-market-data.graphql @@ -1,6 +1,14 @@ -subscription StreamMarketData ( - $marketID: [ID!] = "e9ec6d5c46a7e7bcabf9ba7a893fa5a5eeeec08b731f06f7a6eb7bf0e605b829", -){ +# How to stream market data from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# An array of market Ids must be passed in as an argument, as follows: +# marketsData(marketIds: "MARKET_ID") +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz + + +subscription StreamMarketData ($marketID: [ID!] = "e9ec6d5c46a7e7bcabf9ba7a893fa5a5eeeec08b731f06f7a6eb7bf0e605b829",){ marketsData(marketIds:$marketID){ bestBidPrice bestBidVolume diff --git a/graphql/stream-orders-by-reference.graphql b/graphql/stream-orders-by-reference.graphql index 4e092dd..5ed6206 100644 --- a/graphql/stream-orders-by-reference.graphql +++ b/graphql/stream-orders-by-reference.graphql @@ -1,3 +1,14 @@ +# How to stream orders from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# A party Id or market Id argument needs to passed in, like so: +# orders(partyId: "PUBKEY") +# orders(marketId: "MARKET_ID") +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz + + subscription StreamOrdersByReference( $partyId:ID!="644a1a8bb2fba612612dd6a5d400c49eb469d91dff777b0eda3f4cd554296759" ){ diff --git a/graphql/stream-orders.graphql b/graphql/stream-orders.graphql index 78141b6..364941f 100644 --- a/graphql/stream-orders.graphql +++ b/graphql/stream-orders.graphql @@ -1,3 +1,10 @@ +# How to stream orders from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz + + subscription StreamOrders{ orders{ id diff --git a/graphql/stream-trades.graphql b/graphql/stream-trades.graphql index 4c59d1e..e9d84ad 100644 --- a/graphql/stream-trades.graphql +++ b/graphql/stream-trades.graphql @@ -1,3 +1,10 @@ +# How to stream trades from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz + + subscription StreamTrades { trades { id From 05d25437737b633ce48e655263d4377956c1e5fc Mon Sep 17 00:00:00 2001 From: Sunny Dasgupta Date: Fri, 25 Nov 2022 14:50:25 +0000 Subject: [PATCH 25/33] Positions, rewards and staking data --- graphql/get-positions.graphql | 30 ++++++++++++++++++++++++++ graphql/get-rewards.graphql | 37 ++++++++++++++++++++++++++++++++ graphql/get-staking-data.graphql | 21 ++++++++++++++++++ 3 files changed, 88 insertions(+) create mode 100644 graphql/get-positions.graphql create mode 100644 graphql/get-rewards.graphql create mode 100644 graphql/get-staking-data.graphql diff --git a/graphql/get-positions.graphql b/graphql/get-positions.graphql new file mode 100644 index 0000000..8c7a8eb --- /dev/null +++ b/graphql/get-positions.graphql @@ -0,0 +1,30 @@ +# How to get account information for Positions from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, like so: +# partiesConnection (id: "PUBLIC_KEY") +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz + +query getPositions { + partiesConnection { + edges { + node { + id + positionsConnection() { + edges { + node { + market{id} + openVolume + realisedPNL + averageEntryPrice + unrealisedPNL + realisedPNL + } + } + } + } + } + } +} \ No newline at end of file diff --git a/graphql/get-rewards.graphql b/graphql/get-rewards.graphql new file mode 100644 index 0000000..48b53fc --- /dev/null +++ b/graphql/get-rewards.graphql @@ -0,0 +1,37 @@ +# How to get account information about Rewards from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, like so: +# partiesConnection (id: "PUBLIC_KEY") +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz + +query getRewards { + partiesConnection { + edges { + node { + rewardsConnection { + edges { + node { + asset { + id + } + marketId + rewardType + party { + id + } + epoch { + id + } + amount + percentageOfTotal + receivedAt + } + } + } + } + } + } +} \ No newline at end of file diff --git a/graphql/get-staking-data.graphql b/graphql/get-staking-data.graphql new file mode 100644 index 0000000..a1c3573 --- /dev/null +++ b/graphql/get-staking-data.graphql @@ -0,0 +1,21 @@ +# How to get account information about Staking from a Data Node using GraphQL calls: +# ---------------------------------------------------------------------- +# Cursor pagination is supported +# ---------------------------------------------------------------------- +# The list can be filtered by various parameters, like so: +# partiesConnection (id: "PUBLIC_KEY") +# ---------------------------------------------------------------------- +# For full details see the GraphQL Reference API docs at https://docs.vega.xyz + + +{ + partiesConnection { + edges { + node { + stakingSummary { + currentStakeAvailable + } + } + } + } +} \ No newline at end of file From bd69f85ab44df9bcb714525f8bdd42d1f96fa954 Mon Sep 17 00:00:00 2001 From: Sunny Dasgupta Date: Fri, 25 Nov 2022 14:56:05 +0000 Subject: [PATCH 26/33] Naming --- graphql/get-balances.graphql | 2 +- graphql/get-candles.graphql | 2 +- graphql/get-delegations.graphql | 2 +- graphql/get-deposits.graphql | 2 +- graphql/get-governance-proposals.graphql | 2 +- graphql/get-governance-votes.graphql | 2 +- graphql/get-key-rotations.graphql | 2 +- graphql/get-ledger-entries.graphql | 2 +- graphql/get-liquidity-provisions-by-market.graphql | 2 +- graphql/get-liquidity-provisions-by-party.graphql | 3 ++- graphql/get-margin-levels.graphql | 2 +- graphql/get-market-data.graphql | 2 +- graphql/get-staking-data.graphql | 2 +- graphql/get-transfers.graphql | 2 +- graphql/get-withdrawals.graphql | 2 +- 15 files changed, 16 insertions(+), 15 deletions(-) diff --git a/graphql/get-balances.graphql b/graphql/get-balances.graphql index 87f0c80..f0a417b 100644 --- a/graphql/get-balances.graphql +++ b/graphql/get-balances.graphql @@ -9,7 +9,7 @@ # For full details see the GraphQL Reference API docs at https://docs.vega.xyz -{ +query getBalances { partiesConnection { edges { node { diff --git a/graphql/get-candles.graphql b/graphql/get-candles.graphql index 995c5be..5cb1e54 100644 --- a/graphql/get-candles.graphql +++ b/graphql/get-candles.graphql @@ -8,7 +8,7 @@ # For full details see the GraphQL Reference API docs at https://docs.vega.xyz -{ +query getCandles { marketsConnection { edges { node { diff --git a/graphql/get-delegations.graphql b/graphql/get-delegations.graphql index ad07588..a81ec67 100644 --- a/graphql/get-delegations.graphql +++ b/graphql/get-delegations.graphql @@ -7,7 +7,7 @@ # ---------------------------------------------------------------------- # For full details see the GraphQL Reference API docs at https://docs.vega.xyz -{ +query getDelegations { nodesConnection { edges { node { diff --git a/graphql/get-deposits.graphql b/graphql/get-deposits.graphql index b79be8f..acc42a8 100644 --- a/graphql/get-deposits.graphql +++ b/graphql/get-deposits.graphql @@ -7,7 +7,7 @@ # ---------------------------------------------------------------------- # For full details see the GraphQL Reference API docs at https://docs.vega.xyz -{ +query getDeposits { partiesConnection { edges { node { diff --git a/graphql/get-governance-proposals.graphql b/graphql/get-governance-proposals.graphql index 2e8adff..56d7580 100644 --- a/graphql/get-governance-proposals.graphql +++ b/graphql/get-governance-proposals.graphql @@ -7,7 +7,7 @@ # ---------------------------------------------------------------------- # For full details see the GraphQL Reference API docs at https://docs.vega.xyz -{ +query getGovernanceProposals { proposalsConnection { edges { node { diff --git a/graphql/get-governance-votes.graphql b/graphql/get-governance-votes.graphql index 403a02e..c78cc7d 100644 --- a/graphql/get-governance-votes.graphql +++ b/graphql/get-governance-votes.graphql @@ -8,7 +8,7 @@ # For full details see the GraphQL Reference API docs at https://docs.vega.xyz - { + query getGovernanceVotes { partiesConnection (id: "644a1a8bb2fba612612dd6a5d400c49eb469d91dff777b0eda3f4cd554296759") { edges { node { diff --git a/graphql/get-key-rotations.graphql b/graphql/get-key-rotations.graphql index c3e1d0e..9eebfcf 100644 --- a/graphql/get-key-rotations.graphql +++ b/graphql/get-key-rotations.graphql @@ -5,7 +5,7 @@ # For full details see the GraphQL Reference API docs at https://docs.vega.xyz -{ +query getKeyRotations { keyRotationsConnection { edges { node { diff --git a/graphql/get-ledger-entries.graphql b/graphql/get-ledger-entries.graphql index 0d952de..d4d25e8 100644 --- a/graphql/get-ledger-entries.graphql +++ b/graphql/get-ledger-entries.graphql @@ -4,7 +4,7 @@ # ---------------------------------------------------------------------- # For full details see the GraphQL Reference API docs at https://docs.vega.xyz -{ +query getLedgerEntries { ledgerEntries( filter: {AccountToFilter: {partyIds: "644a1a8bb2fba612612dd6a5d400c49eb469d91dff777b0eda3f4cd554296759"}} ) { diff --git a/graphql/get-liquidity-provisions-by-market.graphql b/graphql/get-liquidity-provisions-by-market.graphql index 4920c7e..37ef319 100644 --- a/graphql/get-liquidity-provisions-by-market.graphql +++ b/graphql/get-liquidity-provisions-by-market.graphql @@ -8,7 +8,7 @@ # For full details see the GraphQL Reference API docs at https://docs.vega.xyz -{ +query getLPByMarket { marketsConnection { edges { node { diff --git a/graphql/get-liquidity-provisions-by-party.graphql b/graphql/get-liquidity-provisions-by-party.graphql index 2d6843e..86e6151 100644 --- a/graphql/get-liquidity-provisions-by-party.graphql +++ b/graphql/get-liquidity-provisions-by-party.graphql @@ -6,7 +6,8 @@ # partiesConnection (id: "PUBLIC_KEY") # ---------------------------------------------------------------------- # For full details see the GraphQL Reference API docs at https://docs.vega.xyz -{ + +query getLPByParty { partiesConnection { edges { node { diff --git a/graphql/get-margin-levels.graphql b/graphql/get-margin-levels.graphql index 90728e6..ccd818f 100644 --- a/graphql/get-margin-levels.graphql +++ b/graphql/get-margin-levels.graphql @@ -8,7 +8,7 @@ # ---------------------------------------------------------------------- # For full details see the GraphQL Reference API docs at https://docs.vega.xyz -{ +query getMarginLevels { partiesConnection { edges { node { diff --git a/graphql/get-market-data.graphql b/graphql/get-market-data.graphql index 45cbf0e..967359e 100644 --- a/graphql/get-market-data.graphql +++ b/graphql/get-market-data.graphql @@ -8,7 +8,7 @@ # For full details see the GraphQL Reference API docs at https://docs.vega.xyz -{ +query getMarketData { getMarketDataHistoryConnectionByID( id: "e9ec6d5c46a7e7bcabf9ba7a893fa5a5eeeec08b731f06f7a6eb7bf0e605b829" ) { diff --git a/graphql/get-staking-data.graphql b/graphql/get-staking-data.graphql index a1c3573..cf9cd7f 100644 --- a/graphql/get-staking-data.graphql +++ b/graphql/get-staking-data.graphql @@ -8,7 +8,7 @@ # For full details see the GraphQL Reference API docs at https://docs.vega.xyz -{ +query getStakingData { partiesConnection { edges { node { diff --git a/graphql/get-transfers.graphql b/graphql/get-transfers.graphql index 6211b5d..312015a 100644 --- a/graphql/get-transfers.graphql +++ b/graphql/get-transfers.graphql @@ -7,7 +7,7 @@ # ---------------------------------------------------------------------- # For full details see the GraphQL Reference API docs at https://docs.vega.xyz -{ +query getTransfers { partiesConnection { edges { node { diff --git a/graphql/get-withdrawals.graphql b/graphql/get-withdrawals.graphql index 0035003..e69960f 100644 --- a/graphql/get-withdrawals.graphql +++ b/graphql/get-withdrawals.graphql @@ -8,7 +8,7 @@ # For full details see the GraphQL Reference API docs at https://docs.vega.xyz -query { +query getWithdrawals { partiesConnection { edges { node { From 07ddcd738e884ffbae24eb78216bebc79b4de2da Mon Sep 17 00:00:00 2001 From: Sunny Dasgupta Date: Wed, 30 Nov 2022 14:22:07 +0000 Subject: [PATCH 27/33] readme for gql --- graphql/README.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/graphql/README.md b/graphql/README.md index e69de29..b7f4bd8 100644 --- a/graphql/README.md +++ b/graphql/README.md @@ -0,0 +1,18 @@ +# GraphQL Samples + +The files here represent queries you can use to call various aspects of the Vega data-node GraphQL APIs. + +**REFERENCE APIs:** Reference API documentation for the REST APIs can be found at: https://docs.vega.xyz/ + + +## How to run GraphQL queries + +1) If you would like to stay in your browser, you can copy and paste the queries in this folder into graphQL playground: + +https://api.n10.testnet.vega.xyz/graphql/ + +Once you enter the query and click the play button, graphQL playground will return the data you were looking for. + + +2) https://github.com/hasura/graphqurl is a CLI for running graphQL queries. You can use this to run these queries in your terminal. + From d4f0d15b5ca903e2cf6792a0ad3ce54e41743282 Mon Sep 17 00:00:00 2001 From: Sunny Dasgupta Date: Wed, 30 Nov 2022 14:24:24 +0000 Subject: [PATCH 28/33] Further detail --- graphql/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/graphql/README.md b/graphql/README.md index b7f4bd8..69b77ca 100644 --- a/graphql/README.md +++ b/graphql/README.md @@ -2,17 +2,17 @@ The files here represent queries you can use to call various aspects of the Vega data-node GraphQL APIs. -**REFERENCE APIs:** Reference API documentation for the REST APIs can be found at: https://docs.vega.xyz/ +**REFERENCE APIs:** Reference API documentation for the GraphQL APIs can be found at: https://docs.vega.xyz/ ## How to run GraphQL queries 1) If you would like to stay in your browser, you can copy and paste the queries in this folder into graphQL playground: -https://api.n10.testnet.vega.xyz/graphql/ + https://api.n10.testnet.vega.xyz/graphql/ Once you enter the query and click the play button, graphQL playground will return the data you were looking for. -2) https://github.com/hasura/graphqurl is a CLI for running graphQL queries. You can use this to run these queries in your terminal. +2) https://github.com/hasura/graphqurl is a CLI for running graphQL queries. You can use this to run these queries in your terminal. Follow the instructions on the graphqurl readMe to install and use this tool. From d2b80c4bd136c64fce3b778f74dd84c234f6b428 Mon Sep 17 00:00:00 2001 From: cdm Date: Wed, 30 Nov 2022 14:44:25 +0000 Subject: [PATCH 29/33] Added extra streaming examples --- README.md | 4 +- rest/get-accounts.py | 2 +- rest/get-candles.py | 1 + rest/propose-vote-enact-network-params.py | 4 +- rest/propose-vote-enact-new-market.py | 46 +++++------ rest/stream-accounts.py | 87 ++++++++++++++++++++ rest/stream-candles.py | 99 +++++++++++++++++++++++ rest/stream-delegations.py | 77 ++++++++++++++++++ rest/stream-governance.py | 75 +++++++++++++++++ rest/stream-market-data.py | 6 +- rest/stream-orders.py | 6 +- rest/stream-trades.py | 13 +-- 12 files changed, 373 insertions(+), 47 deletions(-) create mode 100644 rest/stream-accounts.py create mode 100644 rest/stream-candles.py create mode 100644 rest/stream-delegations.py create mode 100644 rest/stream-governance.py diff --git a/README.md b/README.md index 7b7d79e..3017c15 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,6 @@ Click on the "Gitpod ready-to-code" button above to load a browser based linux d # Contributing or raising issues -Please reach out to us on the [Discord chat](https://discord.gg/bkAF3Tu) to enquire further about how to get involved with Vega. +Please reach out to us on the [Discord chat](https://discord.gg/bkAF3Tu) to enquire further about how to get involved with Vega, alternatively you can check out the [Builders Club](https://vega.xyz/builders-club/). -If you have found an issue or would like to suggest an improvement with our public code samples, please raise an issue in the [Sample-API-Scripts](https://github.com/vegaprotocol/sample-api-scripts/) repository. If you'd like to submit a PR we welcome additional sample code. +If you have found an issue or would like to suggest an improvement with our public code samples, please raise an issue in the [Sample-API-Scripts](https://github.com/vegaprotocol/sample-api-scripts/) repository. If you'd like to submit a PR we welcome additional sample code. \ No newline at end of file diff --git a/rest/get-accounts.py b/rest/get-accounts.py index 3a482b4..bfc00d9 100644 --- a/rest/get-accounts.py +++ b/rest/get-accounts.py @@ -12,7 +12,7 @@ # The list can be filtered by various parameters, including: # filter.partyIds: Vega party ids (public keys) # filter.marketIds: Vega market ids -# filter.assets: Specific assets e.g. tDAI, tBTC, etc +# filter.assets: Specific asset ids e.g. if for tDAI, tBTC, etc # filter.accountTypes: Account types e.g. infrastructure, general, etc # ---------------------------------------------------------------------- # For full details see the REST Reference API docs at https://docs.vega.xyz diff --git a/rest/get-candles.py b/rest/get-candles.py index 96a8cab..740730c 100644 --- a/rest/get-candles.py +++ b/rest/get-candles.py @@ -26,6 +26,7 @@ # located in the root folder of the sample-api-scripts repository data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") market_id = helpers.env_market_id() +assert market_id != "" ############################################################################### # L I S T C A N D L E I N T E R V A L S # diff --git a/rest/propose-vote-enact-network-params.py b/rest/propose-vote-enact-network-params.py index 9e108ca..1c7f920 100644 --- a/rest/propose-vote-enact-network-params.py +++ b/rest/propose-vote-enact-network-params.py @@ -235,7 +235,7 @@ # As described on docs.vega.xyz, a network parameter change will need community # voting support to be passed and then enacted. -# __wait_for_market: +# __wait_for_param: print("Waiting for network parameter update to be completed...", end="", flush=True) while True: time.sleep(0.5) @@ -250,4 +250,4 @@ print() print(edge["node"]) break -# :wait_for_market__ +# :wait_for_param__ diff --git a/rest/propose-vote-enact-new-market.py b/rest/propose-vote-enact-new-market.py index 2dd1472..7a65262 100644 --- a/rest/propose-vote-enact-new-market.py +++ b/rest/propose-vote-enact-new-market.py @@ -80,6 +80,9 @@ print(f"Please deposit VEGA asset to public key {pubkey} and try again") exit(1) +print("Voting balance:") +print(voting_balance) + ############################################################################### # B L O C K C H A I N T I M E # ############################################################################### @@ -267,14 +270,12 @@ proposal_id = found_proposal["id"] proposal_state = found_proposal["state"] -print() +print(found_proposal) if (proposal_state == 'STATE_REJECTED') or ( proposal_state == 'STATE_DECLINED') or ( proposal_state == 'STATE_FAILED'): print(f"Your proposal has been {proposal_state}!") print("Due to: " + found_proposal["reason"]) - if (found_proposal["errorDetails"]) != '': - print("Further details: " + found_proposal["errorDetails"]) exit() else: print("Your proposal has been accepted by the network!") @@ -337,28 +338,27 @@ exit(1) ############################################################################### -# W A I T F O R M A R K E T # +# W A I T F O R M A R K E T # ############################################################################### -# Hint: When voting for a proposal on the Vega Testnet, typically a single -# YES vote from the proposer will not be enough to vote the market into -# existence. As described above in the previous stage, a market will need -# community voting support to be passed and then enacted. +# IMPORTANT: When voting for a proposal on Vega networks, typically a single +# YES vote from the proposer will not be enough to vote the proposal in. +# As described on docs.vega.xyz, a network parameter change will need community +# voting support to be passed and then enacted. # __wait_for_market: -# print("Waiting for proposal to be enacted or failed...", end="", flush=True) -# done = False -# while not done: -# time.sleep(0.5) -# print(".", end="", flush=True) -# markets = requests.get(data_node_url_rest + "/markets") -# if markets.status_code != 200: -# continue -# -# for n in markets.json()["markets"]: -# if n["id"] == proposal_id: -# print() -# print(n) -# done = True -# break +print("Waiting for new market to be enacted...", end="", flush=True) +while True: + time.sleep(0.5) + print(".", end="", flush=True) + url = f"{data_node_url_rest}/markets" + response = requests.get(url) + if response.status_code != 200: + continue + + for edge in response.json()["markets"]["edges"]: + if edge["node"]["id"] == proposal_id: + print() + print(edge["node"]) + break # :wait_for_market__ diff --git a/rest/stream-accounts.py b/rest/stream-accounts.py new file mode 100644 index 0000000..b42d3d6 --- /dev/null +++ b/rest/stream-accounts.py @@ -0,0 +1,87 @@ +#!/usr/bin/python3 + +############################################################################### +# S T R E A M A C C O U N T S # +############################################################################### + +# How to stream account information from a Data Node using Websockets: +# ---------------------------------------------------------------------- +# Pagination is not supported, but the initial snapshot may contain +# multiple pages. Date Range is not supported, this is a realtime stream. +# ---------------------------------------------------------------------- +# The stream can be filtered by various parameters, including: +# partyId: Vega party id (public key) +# marketId: Vega market id +# asset: Vega asset id +# type: Account type +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import websocket +import threading +import json +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +# Load Vega market id +market_id = helpers.env_market_id() +assert market_id != "" + +# Connect to the data node with a WSS based endpoint, this is not a HTTPS:// url +# Hint: to include/filter data from a party, asset or account types: +# e.g. ?marketId=xxx&partyId=yyy&asset=zzz&type=ccc +url = f"{data_node_url_rest}/stream/accounts?marketId={market_id}".replace("https://", "wss://") +res = [] +event = threading.Event() + +# __stream_accounts_by_market: +# Request a stream of accounts and updates for a market id on a Vega network + +def on_message(wsa, line): + # Vega data-node v2 returns the json line by line so we need to wait + # for a full structure before we can parse to valid JSON in python + if line == "{": + del res[:] + res.append(line) + elif line == "}": + res.append(line) + obj = json.loads(''.join(res)) + if "snapshot" in obj["result"]: + # An 'initial image' snapshot containing current accounts state (may be multiple pages) + print("Snapshot found:") + print(obj["result"]["snapshot"]["accounts"]) + if "updates" in obj["result"]: + # A list of account updates typically from the last block + print("Updates found:") + print(obj["result"]["updates"]["accounts"]) + else: + res.append(line) + +def on_error(wsa, error): + print(error) + + +def on_close(wsa, close_status_code, close_msg): + print(f"Accounts stream closed: {url}") + + +def on_open(wsa): + print(f"Accounts stream open: {url}") + + +def timeout(): + while not event.wait(timeout=30): + ws.close() + exit(1) + + +thread = threading.Thread(target=timeout) +thread.start() + +ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) +ws.on_open = on_open +ws.run_forever() +# :stream_accounts_by_market__ diff --git a/rest/stream-candles.py b/rest/stream-candles.py new file mode 100644 index 0000000..b7491e2 --- /dev/null +++ b/rest/stream-candles.py @@ -0,0 +1,99 @@ +#!/usr/bin/python3 + +############################################################################### +# S T R E A M C A N D L E S # +############################################################################### + +# How to stream candle information from a Data Node using Websockets: +# ---------------------------------------------------------------------- +# Pagination and Date Range are not supported, this is a realtime stream. +# ---------------------------------------------------------------------- +# The stream requires the following parameter: +# candleId: Candle id (see below on how to retrieve this) +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import websocket +import threading +import json +import requests +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +# Load Vega market id +market_id = helpers.env_market_id() +assert market_id != "" + +# Hint: In order to get candles of a suitable bucket size e.g. 5 minutes and +# market id e.g. 13b081fe5bc8fd256b0a374dc04d94b904118312dd0d942e891a5f57ce0c556c +# you should use the list candle intervals API to get back a candle id: + +# __get_candle_intervals: +# Request a list of candle intervals available for a market and select a candle id +url = f"{data_node_url_rest}/candle/intervals?marketId={market_id}" +response = requests.get(url) +helpers.check_response(response) +print("Candle intervals for market:\n{}".format( + json.dumps(response.json(), indent=2, sort_keys=True))) +# :get_candle_intervals__ + +# Find the first candle id in the list e.g. trades_candle_5_minutes_ etc +candle_id = response.json()["intervalToCandleId"][0]["candleId"] +assert candle_id != "" +print(f"Candle found: {candle_id}") + +# Connect to the data node with a WSS based endpoint, this is not a HTTPS:// url +# Hint: to include/filter data from a party add the param `partyId` +# e.g. ?marketIds=xxx&partyId=yyy +url = f"{data_node_url_rest}/stream/candle/data?candleId={candle_id}".replace("https://", "wss://") +res = [] +event = threading.Event() + +# __stream_candles_by_market: +# Request a stream of candle updates for a market id and time bucket (e.g. candle id) on a Vega network + +def on_message(wsa, line): + # Vega data-node v2 returns the json line by line so we need to wait + # for a full structure before we can parse to valid JSON in python + if line == "{": + del res[:] + res.append(line) + elif line == "}": + res.append(line) + obj = json.loads(''.join(res)) + if "candle" in obj["result"]: + # When a new candle update arrives print the changes + print(f"Candle data found:") + print(obj["result"]["candle"]) + else: + res.append(line) + + +def on_error(wsa, error): + print(error) + + +def on_close(wsa, close_status_code, close_msg): + print(f"Candle stream closed: {url}") + + +def on_open(wsa): + print(f"Candle stream open: {url}") + + +def timeout(): + while not event.wait(timeout=30): + ws.close() + exit(1) + + +thread = threading.Thread(target=timeout) +thread.start() + +ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) +ws.on_open = on_open +ws.run_forever() +# :stream_candles_by_market__ diff --git a/rest/stream-delegations.py b/rest/stream-delegations.py new file mode 100644 index 0000000..7a99ea8 --- /dev/null +++ b/rest/stream-delegations.py @@ -0,0 +1,77 @@ +#!/usr/bin/python3 + +############################################################################### +# S T R E A M D E L E G A T I O N S # +############################################################################### + +# How to stream delegation information from a Data Node using Websockets: +# ---------------------------------------------------------------------- +# Pagination and Date Range are not supported, this is a realtime stream. +# ---------------------------------------------------------------------- +# The stream can be filtered by various parameters, including: +# partyId: Vega party id (public key) +# nodeId: Vega node id +# > Include none, one or both to refine the stream of data from Vega +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import websocket +import threading +import json +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +# Connect to the data node with a WSS based endpoint, this is not a HTTPS:// url +# Hint: to include/filter data from a party add the param `partyId` or add +# param `nodeId` to filter by Vega node +# e.g. ?nodeId=xxx&partyId=yyy +url = f"{data_node_url_rest}/stream/delegations".replace("https://", "wss://") +res = [] +event = threading.Event() + +# __stream_delegations: +# Request a stream of delegation updates on a Vega network + +def on_message(wsa, line): + # Vega data-node v2 returns the json line by line so we need to wait + # for a full structure before we can parse to valid JSON in python + if line == "{": + del res[:] + res.append(line) + elif line == "}": + res.append(line) + obj = json.loads(''.join(res)) + if "delegation" in obj["result"]: + print(f"Delegation data found:") + print(obj["result"]["delegation"]) + else: + res.append(line) + +def on_error(wsa, error): + print(error) + + +def on_close(wsa, close_status_code, close_msg): + print(f"Delegations stream closed: {url}") + + +def on_open(wsa): + print(f"Delegations stream open: {url}") + + +def timeout(): + while not event.wait(timeout=30): + ws.close() + exit(1) + + +thread = threading.Thread(target=timeout) +thread.start() + +ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) +ws.on_open = on_open +ws.run_forever() +# :stream_delegations__ diff --git a/rest/stream-governance.py b/rest/stream-governance.py new file mode 100644 index 0000000..1e73113 --- /dev/null +++ b/rest/stream-governance.py @@ -0,0 +1,75 @@ +#!/usr/bin/python3 + +############################################################################### +# S T R E A M G O V E R N A N C E # +############################################################################### + +# How to stream governance information from a Data Node using Websockets: +# ---------------------------------------------------------------------- +# Pagination is not supported, but the initial snapshot may contain +# multiple pages. Date Range is not supported, this is a realtime stream. +# ---------------------------------------------------------------------- +# The stream can be filtered the following parameter: +# partyId: Vega party id (public key) +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import websocket +import threading +import json +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +# Connect to the data node with a WSS based endpoint, this is not a HTTPS:// url +url = f"{data_node_url_rest}/stream/governance".replace("https://", "wss://") +res = [] +event = threading.Event() + +# __stream_governance: +# Request a stream of governance data on a Vega network + +def on_message(wsa, line): + # Vega data-node v2 returns the json line by line so we need to wait + # for a full structure before we can parse to valid JSON in python + if line == "{": + del res[:] + res.append(line) + elif line == "}": + res.append(line) + obj = json.loads(''.join(res)) + if "governance" in obj["result"]: + print(f"Governance data found:") + print(obj["result"]["governance"]) + else: + res.append(line) + + print(line) + +def on_error(wsa, error): + print(error) + + +def on_close(wsa, close_status_code, close_msg): + print(f"Governance stream closed: {url}") + + +def on_open(wsa): + print(f"Governance stream open: {url}") + + +def timeout(): + while not event.wait(timeout=30): + ws.close() + exit(1) + + +thread = threading.Thread(target=timeout) +thread.start() + +ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) +ws.on_open = on_open +ws.run_forever() +# :stream_governance__ diff --git a/rest/stream-market-data.py b/rest/stream-market-data.py index 773cb5d..849145a 100644 --- a/rest/stream-market-data.py +++ b/rest/stream-market-data.py @@ -8,7 +8,7 @@ # ---------------------------------------------------------------------- # Pagination and Date Range are not supported, this is a realtime stream. # ---------------------------------------------------------------------- -# The list has a required filter: +# The stream requires the following parameter/filter: # marketIds: Vega market id (a repeated param) for one or more markets # ---------------------------------------------------------------------- # For full details see the REST Reference API docs at https://docs.vega.xyz @@ -33,10 +33,6 @@ res = [] event = threading.Event() -# Load Vega node API v2 URL, this is set using 'source vega-config' -# located in the root folder of the sample-api-scripts repository -data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") - # __stream_market_data_by_markets: # Request a stream of live market data for one or more market ids on a Vega network diff --git a/rest/stream-orders.py b/rest/stream-orders.py index 245ba34..e7b395d 100644 --- a/rest/stream-orders.py +++ b/rest/stream-orders.py @@ -9,7 +9,7 @@ # Pagination is not supported, but the initial snapshot may contain # multiple pages. Date Range is not supported, this is a realtime stream. # ---------------------------------------------------------------------- -# The list can be filtered by various parameters, including: +# The stream can be filtered by various parameters, including: # partyId: Vega party id (public key) # marketId: Vega market id # > Include none, one or both to refine the stream of data from Vega @@ -36,10 +36,6 @@ res = [] event = threading.Event() -# Load Vega node API v2 URL, this is set using 'source vega-config' -# located in the root folder of the sample-api-scripts repository -data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") - # __stream_orders_by_market: # Request a stream of live orders and updates for a market id on a Vega network diff --git a/rest/stream-trades.py b/rest/stream-trades.py index 57540f0..6a189cc 100644 --- a/rest/stream-trades.py +++ b/rest/stream-trades.py @@ -6,10 +6,9 @@ # How to stream trade information from a Data Node using Websockets: # ---------------------------------------------------------------------- -# Pagination is not supported, but the initial snapshot may contain -# multiple pages. Date Range is not supported, this is a realtime stream. +# Pagination and Date Range are not supported, this is a realtime stream. # ---------------------------------------------------------------------- -# The list can be filtered by various parameters, including: +# The stream can be filtered by various parameters, including: # partyId: Vega party id (public key) # marketId: Vega market id # > Include none, one or both to refine the stream of data from Vega @@ -32,16 +31,12 @@ # Connect to the data node with a WSS based endpoint, this is not a HTTPS:// url # Hint: to include/filter data from a party add the param `partyId` # e.g. ?marketIds=xxx&partyId=yyy -url = f"{data_node_url_rest}/stream/trades?market_id={market_id}".replace("https://", "wss://") +url = f"{data_node_url_rest}/stream/trades?marketId={market_id}".replace("https://", "wss://") res = [] event = threading.Event() -# Load Vega node API v2 URL, this is set using 'source vega-config' -# located in the root folder of the sample-api-scripts repository -data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") - # __stream_trades_by_market: -# Request a stream of live trades and updates for a market id on a Vega network +# Request a stream of trades and updates for a market id on a Vega network def on_message(wsa, line): # Vega data-node v2 returns the json line by line so we need to wait From 15dfac71fa5b9ae020c7a85321d7eab57ba520e7 Mon Sep 17 00:00:00 2001 From: cdm Date: Sun, 4 Dec 2022 15:50:19 +0000 Subject: [PATCH 30/33] Improve market proposal script with stake linking check --- rest/propose-vote-enact-new-market.py | 36 +++++------ rest/stream-market-depth.py | 90 +++++++++++++++++++++++++++ 2 files changed, 107 insertions(+), 19 deletions(-) create mode 100644 rest/stream-market-depth.py diff --git a/rest/propose-vote-enact-new-market.py b/rest/propose-vote-enact-new-market.py index 7a65262..3739b6b 100644 --- a/rest/propose-vote-enact-new-market.py +++ b/rest/propose-vote-enact-new-market.py @@ -15,7 +15,7 @@ wallet_server_url = helpers.get_from_env("WALLET_SERVER_URL") # Set to True to optionally wait/block until the new market proposal is enacted -WAIT_FOR_MARKET_AFTER_VOTE = False +WAIT_FOR_MARKET_AFTER_VOTE = True ############################################################################### # F I N D A S S E T S # @@ -57,27 +57,17 @@ print("VEGA asset not found on specified Vega network, please symbol name check and try again") exit(1) -# Request accounts for party and check governance asset balance -url = f"{data_node_url_rest}/accounts?filter.partyIds={pubkey}" -response = requests.get(url) -helpers.check_response(response) - # Debugging # print("Accounts:\n{}".format( # json.dumps(response.json(), indent=2, sort_keys=True))) -voting_balance = 0 -accounts = response.json()["accounts"]["edges"] - -for account in accounts: - if account["account"]["asset"] == vote_asset_id: - print("Found governance asset account") - print(json.dumps(account, indent=2, sort_keys=True)) - voting_balance = account["account"]["balance"] - break - +# Request accounts for party and check governance asset balance +url = f"{data_node_url_rest}/parties/{pubkey}/stake" +response = requests.get(url) +helpers.check_response(response) +voting_balance = response.json()["currentStakeAvailable"] if voting_balance == 0: - print(f"Please deposit VEGA asset to public key {pubkey} and try again") + print(f"Please associate VEGA governance asset to public key {pubkey} and try again") exit(1) print("Voting balance:") @@ -124,7 +114,7 @@ rationale_desc = "Proposal to create a new futures market for tDAI terminating in April 2023" # The proposal command below contains the configuration for a new market -proposal = { +new_market = { "proposalSubmission": { "reference": proposal_ref, "rationale": { @@ -249,8 +239,16 @@ } # :propose_market__ -print(json.dumps(response.json(), indent=4, sort_keys=True)) +# __sign_tx_proposal: +# Sign the transaction with a proposal submission command +# Hint: Setting propagate to true will also submit to a Vega node +url = f"{wallet_server_url}/api/v1/command/sync" +headers = {"Authorization": f"Bearer {token}"} +response = requests.post(url, headers=headers, json=new_market) +helpers.check_response(response) +# :sign_tx_proposal__ +print(json.dumps(response.json(), indent=4, sort_keys=True)) print() print("Signed new market proposal and sent to Vega") diff --git a/rest/stream-market-depth.py b/rest/stream-market-depth.py new file mode 100644 index 0000000..1053f35 --- /dev/null +++ b/rest/stream-market-depth.py @@ -0,0 +1,90 @@ +#!/usr/bin/python3 + +############################################################################### +# S T R E A M M A R K E T D E P T H # +############################################################################### + +# IMPORTANT: This streaming endpoint returns the entire market depth/order +# book on each update, if you're looking for a stream of differences see +# the script `stream-market-depth-updates.py` + +# todo: test with live markets when we have data from one of them available + +# How to stream market depth information from a Data Node using Websockets: +# ---------------------------------------------------------------------- +# Pagination and Date Range are not supported, this is a realtime stream. +# ---------------------------------------------------------------------- +# The stream requires the following parameter/filter: +# marketIds: Vega market id (a repeated param) for one or more markets +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import websocket +import threading +import json +import helpers + + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +# Load Vega market id +market_id = helpers.env_market_id() +assert market_id != "" + +# Connect to the data node with a WSS based endpoint, this is not a HTTPS:// url +# Hint: to include data from multiple markets repeat the param `marketIds` +# e.g. marketIds=xxx&marketIds=yyy&marketIds=zzz +url = f"{data_node_url_rest}/stream/markets/depth?marketIds={market_id}".replace("https://", "wss://") +res = [] +event = threading.Event() + +print(url) + +# __stream_market_depth_by_markets: +# Request a stream of live market depth data for one or more market ids on a Vega network + +def on_message(wsa, line): + # Vega data-node v2 returns the json line by line so we need to wait + # for a full structure before we can parse to valid JSON in python + if line == "{": + del res[:] + res.append(line) + elif line == "}": + res.append(line) + obj = json.loads(''.join(res)) + if "marketDepth" in obj["result"]: + # Result contains each market-depth update (may be multiple) + found_market = obj["result"]["marketDepth"][0]["marketId"] + print(f"Market depth data found for {found_market}:") + print(obj["result"]["marketDepth"][0]) + else: + res.append(line) + + +def on_error(wsa, error): + print(error) + + +def on_close(wsa, close_status_code, close_msg): + print(f"Market-depth stream closed: {url}") + + +def on_open(wsa): + print(f"Market-depth stream open: {url}") + + +def timeout(): + while not event.wait(timeout=30): + ws.close() + exit(1) + + +thread = threading.Thread(target=timeout) +thread.start() + +ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) +ws.on_open = on_open +ws.run_forever() +# :stream_market_data_by_markets__ From a20742f5e07e7fc3cd8627f9f14154d1c50d9b0a Mon Sep 17 00:00:00 2001 From: cdm Date: Sun, 4 Dec 2022 18:11:35 +0000 Subject: [PATCH 31/33] Market depth updates stream example --- rest/stream-market-depth-updates.py | 88 +++++++++++++++++++++++++++++ rest/stream-market-depth.py | 2 - 2 files changed, 88 insertions(+), 2 deletions(-) create mode 100644 rest/stream-market-depth-updates.py diff --git a/rest/stream-market-depth-updates.py b/rest/stream-market-depth-updates.py new file mode 100644 index 0000000..3c39e4b --- /dev/null +++ b/rest/stream-market-depth-updates.py @@ -0,0 +1,88 @@ +#!/usr/bin/python3 + +############################################################################### +# S T R E A M M A R K E T D E P T H U P D A T E S # +############################################################################### + +# IMPORTANT: This streaming endpoint returns only the changes to market depth +# /order book on each update, if you're looking for a stream of the full order +# book, see the script `stream-market-depth.py` + +# How to stream market depth information from a Data Node using Websockets: +# ---------------------------------------------------------------------- +# Pagination and Date Range are not supported, this is a realtime stream. +# ---------------------------------------------------------------------- +# The stream requires the following parameter/filter: +# marketIds: Vega market id (a repeated param) for one or more markets +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import websocket +import threading +import json +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +# Load Vega market id +market_id = helpers.env_market_id() +assert market_id != "" + +# Connect to the data node with a WSS based endpoint, this is not a HTTPS:// url +# Hint: to include data from multiple markets repeat the param `marketIds` +# e.g. marketIds=xxx&marketIds=yyy&marketIds=zzz +url = f"{data_node_url_rest}/stream/markets/depth/updates?marketIds={market_id}"\ + .replace("https://", "wss://") +res = [] +event = threading.Event() + +print(url) + +# __stream_market_depth_by_markets: +# Request a stream of live market depth update data for one or more market ids on a Vega network + +def on_message(wsa, line): + # Vega data-node v2 returns the json line by line so we need to wait + # for a full structure before we can parse to valid JSON in python + if line == "{": + del res[:] + res.append(line) + elif line == "}": + res.append(line) + obj = json.loads(''.join(res)) + if "update" in obj["result"]: + # Result contains each market-depth update (may be multiple) + found_market = obj["result"]["update"][0]["marketId"] + print(f"Market depth data found for {found_market}:") + print(obj["result"]["update"][0]) + else: + res.append(line) + + +def on_error(wsa, error): + print(error) + + +def on_close(wsa, close_status_code, close_msg): + print(f"Market-depth stream closed: {url}") + + +def on_open(wsa): + print(f"Market-depth stream open: {url}") + + +def timeout(): + while not event.wait(timeout=30): + ws.close() + exit(1) + + +thread = threading.Thread(target=timeout) +thread.start() + +ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) +ws.on_open = on_open +ws.run_forever() +# :stream_market_data_by_markets__ diff --git a/rest/stream-market-depth.py b/rest/stream-market-depth.py index 1053f35..6f95f34 100644 --- a/rest/stream-market-depth.py +++ b/rest/stream-market-depth.py @@ -8,8 +8,6 @@ # book on each update, if you're looking for a stream of differences see # the script `stream-market-depth-updates.py` -# todo: test with live markets when we have data from one of them available - # How to stream market depth information from a Data Node using Websockets: # ---------------------------------------------------------------------- # Pagination and Date Range are not supported, this is a realtime stream. From f897559b172c9990150afbb267948f30a661e2e6 Mon Sep 17 00:00:00 2001 From: cdm Date: Sun, 4 Dec 2022 18:52:59 +0000 Subject: [PATCH 32/33] Update margin levels --- rest/propose-vote-enact-freeform.py | 20 +++--- rest/propose-vote-enact-network-params.py | 20 +++--- rest/propose-vote-enact-new-market.py | 2 +- rest/stream-margin-levels.py | 85 +++++++++++++++++++++++ rest/stream-market-depth-updates.py | 4 +- rest/stream-market-depth.py | 2 +- 6 files changed, 107 insertions(+), 26 deletions(-) create mode 100644 rest/stream-margin-levels.py diff --git a/rest/propose-vote-enact-freeform.py b/rest/propose-vote-enact-freeform.py index 69e35ad..769159c 100644 --- a/rest/propose-vote-enact-freeform.py +++ b/rest/propose-vote-enact-freeform.py @@ -46,20 +46,18 @@ # print("Accounts:\n{}".format( # json.dumps(response.json(), indent=2, sort_keys=True))) -voting_balance = 0 -accounts = response.json()["accounts"]["edges"] - -for account in accounts: - if account["account"]["asset"] == vote_asset_id: - print("Found governance asset account") - print(account) - voting_balance = account["account"]["balance"] - break - +# Request governance stake/voting balance +url = f"{data_node_url_rest}/parties/{pubkey}/stake" +response = requests.get(url) +helpers.check_response(response) +voting_balance = response.json()["currentStakeAvailable"] if voting_balance == 0: - print(f"Please deposit VEGA asset to public key {pubkey} and try again") + print(f"Please associate VEGA governance asset to public key {pubkey} and try again") exit(1) +print("Voting balance:") +print(voting_balance) + ##################################################################################### # B L O C K C H A I N T I M E # ##################################################################################### diff --git a/rest/propose-vote-enact-network-params.py b/rest/propose-vote-enact-network-params.py index 1c7f920..c161aa1 100644 --- a/rest/propose-vote-enact-network-params.py +++ b/rest/propose-vote-enact-network-params.py @@ -48,20 +48,18 @@ # print("Accounts:\n{}".format( # json.dumps(response.json(), indent=2, sort_keys=True))) -voting_balance = 0 -accounts = response.json()["accounts"]["edges"] - -for account in accounts: - if account["account"]["asset"] == vote_asset_id: - print("Found governance asset account") - print(account) - voting_balance = account["account"]["balance"] - break - +# Request governance stake/voting balance +url = f"{data_node_url_rest}/parties/{pubkey}/stake" +response = requests.get(url) +helpers.check_response(response) +voting_balance = response.json()["currentStakeAvailable"] if voting_balance == 0: - print(f"Please deposit VEGA asset to public key {pubkey} and try again") + print(f"Please associate VEGA governance asset to public key {pubkey} and try again") exit(1) +print("Voting balance:") +print(voting_balance) + ##################################################################################### # B L O C K C H A I N T I M E # ##################################################################################### diff --git a/rest/propose-vote-enact-new-market.py b/rest/propose-vote-enact-new-market.py index 3739b6b..a6d431e 100644 --- a/rest/propose-vote-enact-new-market.py +++ b/rest/propose-vote-enact-new-market.py @@ -61,7 +61,7 @@ # print("Accounts:\n{}".format( # json.dumps(response.json(), indent=2, sort_keys=True))) -# Request accounts for party and check governance asset balance +# Request governance stake/voting balance url = f"{data_node_url_rest}/parties/{pubkey}/stake" response = requests.get(url) helpers.check_response(response) diff --git a/rest/stream-margin-levels.py b/rest/stream-margin-levels.py new file mode 100644 index 0000000..81d8aa4 --- /dev/null +++ b/rest/stream-margin-levels.py @@ -0,0 +1,85 @@ +#!/usr/bin/python3 + +############################################################################### +# S T R E A M M A R G I N L E V E L S # +############################################################################### + +# How to stream margin levels information from a Data Node using Websockets: +# ---------------------------------------------------------------------- +# Pagination and Date Range are not supported, this is a realtime stream. +# ---------------------------------------------------------------------- +# The stream has two required parameters, as follows: +# partyId: Vega party id (public key) +# marketId: Vega market id +# > Both are required to stream margin level data +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import websocket +import threading +import json +import helpers + +# Vega wallet interaction helper, see login.py for detail +from login import pubkey + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +# Load Vega market id +market_id = helpers.env_market_id() +assert market_id != "" + +# Connect to the data node with a WSS based endpoint, this is not a HTTPS:// url +# e.g. ?marketId=xxx&partyId=yyy +url = f"{data_node_url_rest}/stream/margin/levels?partyId={pubkey}&marketId={market_id}"\ + .replace("https://", "wss://") +res = [] +event = threading.Event() + +# __stream_margin_levels: +# Request a stream of margin level updates for a party and market id on a Vega network + +def on_message(wsa, line): + # Vega data-node v2 returns the json line by line so we need to wait + # for a full structure before we can parse to valid JSON in python + if line == "{": + del res[:] + res.append(line) + elif line == "}": + res.append(line) + obj = json.loads(''.join(res)) + if "marginLevels" in obj["result"]: + # Result contains margin level update for party on a market + print(f"Margin level data found:") + print(obj["result"]["marginLevels"]) + else: + res.append(line) + + +def on_error(wsa, error): + print(error) + + +def on_close(wsa, close_status_code, close_msg): + print(f"Margin levels stream closed: {url}") + + +def on_open(wsa): + print(f"Margin levels stream open: {url}") + + +def timeout(): + while not event.wait(timeout=30): + ws.close() + exit(1) + + +thread = threading.Thread(target=timeout) +thread.start() + +ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) +ws.on_open = on_open +ws.run_forever() +# :stream_margin_levels__ diff --git a/rest/stream-market-depth-updates.py b/rest/stream-market-depth-updates.py index 3c39e4b..8fd40c5 100644 --- a/rest/stream-market-depth-updates.py +++ b/rest/stream-market-depth-updates.py @@ -40,7 +40,7 @@ print(url) -# __stream_market_depth_by_markets: +# __stream_market_depth_updates_by_markets: # Request a stream of live market depth update data for one or more market ids on a Vega network def on_message(wsa, line): @@ -85,4 +85,4 @@ def timeout(): ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) ws.on_open = on_open ws.run_forever() -# :stream_market_data_by_markets__ +# :stream_market_depth_updates_by_markets__ diff --git a/rest/stream-market-depth.py b/rest/stream-market-depth.py index 6f95f34..835e9f2 100644 --- a/rest/stream-market-depth.py +++ b/rest/stream-market-depth.py @@ -85,4 +85,4 @@ def timeout(): ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) ws.on_open = on_open ws.run_forever() -# :stream_market_data_by_markets__ +# :stream_market_depth_by_markets__ From 2c72b4412a2620ee95b44ccbb7e82baf6a7ae2e5 Mon Sep 17 00:00:00 2001 From: cdm Date: Sun, 4 Dec 2022 20:25:54 +0000 Subject: [PATCH 33/33] Add streaming examples --- rest/stream-positions.py | 88 ++++++++++++++++++++++++++++++++++++++++ rest/stream-rewards.py | 86 +++++++++++++++++++++++++++++++++++++++ rest/stream-votes.py | 82 +++++++++++++++++++++++++++++++++++++ 3 files changed, 256 insertions(+) create mode 100644 rest/stream-positions.py create mode 100644 rest/stream-rewards.py create mode 100644 rest/stream-votes.py diff --git a/rest/stream-positions.py b/rest/stream-positions.py new file mode 100644 index 0000000..96db755 --- /dev/null +++ b/rest/stream-positions.py @@ -0,0 +1,88 @@ +#!/usr/bin/python3 + +############################################################################### +# S T R E A M P O S I T I O N S # +############################################################################### + +# How to stream position information from a Data Node using Websockets: +# ---------------------------------------------------------------------- +# Pagination is not supported, but the initial snapshot may contain +# multiple pages. Date Range is not supported, this is a realtime stream. +# ---------------------------------------------------------------------- +# The stream can be filtered by various parameters, including: +# partyId: Vega party id (public key) +# marketId: Vega market id +# > Include none, one or both to refine the stream of data from Vega +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import websocket +import threading +import json +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +# Load Vega market id +market_id = helpers.env_market_id() +assert market_id != "" + +# Connect to the data node with a WSS based endpoint, this is not a HTTPS:// url +# Hint: to include/filter data from a party add the param `partyId` and same +# for a market id: +# e.g. ?marketId=xxx&partyId=yyy +url = f"{data_node_url_rest}/stream/positions".replace("https://", "wss://") +res = [] +event = threading.Event() + +# __stream_positions: +# Request a stream of positions for a market id on a Vega network + +def on_message(wsa, line): + # Vega data-node v2 returns the json line by line so we need to wait + # for a full structure before we can parse to valid JSON in python + if line == "{": + del res[:] + res.append(line) + elif line == "}": + res.append(line) + obj = json.loads(''.join(res)) + if "snapshot" in obj["result"]: + # An 'initial image' snapshot containing current positions (may be multiple pages) + print("Snapshot found:") + print(obj["result"]["snapshot"]["positions"]) + if "updates" in obj["result"]: + # A list of position updates typically from the last block + print("Updates found:") + print(obj["result"]["updates"]["positions"]) + else: + res.append(line) + + +def on_error(wsa, error): + print(error) + + +def on_close(wsa, close_status_code, close_msg): + print(f"Positions stream closed: {url}") + + +def on_open(wsa): + print(f"Positions stream open: {url}") + + +def timeout(): + while not event.wait(timeout=30): + ws.close() + exit(1) + + +thread = threading.Thread(target=timeout) +thread.start() + +ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) +ws.on_open = on_open +ws.run_forever() +# :stream_positions__ diff --git a/rest/stream-rewards.py b/rest/stream-rewards.py new file mode 100644 index 0000000..9a21d3b --- /dev/null +++ b/rest/stream-rewards.py @@ -0,0 +1,86 @@ +#!/usr/bin/python3 + +############################################################################### +# S T R E A M R E W A R D S # +############################################################################### + +# How to stream reward information from a Data Node using Websockets: +# ---------------------------------------------------------------------- +# Pagination and Date Range are not supported, this is a realtime stream. +# ---------------------------------------------------------------------- +# The stream can be filtered by various parameters, including: +# partyId: Vega party id (public key) +# marketId: Vega market id +# > Include none, one or both to refine the stream of data from Vega +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import websocket +import threading +import json +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +# Load Vega market id +market_id = helpers.env_market_id() +assert market_id != "" + +# Load Vega party id +party_id = helpers.env_party_id() +assert party_id != "" + +# Connect to the data node with a WSS based endpoint, this is not a HTTPS:// url +# Hint: to include/filter data from a party add the param `partyId` +# e.g. ?assetId=xxx&partyId=yyy +url = f"{data_node_url_rest}/stream/rewards?partyId={party_id}".replace("https://", "wss://") +res = [] +event = threading.Event() + +# __stream_rewards: +# Request a stream of rewards on a Vega network + +def on_message(wsa, line): + # Vega data-node v2 returns the json line by line so we need to wait + # for a full structure before we can parse to valid JSON in python + if line == "{": + del res[:] + res.append(line) + elif line == "}": + res.append(line) + obj = json.loads(''.join(res)) + if "reward" in obj["result"]: + # Result contains reward data for party + print(f"Reward data found:") + print(obj["result"]["reward"]) + else: + res.append(line) + + +def on_error(wsa, error): + print(error) + + +def on_close(wsa, close_status_code, close_msg): + print(f"Rewards stream closed: {url}") + + +def on_open(wsa): + print(f"Rewards stream open: {url}") + + +def timeout(): + while not event.wait(timeout=30): + ws.close() + exit(1) + + +thread = threading.Thread(target=timeout) +thread.start() + +ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) +ws.on_open = on_open +ws.run_forever() +# :stream_rewards__ diff --git a/rest/stream-votes.py b/rest/stream-votes.py new file mode 100644 index 0000000..139acf8 --- /dev/null +++ b/rest/stream-votes.py @@ -0,0 +1,82 @@ +#!/usr/bin/python3 + +############################################################################### +# S T R E A M V O T E S # +############################################################################### + +# How to stream vote information from a Data Node using Websockets: +# ---------------------------------------------------------------------- +# Pagination and Date Range are not supported, this is a realtime stream. +# ---------------------------------------------------------------------- +# The stream can be filtered by various parameters, including: +# partyId: Vega party id (public key) +# proposalId: Optional proposal id +# > Include one or both to refine the stream of data from Vega +# ---------------------------------------------------------------------- +# For full details see the REST Reference API docs at https://docs.vega.xyz + +import websocket +import threading +import json +import helpers + +# Load Vega node API v2 URL, this is set using 'source vega-config' +# located in the root folder of the sample-api-scripts repository +data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") + +# Load Vega party id +party_id = helpers.env_party_id() +assert party_id != "" + +# Connect to the data node with a WSS based endpoint, this is not a HTTPS:// url +# Hint: to include/filter data from a proposal id add the param `proposalId` +# e.g. ?partyId=xxx&proposalId=yyy +url = f"{data_node_url_rest}/stream/votes?partyId={party_id}".replace("https://", "wss://") +res = [] +event = threading.Event() + +# __stream_votes_by_party: +# Request a stream of votes for a party id on a Vega network + +def on_message(wsa, line): + # Vega data-node v2 returns the json line by line so we need to wait + # for a full structure before we can parse to valid JSON in python + if line == "{": + del res[:] + res.append(line) + elif line == "}": + res.append(line) + obj = json.loads(''.join(res)) + if "vote" in obj["result"]: + # Result contains reward data for party + print(f"Vote data found:") + print(obj["result"]["vote"]) + else: + res.append(line) + + +def on_error(wsa, error): + print(error) + + +def on_close(wsa, close_status_code, close_msg): + print(f"Votes stream closed: {url}") + + +def on_open(wsa): + print(f"Votes stream open: {url}") + + +def timeout(): + while not event.wait(timeout=30): + ws.close() + exit(1) + + +thread = threading.Thread(target=timeout) +thread.start() + +ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) +ws.on_open = on_open +ws.run_forever() +# :stream_votes_by_party__