├── graphql ├── get-checkpoints.graphql ├── get-vega-time.graphql ├── stream-trades.graphql ├── stream-orders.graphql ├── get-node-data.graphql ├── get-network-parameters.graphql ├── get-key-rotations.graphql ├── get-network-limits.graphql ├── get-statistics.graphql ├── get-ledger-entries.graphql ├── get-assets.graphql ├── get-staking-data.graphql ├── README.md ├── get-order-by-reference.graphql ├── stream-orders-by-reference.graphql ├── get-trades-for-order.graphql ├── stream-market-data.graphql ├── get-accounts-for-markets.graphql ├── get-transfers.graphql ├── get-delegations.graphql ├── get-accounts-for-parties.graphql ├── get-candles.graphql ├── get-positions.graphql ├── get-governance-votes.graphql ├── get-balances.graphql ├── get-parties-accounts.graphql ├── get-rewards.graphql ├── get-withdrawals.graphql ├── get-deposits.graphql ├── get-orders-and-trades-for-party.graphql ├── get-orders-and-trades-for-market.graphql ├── get-margin-levels.graphql ├── Get-Markets.graphql ├── get-governance-proposals.graphql ├── stream-events.graphql ├── get-liquidity-provisions-by-party.graphql ├── get-liquidity-provisions-by-market.graphql └── get-market-data.graphql ├── rest ├── requirements.txt ├── logout.py ├── get-checkpoints.py ├── get-statistics.py ├── get-vega-time.py ├── liquidity-commitments-list.py ├── get-key-rotations.py ├── get-market-depth.py ├── login.py ├── get-staking-data.py ├── get-governance-votes.py ├── get-positions.py ├── get-network-data-and-limits.py ├── get-network-parameters.py ├── get-epochs.py ├── get-markets.py ├── liquidity-commitment-cancel.py ├── stream-governance.py ├── README.md ├── get-assets.py ├── get-governance-proposals.py ├── stream-delegations.py ├── get-ledger-entries.py ├── stream-votes.py ├── stream-rewards.py ├── stream-market-data.py ├── liquidity-commitment-amend.py ├── stream-trades.py ├── stream-margin-levels.py ├── get-node-data.py ├── estimate-fees-and-margin.py ├── get-transfers.py ├── get-parties.py ├── stream-orders.py ├── stream-positions.py ├── get-deposits.py ├── stream-accounts.py ├── stream-market-depth.py ├── stream-market-depth-updates.py ├── get-withdrawals.py ├── get-liquidity-provisions.py ├── get-candles.py ├── get-market-data.py ├── get-balances.py ├── stream-candles.py ├── liquidity-commitment-submit.py ├── get-margin-levels.py ├── get-delegations.py ├── date-range.py ├── pegged-order-cancel.py ├── order-submit.py ├── pegged-order-submit.py ├── order-amend.py ├── order-cancel.py ├── pegged-order-amend.py ├── get-trades.py └── get-accounts.py ├── renovate.json ├── .gitignore ├── .gitpod.Dockerfile ├── .gitpod.yml ├── vega-config-win.bat ├── vega-config ├── LICENSE └── README.md /graphql/get-checkpoints.graphql: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /rest/requirements.txt: -------------------------------------------------------------------------------- 1 | requests==2.27.1 2 | websocket-client==1.3.2 3 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "config:base" 4 | ] 5 | } 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | .venv 3 | venv 4 | credentials.* 5 | /credentials 6 | *.tmp 7 | .idea 8 | .DS_Store 9 | token.temp 10 | -------------------------------------------------------------------------------- /.gitpod.Dockerfile: -------------------------------------------------------------------------------- 1 | FROM gitpod/workspace-full:latest 2 | 3 | # Install gq 4 | ENV PATH="$PATH:$HOME/node_modules/.bin" 5 | RUN npm install graphqurl@0.3.3 6 | -------------------------------------------------------------------------------- /.gitpod.yml: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | image: 4 | file: .gitpod.Dockerfile 5 | 6 | tasks: 7 | - init: pipenv install -r requirements.txt --python 3.8 ; [[ -r credentials ]] || cp -a credentials-template credentials 8 | command: pipenv shell 9 | 10 | ports: [] 11 | -------------------------------------------------------------------------------- /graphql/get-vega-time.graphql: -------------------------------------------------------------------------------- 1 | # How to get Vega Time from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 6 | 7 | 8 | query GetVegaTime { 9 | statistics { 10 | vegaTime 11 | } 12 | } -------------------------------------------------------------------------------- /graphql/stream-trades.graphql: -------------------------------------------------------------------------------- 1 | # How to stream trades from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 6 | 7 | 8 | subscription StreamTrades { 9 | trades { 10 | id 11 | marketId 12 | buyOrder 13 | sellOrder 14 | } 15 | } -------------------------------------------------------------------------------- /graphql/stream-orders.graphql: -------------------------------------------------------------------------------- 1 | # How to stream orders from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 6 | 7 | 8 | subscription StreamOrders{ 9 | orders{ 10 | id 11 | price 12 | timeInForce 13 | side 14 | marketId 15 | size 16 | } 17 | } -------------------------------------------------------------------------------- /graphql/get-node-data.graphql: -------------------------------------------------------------------------------- 1 | 2 | # How to get information on nodes from a Data Node using GraphQL calls: 3 | # ---------------------------------------------------------------------- 4 | # Cursor pagination is supported 5 | # ---------------------------------------------------------------------- 6 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 7 | 8 | query getNodeData { 9 | nodeData { 10 | stakedTotal 11 | totalNodes 12 | inactiveNodes 13 | validatingNodes 14 | uptime 15 | } 16 | } -------------------------------------------------------------------------------- /rest/logout.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from login import token 3 | 4 | url = "http://localhost:1789/api/v2/requests" 5 | connect_payload = "{\n \"id\": \"1\",\n \"jsonrpc\": \"2.0\",\n \"method\": \"client.disconnect_wallet\"\n }" 6 | connect_headers = { 7 | 'Content-Type': 'application/json-rpc', 8 | 'Accept': 'application/json-rpc', 9 | 'Origin': 'application/json-rpc', 10 | 'Authorization': token 11 | } 12 | connectionResponse = requests.request("POST", url, headers=connect_headers, data=connect_payload) 13 | print(connectionResponse.text) -------------------------------------------------------------------------------- /graphql/get-network-parameters.graphql: -------------------------------------------------------------------------------- 1 | 2 | # How to get information on network parameters from a Data Node using GraphQL calls: 3 | # ---------------------------------------------------------------------- 4 | # Cursor pagination is supported 5 | # ---------------------------------------------------------------------- 6 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 7 | 8 | query getNetworkParameters { 9 | networkParametersConnection { 10 | edges { 11 | node { 12 | key 13 | value 14 | } 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /graphql/get-key-rotations.graphql: -------------------------------------------------------------------------------- 1 | # How to get information on key rotations from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 6 | 7 | 8 | query getKeyRotations { 9 | keyRotationsConnection { 10 | edges { 11 | node { 12 | nodeId 13 | oldPubKey 14 | newPubKey 15 | blockHeight 16 | } 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /vega-config-win.bat: -------------------------------------------------------------------------------- 1 | 2 | REM Default server configuration used by REST/GRPC/GRAPHQL examples on WINDOWS 3 | 4 | REM See other vega-config-XXXX scripts for other examples of network configurations or 5 | REM update the URLs below to your desired network and wallet setup: 6 | 7 | SET DATA_NODE_URL_REST=https://api.n06.testnet.vega.xyz/api/v2 8 | SET DATA_NODE_URL_GRAPHQL=https://api.n07.testnet.vega.xyz/graphql 9 | SET DATA_NODE_URL_GRPC=n07.testnet.vega.xyz:3007 10 | SET WALLET_SERVER_URL=https://wallet.testnet.vega.xyz 11 | SET MARKET_ID= 12 | SET PARTY_ID= 13 | SET ASSET_ID= 14 | 15 | echo vega-config has been configured 16 | -------------------------------------------------------------------------------- /graphql/get-network-limits.graphql: -------------------------------------------------------------------------------- 1 | 2 | # How to get information on network limits from a Data Node using GraphQL calls: 3 | # ---------------------------------------------------------------------- 4 | # Cursor pagination is supported 5 | # ---------------------------------------------------------------------- 6 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 7 | 8 | 9 | query getNetworkLimits { 10 | networkLimits { 11 | canProposeMarket 12 | canProposeAsset 13 | bootstrapFinished 14 | proposeMarketEnabled 15 | proposeAssetEnabled 16 | bootstrapBlockCount 17 | genesisLoaded 18 | proposeMarketEnabledFrom 19 | proposeAssetEnabledFrom 20 | } 21 | } -------------------------------------------------------------------------------- /graphql/get-statistics.graphql: -------------------------------------------------------------------------------- 1 | # How to get information on key statistics from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 6 | 7 | 8 | query getStatistics { 9 | statistics { 10 | chainVersion 11 | appVersion 12 | status 13 | totalTrades 14 | totalOrders 15 | totalPeers 16 | totalMarkets 17 | ordersPerSecond 18 | tradesPerSecond 19 | averageOrdersPerBlock 20 | averageTxBytes 21 | } 22 | } -------------------------------------------------------------------------------- /graphql/get-ledger-entries.graphql: -------------------------------------------------------------------------------- 1 | # How to get information on ledger entries from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 6 | 7 | query getLedgerEntries { 8 | ledgerEntries( 9 | filter: {AccountToFilter: {partyIds: "644a1a8bb2fba612612dd6a5d400c49eb469d91dff777b0eda3f4cd554296759"}} 10 | ) { 11 | edges { 12 | node { 13 | vegaTime 14 | quantity 15 | partyId 16 | assetId 17 | marketId 18 | accountType 19 | } 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /graphql/get-assets.graphql: -------------------------------------------------------------------------------- 1 | # How to get information on assets from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # The list can be filtered by various parameters, like so: 6 | # assetsConnection (id: "ASSET_ID") 7 | # ---------------------------------------------------------------------- 8 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 9 | 10 | query getAssets { 11 | assetsConnection { 12 | edges { 13 | node { 14 | id 15 | name 16 | symbol 17 | decimals 18 | quantum 19 | status 20 | } 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /graphql/get-staking-data.graphql: -------------------------------------------------------------------------------- 1 | # How to get account information about Staking from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # The list can be filtered by various parameters, like so: 6 | # partiesConnection (id: "PUBLIC_KEY") 7 | # ---------------------------------------------------------------------- 8 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 9 | 10 | 11 | query getStakingData { 12 | partiesConnection { 13 | edges { 14 | node { 15 | stakingSummary { 16 | currentStakeAvailable 17 | } 18 | } 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /vega-config: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Default server configuration used by REST/GRPC/GRAPHQL examples 4 | 5 | # See other vega-config-XXXX scripts for other examples of network configurations or 6 | # update the URLs below to your desired network and wallet setup: 7 | 8 | DATA_NODE_URL_REST="https://api.n06.testnet.vega.xyz/api/v2" 9 | DATA_NODE_URL_GRAPHQL="https://api.n07.testnet.vega.xyz/graphql" 10 | DATA_NODE_URL_GRPC="n07.testnet.vega.xyz:3007" 11 | WALLET_SERVER_URL="https://wallet.testnet.vega.xyz" 12 | MARKET_ID="" 13 | PARTY_ID="" 14 | ASSET_ID="" 15 | 16 | # Do not edit below this line 17 | 18 | export DATA_NODE_URL_GRPC 19 | export DATA_NODE_URL_REST 20 | export DATA_NODE_URL_GRAPHQL 21 | export WALLET_SERVER_URL 22 | 23 | export MARKET_ID 24 | export PARTY_ID 25 | export ASSET_ID 26 | -------------------------------------------------------------------------------- /graphql/README.md: -------------------------------------------------------------------------------- 1 | # GraphQL Samples 2 | 3 | The files here represent queries you can use to call various aspects of the Vega data-node GraphQL APIs. 4 | 5 | **REFERENCE APIs:** Reference API documentation for the GraphQL APIs can be found at: https://docs.vega.xyz/ 6 | 7 | 8 | ## How to run GraphQL queries 9 | 10 | 1) If you would like to stay in your browser, you can copy and paste the queries in this folder into graphQL playground: 11 | 12 | https://api.n10.testnet.vega.xyz/graphql/ 13 | 14 | Once you enter the query and click the play button, graphQL playground will return the data you were looking for. 15 | 16 | 17 | 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. 18 | 19 | -------------------------------------------------------------------------------- /graphql/get-order-by-reference.graphql: -------------------------------------------------------------------------------- 1 | # How to get information on an order from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # The query must contain an id argument: 6 | # orderByID(id: "ORDER_ID") 7 | # ---------------------------------------------------------------------- 8 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 9 | 10 | 11 | query GetOrderByID( 12 | $orderID: ID! = "7e862ff63b4d70380b0b78ea5762e346ac1e711ec2516bc9994f92c7c19a3af6" 13 | ){ 14 | orderByID(id:$orderID){ 15 | id 16 | price 17 | timeInForce 18 | side 19 | size 20 | market{ 21 | id 22 | } 23 | updatedAt 24 | } 25 | } -------------------------------------------------------------------------------- /graphql/stream-orders-by-reference.graphql: -------------------------------------------------------------------------------- 1 | # How to stream orders from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # A party Id or market Id argument needs to passed in, like so: 6 | # orders(partyId: "PUBKEY") 7 | # orders(marketId: "MARKET_ID") 8 | # ---------------------------------------------------------------------- 9 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 10 | 11 | 12 | subscription StreamOrdersByReference( 13 | $partyId:ID!="644a1a8bb2fba612612dd6a5d400c49eb469d91dff777b0eda3f4cd554296759" 14 | ){ 15 | orders(partyId:$partyId){ 16 | id 17 | price 18 | timeInForce 19 | side 20 | marketId 21 | size 22 | } 23 | } -------------------------------------------------------------------------------- /graphql/get-trades-for-order.graphql: -------------------------------------------------------------------------------- 1 | # How to get information on trades for an order from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # The query must contain an id argument: 6 | # orderByID(id: "ORDER_ID") 7 | # ---------------------------------------------------------------------- 8 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 9 | 10 | 11 | query GetTradesForOrder($orderId: ID! = "7e862ff63b4d70380b0b78ea5762e346ac1e711ec2516bc9994f92c7c19a3af6") { 12 | orderByID(id: $orderId) { 13 | tradesConnection { 14 | edges { 15 | node { 16 | id 17 | price 18 | size 19 | } 20 | } 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /graphql/stream-market-data.graphql: -------------------------------------------------------------------------------- 1 | # How to stream market data from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # An array of market Ids must be passed in as an argument, as follows: 6 | # marketsData(marketIds: "MARKET_ID") 7 | # ---------------------------------------------------------------------- 8 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 9 | 10 | 11 | subscription StreamMarketData ($marketID: [ID!] = "e9ec6d5c46a7e7bcabf9ba7a893fa5a5eeeec08b731f06f7a6eb7bf0e605b829",){ 12 | marketsData(marketIds:$marketID){ 13 | bestBidPrice 14 | bestBidVolume 15 | bestOfferPrice 16 | bestOfferVolume 17 | midPrice 18 | timestamp 19 | marketTradingMode 20 | } 21 | } -------------------------------------------------------------------------------- /graphql/get-accounts-for-markets.graphql: -------------------------------------------------------------------------------- 1 | # How to get account information for a Market from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # The list can be filtered by various parameters, like so: 6 | # marketsConnection (id: "MARKET_ID") 7 | # ---------------------------------------------------------------------- 8 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 9 | 10 | query GetAccountsByMarket { 11 | marketsConnection { 12 | edges { 13 | node { 14 | accountsConnection { 15 | edges { 16 | node { 17 | balance 18 | asset { 19 | id 20 | } 21 | type 22 | } 23 | } 24 | } 25 | } 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /graphql/get-transfers.graphql: -------------------------------------------------------------------------------- 1 | # How to get withdrawal information from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # The list can be filtered by various parameters, like so: 6 | # partiesConnection (id: "PUBLIC_KEY") 7 | # ---------------------------------------------------------------------- 8 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 9 | 10 | query getTransfers { 11 | partiesConnection { 12 | edges { 13 | node { 14 | id 15 | transfersConnection { 16 | edges { 17 | node { 18 | id 19 | fromAccountType 20 | toAccountType 21 | from 22 | amount 23 | timestamp 24 | asset { 25 | id 26 | name 27 | } 28 | } 29 | } 30 | } 31 | } 32 | } 33 | } 34 | } 35 | 36 | -------------------------------------------------------------------------------- /graphql/get-delegations.graphql: -------------------------------------------------------------------------------- 1 | # How to get information on delegations from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # The list can be filtered by various parameters, like so: 6 | # delegationsConnection(partyId: "PUBLIC_KEY") 7 | # ---------------------------------------------------------------------- 8 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 9 | 10 | query getDelegations { 11 | nodesConnection { 12 | edges { 13 | node { 14 | delegationsConnection { 15 | edges { 16 | node { 17 | amount 18 | party { 19 | id 20 | } 21 | node { 22 | id 23 | } 24 | epoch 25 | } 26 | } 27 | } 28 | } 29 | } 30 | } 31 | } 32 | 33 | -------------------------------------------------------------------------------- /graphql/get-accounts-for-parties.graphql: -------------------------------------------------------------------------------- 1 | # How to get account information for a Party from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # The list can be filtered by various parameters, like so: 6 | # partiesConnection (id: "PUBLIC_KEY") 7 | # ---------------------------------------------------------------------- 8 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 9 | 10 | query GetAccountsByParty { 11 | partiesConnection { 12 | edges { 13 | node { 14 | id 15 | accountsConnection { 16 | edges { 17 | node { 18 | balance 19 | asset { 20 | id 21 | } 22 | type 23 | market { 24 | id 25 | } 26 | 27 | } 28 | } 29 | } 30 | } 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /graphql/get-candles.graphql: -------------------------------------------------------------------------------- 1 | # How to get information on candles from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # The list can be filtered by various parameters, like so: 6 | # marketsConnection (id: "MARKET_ID") 7 | # ---------------------------------------------------------------------- 8 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 9 | 10 | 11 | query getCandles { 12 | marketsConnection { 13 | edges { 14 | node { 15 | candlesConnection( 16 | since: "2022-11-12T15:49:00.69896836Z" 17 | interval: INTERVAL_I1H 18 | ) { 19 | edges { 20 | node { 21 | high 22 | low 23 | open 24 | close 25 | volume 26 | } 27 | } 28 | } 29 | } 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /graphql/get-positions.graphql: -------------------------------------------------------------------------------- 1 | # How to get account information for Positions from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # The list can be filtered by various parameters, like so: 6 | # partiesConnection (id: "PUBLIC_KEY") 7 | # ---------------------------------------------------------------------- 8 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 9 | 10 | query getPositions { 11 | partiesConnection { 12 | edges { 13 | node { 14 | id 15 | positionsConnection() { 16 | edges { 17 | node { 18 | market{id} 19 | openVolume 20 | realisedPNL 21 | averageEntryPrice 22 | unrealisedPNL 23 | realisedPNL 24 | } 25 | } 26 | } 27 | } 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /graphql/get-governance-votes.graphql: -------------------------------------------------------------------------------- 1 | # How to get information on governance votes from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # The list can be filtered by various parameters, like so: 6 | # partiesConnection (id: "PUBLIC_KEY") 7 | # ---------------------------------------------------------------------- 8 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 9 | 10 | 11 | query getGovernanceVotes { 12 | partiesConnection (id: "644a1a8bb2fba612612dd6a5d400c49eb469d91dff777b0eda3f4cd554296759") { 13 | edges { 14 | node { 15 | id 16 | votesConnection { 17 | edges { 18 | node { 19 | proposalId 20 | vote { 21 | value 22 | datetime 23 | } 24 | } 25 | } 26 | } 27 | } 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /graphql/get-balances.graphql: -------------------------------------------------------------------------------- 1 | # How to get information on asset balances from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # The list can be filtered by various parameters, like so: 6 | # partiesConnection (id: "PUBLIC_KEY") 7 | # accountsConnection (assetId: "ASSET_ID") 8 | # ---------------------------------------------------------------------- 9 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 10 | 11 | 12 | query getBalances { 13 | partiesConnection { 14 | edges { 15 | node { 16 | id 17 | accountsConnection { 18 | edges { 19 | node { 20 | asset { 21 | id 22 | symbol 23 | decimals 24 | } 25 | balance 26 | type 27 | } 28 | } 29 | } 30 | } 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /graphql/get-parties-accounts.graphql: -------------------------------------------------------------------------------- 1 | # How to get account information for a Party from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # The list can be filtered by various parameters, like so: 6 | # partiesConnection (id: "PUBLIC_KEY") 7 | # ---------------------------------------------------------------------- 8 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 9 | 10 | query getParties { 11 | partiesConnection { 12 | edges { 13 | node { 14 | id 15 | accountsConnection { 16 | edges { 17 | node { 18 | balance 19 | asset { 20 | id 21 | name 22 | symbol 23 | } 24 | type 25 | market { 26 | id 27 | } 28 | } 29 | } 30 | } 31 | } 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /graphql/get-rewards.graphql: -------------------------------------------------------------------------------- 1 | # How to get account information about Rewards from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # The list can be filtered by various parameters, like so: 6 | # partiesConnection (id: "PUBLIC_KEY") 7 | # ---------------------------------------------------------------------- 8 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 9 | 10 | query getRewards { 11 | partiesConnection { 12 | edges { 13 | node { 14 | rewardsConnection { 15 | edges { 16 | node { 17 | asset { 18 | id 19 | } 20 | marketId 21 | rewardType 22 | party { 23 | id 24 | } 25 | epoch { 26 | id 27 | } 28 | amount 29 | percentageOfTotal 30 | receivedAt 31 | } 32 | } 33 | } 34 | } 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Gobalsky Labs Ltd. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /graphql/get-withdrawals.graphql: -------------------------------------------------------------------------------- 1 | # How to get withdrawal information from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # The list can be filtered by various parameters, like so: 6 | # partiesConnection (id: "PUBLIC_KEY") 7 | # ---------------------------------------------------------------------- 8 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 9 | 10 | 11 | query getWithdrawals { 12 | partiesConnection { 13 | edges { 14 | node { 15 | id 16 | withdrawalsConnection { 17 | edges { 18 | node { 19 | amount 20 | createdTimestamp 21 | createdTimestamp 22 | status 23 | asset { 24 | id 25 | symbol 26 | source { 27 | __typename 28 | } 29 | } 30 | } 31 | } 32 | } 33 | } 34 | } 35 | } 36 | } 37 | 38 | -------------------------------------------------------------------------------- /graphql/get-deposits.graphql: -------------------------------------------------------------------------------- 1 | # How to get deposit information for a Party from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # The list can be filtered by various parameters, like so: 6 | # partiesConnection (id: "PUBLIC_KEY") 7 | # ---------------------------------------------------------------------- 8 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 9 | 10 | query getDeposits { 11 | partiesConnection { 12 | edges { 13 | node { 14 | id 15 | depositsConnection { 16 | edges { 17 | node { 18 | id 19 | amount 20 | createdTimestamp 21 | creditedTimestamp 22 | status 23 | asset { 24 | id 25 | symbol 26 | source { 27 | __typename 28 | } 29 | } 30 | } 31 | } 32 | } 33 | } 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /graphql/get-orders-and-trades-for-party.graphql: -------------------------------------------------------------------------------- 1 | # How to get information on an orders and trades for a party from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # The query must contain an id argument on the market field: 6 | # party(id: "PUBKEY") 7 | # ---------------------------------------------------------------------- 8 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 9 | 10 | 11 | query GetOrderTradesForParty($partyId: ID! = "644a1a8bb2fba612612dd6a5d400c49eb469d91dff777b0eda3f4cd554296759") { 12 | party(id: $partyId) { 13 | id 14 | ordersConnection { 15 | edges { 16 | node { 17 | id 18 | price 19 | side 20 | status 21 | tradesConnection { 22 | edges { 23 | node { 24 | id 25 | price 26 | size 27 | } 28 | } 29 | } 30 | } 31 | } 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /graphql/get-orders-and-trades-for-market.graphql: -------------------------------------------------------------------------------- 1 | # How to get information on an orders and trades on a market from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # The query must contain an id argument on the market field: 6 | # market(id: "MARKET_ID") 7 | # ---------------------------------------------------------------------- 8 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 9 | 10 | 11 | 12 | query GetOrderTradesForMarket($marketId: ID! = "ad2e531441c2e8a43e85423db399a4acc8f9a8a2376304a4c377d0da8eb31e80") { 13 | market(id: $marketId) { 14 | id 15 | ordersConnection { 16 | edges { 17 | node { 18 | id 19 | price 20 | side 21 | status 22 | tradesConnection { 23 | edges { 24 | node { 25 | id 26 | price 27 | size 28 | } 29 | } 30 | } 31 | } 32 | } 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /graphql/get-margin-levels.graphql: -------------------------------------------------------------------------------- 1 | # How to get information on margin levels from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # The list can be filtered by various parameters, like so: 6 | # partiesConnection (id: "PUBLIC_KEY") 7 | # marketsConnection (assetId: "MARKET_ID") 8 | # ---------------------------------------------------------------------- 9 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 10 | 11 | query getMarginLevels { 12 | partiesConnection { 13 | edges { 14 | node { 15 | marginsConnection { 16 | edges { 17 | node { 18 | market { 19 | id 20 | } 21 | asset { 22 | id 23 | } 24 | party { 25 | id 26 | } 27 | maintenanceLevel 28 | searchLevel 29 | initialLevel 30 | collateralReleaseLevel 31 | timestamp 32 | } 33 | } 34 | } 35 | } 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /graphql/Get-Markets.graphql: -------------------------------------------------------------------------------- 1 | # How to get information on markets from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # The list can be filtered by various parameters, like so: 6 | # marketsConnection (id: "MARKET_KEY") 7 | # accountsConnection (assetId: "ASSET_ID") 8 | # ---------------------------------------------------------------------- 9 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 10 | 11 | 12 | query getMarkets { 13 | marketsConnection { 14 | edges { 15 | node { 16 | id 17 | tradingMode 18 | marketTimestamps { 19 | proposed 20 | pending 21 | open 22 | close 23 | } 24 | depth { 25 | buy { 26 | volume 27 | numberOfOrders 28 | } 29 | sell { 30 | volume 31 | numberOfOrders 32 | } 33 | lastTrade { 34 | price 35 | size 36 | } 37 | } 38 | } 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /rest/get-checkpoints.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # G E T C H E C K P O I N T S # 5 | ############################################################################### 6 | 7 | # How to get checkpoint information from a Data Node using REST calls: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is supported [default page size is 1000] 10 | # -> Check out pagination.py for example usage 11 | # ---------------------------------------------------------------------- 12 | # For full details see the REST Reference API docs at https://docs.vega.xyz 13 | 14 | import json 15 | import requests 16 | import helpers 17 | 18 | # Load Vega node API v2 URL, this is set using 'source vega-config' 19 | # located in the root folder of the sample-api-scripts repository 20 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 21 | 22 | # __get_checkpoints: 23 | # Request a list of checkpoints for a Vega network 24 | url = f"{data_node_url_rest}/checkpoints" 25 | response = requests.get(url) 26 | helpers.check_response(response) 27 | print("Checkpoints for network:\n{}".format( 28 | json.dumps(response.json(), indent=2, sort_keys=True) 29 | )) 30 | # :get_checkpoints__ 31 | -------------------------------------------------------------------------------- /graphql/get-governance-proposals.graphql: -------------------------------------------------------------------------------- 1 | # How to get information on governance proposals from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # The list can be filtered by various parameters, like so: 6 | # proposalsConnection (proposalType: "PROPOSAL_TYPE") 7 | # ---------------------------------------------------------------------- 8 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 9 | 10 | query getGovernanceProposals { 11 | proposalsConnection { 12 | edges { 13 | node { 14 | id 15 | reference 16 | party { 17 | id 18 | } 19 | state 20 | datetime 21 | rationale { 22 | description 23 | } 24 | terms { 25 | closingDatetime 26 | enactmentDatetime 27 | } 28 | votes { 29 | yes { 30 | totalNumber 31 | totalWeight 32 | totalTokens 33 | } 34 | no { 35 | totalNumber 36 | totalWeight 37 | totalTokens 38 | } 39 | } 40 | rejectionReason 41 | errorDetails 42 | } 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /rest/get-statistics.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # V E G A S T A T I S T I C S # 5 | ############################################################################### 6 | 7 | # How to get statistics from a Vega Node using REST calls: 8 | # ---------------------------------------------------------------------- 9 | # For full details see the REST Reference API docs at https://docs.vega.xyz 10 | 11 | import json 12 | import requests 13 | import helpers 14 | 15 | # Load Vega node API v2 URL, this is set using 'source vega-config' 16 | # located in the root folder of the sample-api-scripts repository 17 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 18 | 19 | # Note: The statistics endpoint is proxied from Vega core so we must drop the api 20 | # v2 portion of the url for testnet configurations, other networks might need 21 | # a different url specified here... 22 | node_url_rest = data_node_url_rest.strip("/api/v2") 23 | 24 | # __get_statistics: 25 | # Request statistics for a node on Vega 26 | url = f"{node_url_rest}/statistics" 27 | response = requests.get(url) 28 | helpers.check_response(response) 29 | print("Node statistics:\n{}".format( 30 | json.dumps(response.json(), indent=2, sort_keys=True) 31 | )) 32 | # :get_statistics__ 33 | -------------------------------------------------------------------------------- /graphql/stream-events.graphql: -------------------------------------------------------------------------------- 1 | # How to stream events from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # There can be various arguments passed into busEvents, such as: 6 | # batchSize 7 | # marketId 8 | # partyId 9 | # ---------------------------------------------------------------------- 10 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 11 | 12 | 13 | subscription StreamEvents { 14 | busEvents(batchSize: 0, types: [Order], marketId: "'$marketID'") { 15 | type 16 | event { 17 | ... on Order { 18 | id 19 | side 20 | price 21 | timeInForce 22 | side 23 | market { 24 | id 25 | } 26 | size 27 | remaining 28 | party { 29 | id 30 | } 31 | createdAt 32 | expiresAt 33 | status 34 | reference 35 | tradesConnection { 36 | edges { 37 | node { 38 | id 39 | size 40 | aggressor 41 | } 42 | } 43 | } 44 | type 45 | rejectionReason 46 | version 47 | updatedAt 48 | } 49 | ... on TimeUpdate { 50 | timestamp 51 | } 52 | } 53 | } 54 | } -------------------------------------------------------------------------------- /graphql/get-liquidity-provisions-by-party.graphql: -------------------------------------------------------------------------------- 1 | # How to get liquidity provision information for a Party from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # The list can be filtered by various parameters, like so: 6 | # partiesConnection (id: "PUBLIC_KEY") 7 | # ---------------------------------------------------------------------- 8 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 9 | 10 | query getLPByParty { 11 | partiesConnection { 12 | edges { 13 | node { 14 | liquidityProvisionsConnection { 15 | edges { 16 | node { 17 | id 18 | market { 19 | id 20 | } 21 | commitmentAmount 22 | createdAt 23 | reference 24 | buys { 25 | liquidityOrder { 26 | reference 27 | proportion 28 | offset 29 | } 30 | } 31 | sells { 32 | liquidityOrder { 33 | reference 34 | proportion 35 | offset 36 | } 37 | } 38 | } 39 | } 40 | } 41 | } 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /graphql/get-liquidity-provisions-by-market.graphql: -------------------------------------------------------------------------------- 1 | # How to get liqudity provision information for a Market from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # The list can be filtered by various parameters, like so: 6 | # marketsConnection (id: "MARKET_ID") 7 | # ---------------------------------------------------------------------- 8 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 9 | 10 | 11 | query getLPByMarket { 12 | marketsConnection { 13 | edges { 14 | node { 15 | liquidityProvisionsConnection { 16 | edges { 17 | node { 18 | id 19 | market { 20 | id 21 | } 22 | commitmentAmount 23 | createdAt 24 | reference 25 | buys { 26 | liquidityOrder { 27 | reference 28 | proportion 29 | offset 30 | } 31 | } 32 | sells { 33 | liquidityOrder { 34 | reference 35 | proportion 36 | offset 37 | } 38 | } 39 | } 40 | } 41 | } 42 | } 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /rest/get-vega-time.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # G E T V E G A T I M E # 5 | ############################################################################### 6 | 7 | # How to get vega time (current block time) from a Data Node using REST calls: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is NOT supported on this endpoint. 10 | # ---------------------------------------------------------------------- 11 | # For full details see the REST Reference API docs at https://docs.vega.xyz 12 | 13 | import requests 14 | import helpers 15 | 16 | # Load Vega node API v2 URL, this is set using 'source vega-config' 17 | # located in the root folder of the sample-api-scripts repository 18 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 19 | 20 | # __get_time: 21 | # Request the latest timestamp in nanoseconds since epoch from the Vega network 22 | url = f"{data_node_url_rest}/vega/time" 23 | response = requests.get(url) 24 | helpers.check_response(response) 25 | 26 | # The "timestamp" field contains the resulting data we need. 27 | vega_time = response.json()["timestamp"] 28 | print("Vega time:\n{}".format(vega_time)) 29 | # :get_time__ 30 | 31 | # Print the human readable value of vega time (timestamp is a nanoseconds since epoch timestamp) 32 | print(helpers.nano_ts_to_human_date(float(vega_time))) 33 | -------------------------------------------------------------------------------- /rest/liquidity-commitments-list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import json 4 | import requests 5 | import helpers 6 | 7 | # Vega wallet interaction helper, see login.py for detail 8 | from login import token, pubkey 9 | 10 | # Load Vega node API v2 URL, this is set using 'source vega-config' 11 | # located in the root folder of the sample-api-scripts repository 12 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 13 | # Load Vega wallet server URL, set in same way as above 14 | wallet_server_url = helpers.get_from_env("WALLET_SERVER_URL") 15 | 16 | # Load Vega market id 17 | market_id = helpers.env_market_id() 18 | assert market_id != "" 19 | 20 | # Set market id in ENV or uncomment the line below to override market id directly 21 | market_id = "e503cadb437861037cddfd7263d25b69102098a97573db23f8e5fc320cea1ce9" 22 | 23 | ##################################################################################### 24 | # L I S T L I Q U I D I T Y P R O V I S I O N S # 25 | ##################################################################################### 26 | # __get_liquidity_provisions: 27 | # Request liquidity provisions for a party on a Vega network 28 | url = f"{data_node_url_rest}/liquidity/provisions?partyId={pubkey}" 29 | headers = {"Authorization": f"Bearer {token}"} 30 | response = requests.get(url) 31 | helpers.check_response(response) 32 | print("Liquidity Provisions for party:\n{}".format( 33 | json.dumps(response.json(), indent=2, sort_keys=True) 34 | )) 35 | 36 | -------------------------------------------------------------------------------- /rest/get-key-rotations.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # G E T K E Y R O T A T I O N S # 5 | ############################################################################### 6 | 7 | # How to get key rotation information from a Data Node using REST calls: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is supported [default page size is 1000] 10 | # -> Check out pagination.py for example usage 11 | # ---------------------------------------------------------------------- 12 | # The list can be filtered by various parameters, including: 13 | # nodeId: Vega node id 14 | # ---------------------------------------------------------------------- 15 | # For full details see the REST Reference API docs at https://docs.vega.xyz 16 | 17 | import json 18 | import requests 19 | import helpers 20 | 21 | # Load Vega node API v2 URL, this is set using 'source vega-config' 22 | # located in the root folder of the sample-api-scripts repository 23 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 24 | 25 | # __get_key_rotations: 26 | # Request a list of key rotations for a Vega network 27 | url = f"{data_node_url_rest}/vega/keys/rotations" 28 | response = requests.get(url) 29 | helpers.check_response(response) 30 | print("Key rotations for network:\n{}".format( 31 | json.dumps(response.json(), indent=2, sort_keys=True) 32 | )) 33 | # :get_key_rotations__ 34 | -------------------------------------------------------------------------------- /rest/get-market-depth.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # G E T M A R K E T D E P T H # 5 | ############################################################################### 6 | 7 | # How to get market depth information from a Data Node using REST calls: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is NOT supported on this endpoint. 10 | # ---------------------------------------------------------------------- 11 | # The following path parameter is required: 12 | # marketId: Vega market id 13 | # ---------------------------------------------------------------------- 14 | # The list can be filtered by various parameters, including: 15 | # maxDepth: Maximum number of levels to return 16 | # ---------------------------------------------------------------------- 17 | # For full details see the REST Reference API docs at https://docs.vega.xyz 18 | 19 | import json 20 | import requests 21 | import helpers 22 | 23 | # Load Vega node API v2 URL, this is set using 'source vega-config' 24 | # located in the root folder of the sample-api-scripts repository 25 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 26 | 27 | # Load Vega market id 28 | market_id = helpers.env_market_id() 29 | assert market_id != "" 30 | 31 | # __get_market_depth: 32 | # Request market depth for a specific market using a pre-defined market id 33 | url = f"{data_node_url_rest}/market/depth/{market_id}/latest?maxDepth=50" 34 | response = requests.get(url) 35 | helpers.check_response(response) 36 | print("Market depth for market:\n{}".format( 37 | json.dumps(response.json(), indent=2, sort_keys=True) 38 | )) 39 | # :get_market_depth__ 40 | -------------------------------------------------------------------------------- /rest/login.py: -------------------------------------------------------------------------------- 1 | import json 2 | import requests 3 | 4 | url = "http://localhost:1789/api/v2/requests" 5 | connect_payload = { 6 | "id": "1", 7 | "jsonrpc": "2.0", 8 | "method": "client.connect_wallet" 9 | } 10 | connect_headers = { 11 | 'Content-Type': 'application/json-rpc', 12 | 'Accept': 'application/json-rpc', 13 | 'Origin': 'application/json-rpc' 14 | } 15 | 16 | try: 17 | connectionResponse = requests.post(url, headers=connect_headers, json=connect_payload) 18 | connectionResponse.raise_for_status() # Raise an exception for unsuccessful responses 19 | except requests.exceptions.RequestException as e: 20 | print("Error connecting to the API - Make sure you have a wallet connection open and have imported the right vega-config:", str(e)) 21 | exit(1) 22 | 23 | authorize_payload = { 24 | "id": "1", 25 | "jsonrpc": "2.0", 26 | "method": "client.list_keys" 27 | } 28 | authorize_headers = { 29 | 'Content-Type': 'application/json-rpc', 30 | 'Accept': 'application/json-rpc', 31 | 'Origin': 'application/json-rpc', 32 | "Authorization": connectionResponse.headers["Authorization"] 33 | } 34 | 35 | try: 36 | authorizationResponse = requests.post(url, headers=authorize_headers, json=authorize_payload) 37 | authorizationResponse.raise_for_status() 38 | except requests.exceptions.RequestException as e: 39 | print("Error authorizing request:", str(e)) 40 | exit(1) 41 | 42 | try: 43 | token = connectionResponse.headers["Authorization"] 44 | authContent = json.loads(authorizationResponse.content) 45 | pubkey = authContent['result']['keys'][0]['publicKey'] 46 | except (KeyError, IndexError, json.JSONDecodeError) as e: 47 | print("Error parsing authorization response:", str(e)) 48 | exit(1) 49 | 50 | # Rest of your code... 51 | -------------------------------------------------------------------------------- /rest/get-staking-data.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # G E T S T A K I N G D A T A # 5 | ############################################################################### 6 | 7 | # How to get staking data information from a Data Node using REST calls: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is supported [default page size is 1000] 10 | # -> Check out pagination.py for example usage 11 | # ---------------------------------------------------------------------- 12 | # The following path parameter is required: 13 | # partyId: Vega party id (public key) 14 | # ---------------------------------------------------------------------- 15 | # For full details see the REST Reference API docs at https://docs.vega.xyz 16 | 17 | import json 18 | import requests 19 | import helpers 20 | 21 | # Load Vega node API v2 URL, this is set using 'source vega-config' 22 | # located in the root folder of the sample-api-scripts repository 23 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 24 | 25 | ############################################################################### 26 | # L I S T S T A K I N G D A T A # 27 | ############################################################################### 28 | 29 | party_id = helpers.env_party_id() 30 | assert party_id != "" 31 | 32 | # __get_staking_data: 33 | # Request all staking data for a Vega network 34 | url = f"{data_node_url_rest}/parties/{party_id}/stake" 35 | response = requests.get(url) 36 | helpers.check_response(response) 37 | print("Staking data for party:\n{}".format( 38 | json.dumps(response.json(), indent=2, sort_keys=True) 39 | )) 40 | # :get_staking_data__ 41 | -------------------------------------------------------------------------------- /rest/get-governance-votes.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # G E T G O V E R N A N C E V O T E S # 5 | ############################################################################### 6 | 7 | # How to get votes information from a Data Node using REST calls: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is supported [default page size is 1000] 10 | # -> Check out pagination.py for example usage 11 | # ---------------------------------------------------------------------- 12 | # The list must be filtered by at least one of the following parameters: 13 | # partyId: Vega party id (public key) 14 | # ---------------------------------------------------------------------- 15 | # For full details see the REST Reference API docs at https://docs.vega.xyz 16 | 17 | import json 18 | import requests 19 | import helpers 20 | 21 | # Load Vega node API v2 URL, this is set using 'source vega-config' 22 | # located in the root folder of the sample-api-scripts repository 23 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 24 | 25 | ############################################################################### 26 | # L I S T V O T E S # 27 | ############################################################################### 28 | 29 | # Load Vega party id 30 | party_id = helpers.env_party_id() 31 | assert party_id != "" 32 | 33 | # __get_votes: 34 | # Request vote data for a Vega network 35 | url = f"{data_node_url_rest}/votes?partyId={party_id}" 36 | print(url) 37 | response = requests.get(url) 38 | helpers.check_response(response) 39 | print("Governance (votes) data for network:\n{}".format( 40 | json.dumps(response.json(), indent=2, sort_keys=True) 41 | )) 42 | # :get_votes__ 43 | -------------------------------------------------------------------------------- /rest/get-positions.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # G E T P O S I T I O N S # 5 | ############################################################################### 6 | 7 | # How to get rewards information from a Data Node using REST calls: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is supported [default page size is 1000] 10 | # -> Check out pagination.py for example usage 11 | # ---------------------------------------------------------------------- 12 | # The list can be filtered by various parameters, including: 13 | # partyId: Vega party id (public key) 14 | # marketId: Vega market id 15 | # ---------------------------------------------------------------------- 16 | # For full details see the REST Reference API docs at https://docs.vega.xyz 17 | 18 | import json 19 | import requests 20 | import helpers 21 | 22 | # Load Vega node API v2 URL, this is set using 'source vega-config' 23 | # located in the root folder of the sample-api-scripts repository 24 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 25 | 26 | # Load Vega market and party ids 27 | party_id = helpers.env_party_id() 28 | market_id = helpers.env_market_id() 29 | assert party_id != "" 30 | assert market_id != "" 31 | 32 | ############################################################################### 33 | # L I S T P O S I T I O N S # 34 | ############################################################################### 35 | 36 | # __get_positions: 37 | # Request a list of trading positions for a Vega network 38 | url = f"{data_node_url_rest}/positions?partyId={party_id}&marketId={market_id}" 39 | response = requests.get(url) 40 | helpers.check_response(response) 41 | print("Positions for party:\n{}".format( 42 | json.dumps(response.json(), indent=2, sort_keys=True) 43 | )) 44 | # :get_positions__ 45 | -------------------------------------------------------------------------------- /rest/get-network-data-and-limits.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # G E T N E T W O R K D A T A / L I M I T S # 5 | ############################################################################### 6 | 7 | # How to get network data/limits information from a Data Node using REST calls: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is NOT supported on these endpoints. 10 | # ---------------------------------------------------------------------- 11 | # For full details see the REST Reference API docs at https://docs.vega.xyz 12 | 13 | import json 14 | import requests 15 | import helpers 16 | 17 | # Load Vega node API v2 URL, this is set using 'source vega-config' 18 | # located in the root folder of the sample-api-scripts repository 19 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 20 | 21 | ############################################################################### 22 | # N E T W O R K D A T A # 23 | ############################################################################### 24 | 25 | # __get_network_data: 26 | # Request all data for a Vega network 27 | url = f"{data_node_url_rest}/network/data" 28 | response = requests.get(url) 29 | helpers.check_response(response) 30 | print("Network data:\n{}".format( 31 | json.dumps(response.json(), indent=2, sort_keys=True) 32 | )) 33 | # :get_network_data__ 34 | 35 | ############################################################################### 36 | # N E T W O R K L I M I T S # 37 | ############################################################################### 38 | 39 | # __get_network_limits: 40 | # Request all limits for a Vega network 41 | url = f"{data_node_url_rest}/network/limits" 42 | response = requests.get(url) 43 | helpers.check_response(response) 44 | print("Network limits:\n{}".format( 45 | json.dumps(response.json(), indent=2, sort_keys=True) 46 | )) 47 | # :get_network_limits__ 48 | -------------------------------------------------------------------------------- /graphql/get-market-data.graphql: -------------------------------------------------------------------------------- 1 | # How to get market data history from a Data Node using GraphQL calls: 2 | # ---------------------------------------------------------------------- 3 | # Cursor pagination is supported 4 | # ---------------------------------------------------------------------- 5 | # The query must contain an id argument: 6 | # getMarketDataHistoryConnectionByID(id: "MARKET_ID") 7 | # ---------------------------------------------------------------------- 8 | # For full details see the GraphQL Reference API docs at https://docs.vega.xyz 9 | 10 | 11 | query getMarketData { 12 | getMarketDataHistoryConnectionByID( 13 | id: "e9ec6d5c46a7e7bcabf9ba7a893fa5a5eeeec08b731f06f7a6eb7bf0e605b829" 14 | ) { 15 | edges { 16 | node { 17 | market { 18 | id 19 | } 20 | markPrice 21 | bestBidPrice 22 | bestBidVolume 23 | bestOfferPrice 24 | bestOfferVolume 25 | bestStaticBidPrice 26 | bestStaticBidVolume 27 | bestStaticOfferPrice 28 | bestStaticOfferVolume 29 | midPrice 30 | staticMidPrice 31 | timestamp 32 | openInterest 33 | auctionEnd 34 | auctionStart 35 | indicativePrice 36 | indicativeVolume 37 | marketTradingMode 38 | trigger 39 | extensionTrigger 40 | targetStake 41 | suppliedStake 42 | commitments { 43 | buys { 44 | order { 45 | id 46 | price 47 | timeInForce 48 | side 49 | size 50 | remaining 51 | party { 52 | id 53 | } 54 | } 55 | } 56 | sells { 57 | order { 58 | id 59 | price 60 | timeInForce 61 | side 62 | size 63 | remaining 64 | party { 65 | id 66 | } 67 | } 68 | } 69 | } 70 | priceMonitoringBounds { 71 | minValidPrice 72 | maxValidPrice 73 | } 74 | marketValueProxy 75 | liquidityProviderFeeShare { 76 | party { 77 | id 78 | } 79 | equityLikeShare 80 | averageEntryValuation 81 | } 82 | } 83 | } 84 | } 85 | } -------------------------------------------------------------------------------- /rest/get-network-parameters.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # G E T N E T W O R K P A R A M E T E R S # 5 | ############################################################################### 6 | 7 | # How to get Vega network parameters from a Data Node using REST calls: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is supported [default page size is 1000] 10 | # -> Check out pagination.py for example usage 11 | # ---------------------------------------------------------------------- 12 | # For full details see the REST Reference API docs at https://docs.vega.xyz 13 | 14 | import requests 15 | import helpers 16 | 17 | # Load Vega data node API v2 URL, this is set using 'source vega-config' 18 | # located in the root folder of the sample-api-scripts repository 19 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 20 | 21 | ############################################################################### 22 | # L I S T N E T W O R K P A R A M E T E R S # 23 | ############################################################################### 24 | 25 | # __get_network_params: 26 | # Request a list of network parameters configured on a Vega network 27 | url = f"{data_node_url_rest}/network/parameters" 28 | response = requests.get(url) 29 | helpers.check_response(response) 30 | print("Network parameters:\n") 31 | for edge in response.json()['networkParameters']['edges']: 32 | print(edge['node']) 33 | # :get_network_params__ 34 | 35 | parameter_key = response.json()['networkParameters']['edges'][0]['node']['key'] 36 | assert parameter_key != "" 37 | 38 | print() 39 | print(f"Selected parameter key: {parameter_key}") 40 | print() 41 | 42 | ############################################################################### 43 | # S I N G L E N E T W O R K P A R A M E T E R # 44 | ############################################################################### 45 | 46 | # __get_network_param: 47 | # Request a specific network parameter from those configured on a Vega network 48 | url = f"{data_node_url_rest}/network/parameters/{parameter_key}" 49 | response = requests.get(url) 50 | helpers.check_response(response) 51 | print(f"Network parameter for key {parameter_key}:\n") 52 | print(response.json()) 53 | # :get_network_param__ 54 | -------------------------------------------------------------------------------- /rest/get-epochs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # G E T E P O C H S D A T A # 5 | ############################################################################### 6 | 7 | # How to get epoch information from a Data Node using REST calls: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is NOT supported on this endpoint. 10 | # ---------------------------------------------------------------------- 11 | # The list can be optionally filtered by: 12 | # id: Vega epoch id (also referred to as the epochSeq field) 13 | # ---------------------------------------------------------------------- 14 | # For full details see the REST Reference API docs at https://docs.vega.xyz 15 | 16 | import json 17 | import requests 18 | import helpers 19 | 20 | # Load Vega node API v2 URL, this is set using 'source vega-config' 21 | # located in the root folder of the sample-api-scripts repository 22 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 23 | 24 | ############################################################################### 25 | # L I S T E P O C H S # 26 | ############################################################################### 27 | 28 | # __get_epochs: 29 | # Request all epoch data for a Vega network 30 | url = f"{data_node_url_rest}/epoch" 31 | response = requests.get(url) 32 | helpers.check_response(response) 33 | print("Epoch data for network:\n{}".format( 34 | json.dumps(response.json(), indent=2, sort_keys=True) 35 | )) 36 | # :get_epochs__ 37 | 38 | # Find the first delegation in the list (above) 39 | first_delegation = response.json()["epoch"]["delegations"][0] 40 | epoch_id = first_delegation["epochSeq"] 41 | 42 | ############################################################################### 43 | # E P O C H B Y I D # 44 | ############################################################################### 45 | 46 | # __get_epochs_by_id: 47 | # Request epoch data for a specific epoch id 48 | url = f"{data_node_url_rest}/epoch?id={epoch_id}" 49 | response = requests.get(url) 50 | helpers.check_response(response) 51 | print("Epoch data for epoch id:\n{}".format( 52 | json.dumps(response.json(), indent=2, sort_keys=True) 53 | )) 54 | # :get_epochs_by_id__ 55 | -------------------------------------------------------------------------------- /rest/get-markets.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # G E T M A R K E T S # 5 | ############################################################################### 6 | 7 | # How to get market information from a Data Node using REST calls: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is supported [default page size is 1000] 10 | # -> Check out pagination.py for example usage 11 | # ---------------------------------------------------------------------- 12 | # For full details see the REST Reference API docs at https://docs.vega.xyz 13 | 14 | import json 15 | import requests 16 | import helpers 17 | 18 | # Load Vega node API v2 URL, this is set using 'source vega-config' 19 | # located in the root folder of the sample-api-scripts repository 20 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 21 | 22 | ############################################################################### 23 | # L I S T M A R K E T S # 24 | ############################################################################### 25 | 26 | # __get_markets: 27 | # Request a list of markets on a Vega network 28 | url = f"{data_node_url_rest}/markets" 29 | print(url) 30 | response = requests.get(url) 31 | helpers.check_response(response) 32 | response_json = response.json() 33 | print("Markets:\n{}".format( 34 | json.dumps(response_json, indent=2, sort_keys=True) 35 | )) 36 | # :get_markets__ 37 | 38 | # Find the first market in the list (above) if it exists 39 | market_id = "6a834328d835ca79880dfc238a989c238fe32a62562690d717ab1ff42ad5004d" 40 | if helpers.check_nested_response(response, "markets"): 41 | first_market = helpers.get_nested_response(response, "markets")[0]["node"] 42 | market_id = first_market["id"] 43 | 44 | ############################################################################### 45 | # M A R K E T B Y I D # 46 | ############################################################################### 47 | 48 | # Hint: Requesting a market by ID is a different REST route to listing markets 49 | # and therefore it does not have filters or pagination (unlike the above request) 50 | 51 | # __get_market: 52 | # Request a specific market using a pre-defined market id 53 | url = f"{data_node_url_rest}/market/{market_id}" 54 | response = requests.get(url) 55 | helpers.check_response(response) 56 | print("Market:\n{}".format( 57 | json.dumps(response.json(), indent=2, sort_keys=True))) 58 | # :get_market__ 59 | -------------------------------------------------------------------------------- /rest/liquidity-commitment-cancel.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import json 4 | import time 5 | import requests 6 | import helpers 7 | 8 | # Vega wallet interaction helper, see login.py for detail 9 | from login import token, pubkey 10 | 11 | # Load Vega node API v2 URL, this is set using 'source vega-config' 12 | # located in the root folder of the sample-api-scripts repository 13 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 14 | # Load Vega wallet server URL, set in same way as above 15 | wallet_server_url = helpers.get_from_env("WALLET_SERVER_URL") 16 | 17 | # Load Vega market id 18 | market_id = helpers.env_market_id() 19 | assert market_id != "" 20 | 21 | # Set market id in ENV or uncomment the line below to override market id directly 22 | market_id = "e503cadb437861037cddfd7263d25b69102098a97573db23f8e5fc320cea1ce9" 23 | 24 | ##################################################################################### 25 | # 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 # 26 | ##################################################################################### 27 | 28 | # __cancel_liquidity_commitment: 29 | # Compose a liquidity commitment cancellation command 30 | # Hint: The transaction may get rejected if removing previously supplied liquidity 31 | # will result in insufficient liquidity for the market to operate 32 | submission = { 33 | "liquidityProvisionCancellation": { 34 | "marketId": market_id, 35 | }, 36 | "pubKey": pubkey, 37 | "propagate": True 38 | } 39 | # :cancel_liquidity_commitment__ 40 | 41 | print("Liquidity commitment cancellation:\n{}".format( 42 | json.dumps(submission, indent=2, sort_keys=True) 43 | )) 44 | 45 | # __sign_tx_liquidity_cancel: 46 | # Sign the transaction with an order submission command 47 | url = "http://localhost:1789/api/v2/requests" 48 | 49 | payload1 = { 50 | "id": "1", 51 | "jsonrpc": "2.0", 52 | "method": "client.send_transaction", 53 | "params": { 54 | "publicKey": pubkey, 55 | "sendingMode": "TYPE_SYNC", 56 | "transaction": submission 57 | } 58 | } 59 | 60 | payload = json.dumps(payload1) 61 | 62 | headers = { 63 | 'Content-Type': 'application/json-rpc', 64 | 'Accept': 'application/json-rpc', 65 | 'Origin': 'application/json-rpc', 66 | 'Authorization': f'{token}' 67 | } 68 | 69 | response = requests.request("POST", url, headers=headers, data=payload) 70 | 71 | print(response.text) 72 | # :sign_tx_liquidity_cancel__ 73 | 74 | print("Signed liquidity commitment cancellation and sent to Vega") 75 | 76 | # Wait for cancellation to be included in a block 77 | print("Waiting for blockchain...") 78 | time.sleep(3) 79 | -------------------------------------------------------------------------------- /rest/stream-governance.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # S T R E A M G O V E R N A N C E # 5 | ############################################################################### 6 | 7 | # How to stream governance information from a Data Node using Websockets: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is not supported, but the initial snapshot may contain 10 | # multiple pages. Date Range is not supported, this is a realtime stream. 11 | # ---------------------------------------------------------------------- 12 | # The stream can be filtered the following parameter: 13 | # partyId: Vega party id (public key) 14 | # ---------------------------------------------------------------------- 15 | # For full details see the REST Reference API docs at https://docs.vega.xyz 16 | 17 | import websocket 18 | import threading 19 | import json 20 | import helpers 21 | 22 | # Load Vega node API v2 URL, this is set using 'source vega-config' 23 | # located in the root folder of the sample-api-scripts repository 24 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 25 | 26 | # Connect to the data node with a WSS based endpoint, this is not a HTTPS:// url 27 | url = f"{data_node_url_rest}/stream/governance".replace("https://", "wss://") 28 | res = [] 29 | event = threading.Event() 30 | 31 | # __stream_governance: 32 | # Request a stream of governance data on a Vega network 33 | 34 | def on_message(wsa, line): 35 | # Vega data-node v2 returns the json line by line so we need to wait 36 | # for a full structure before we can parse to valid JSON in python 37 | if line == "{": 38 | del res[:] 39 | res.append(line) 40 | elif line == "}": 41 | res.append(line) 42 | obj = json.loads(''.join(res)) 43 | if "governance" in obj["result"]: 44 | print(f"Governance data found:") 45 | print(obj["result"]["governance"]) 46 | else: 47 | res.append(line) 48 | 49 | print(line) 50 | 51 | def on_error(wsa, error): 52 | print(error) 53 | 54 | 55 | def on_close(wsa, close_status_code, close_msg): 56 | print(f"Governance stream closed: {url}") 57 | 58 | 59 | def on_open(wsa): 60 | print(f"Governance stream open: {url}") 61 | 62 | 63 | def timeout(): 64 | while not event.wait(timeout=30): 65 | ws.close() 66 | exit(1) 67 | 68 | 69 | thread = threading.Thread(target=timeout) 70 | thread.start() 71 | 72 | ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) 73 | ws.on_open = on_open 74 | ws.run_forever() 75 | # :stream_governance__ 76 | -------------------------------------------------------------------------------- /rest/README.md: -------------------------------------------------------------------------------- 1 | # REST API samples in Python 2 | 3 | The files here represent how to call various aspects of the Vega data-node REST APIs and Wallet APIs programmatically using Python. 4 | 5 | **REFERENCE APIs:** Reference API documentation for the REST APIs can be found at: https://docs.vega.xyz/ 6 | 7 | 8 | ## Prerequisites 9 | 10 | *Ensure you have set up `vega-config` on your environment as explained in the main [Getting Started](../) guides.* 11 | 12 | The following tools or applications are required for these scripts to work. Here are the commands to check they are installed on your system: 13 | 14 | 1. python3 15 | ```bash 16 | python3 --version 17 | ``` 18 | 1. pip3 19 | ```bash 20 | pip3 --version 21 | ``` 22 | To make sure we have all the correct libraries you can use pip with the requirements.txt to install them all 23 | ```bash 24 | pip3 install -r requirements.txt 25 | ``` 26 | 27 | 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. 28 | 29 | ```bash 30 | python3 get-vega-time.py 31 | ``` 32 | 33 | 1. Import the appropriate vega-config into your local environment for the network you want to test against (default vega-config is Fairground testnet). 34 | 35 | ```bash 36 | source vega-config 37 | ``` 38 | 39 | 1. wallet 40 | 41 | 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. 42 | 43 | ```bash 44 | python3 login.py 45 | ``` 46 | 47 | 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 48 | 49 | To logout or remove the token, simply run the logout script or delete `token.temp` 50 | 51 | ```bash 52 | python3 logout.py 53 | ``` 54 | 55 | ## How to run a script 56 | 57 | All the source files are named logically so that the caller can read the file tree and understand the actions performed within. 58 | Hint: If you do not require all of the actions within a script, simply comment them out. 59 | 60 | If the prerequisites are installed and set up correctly you can run a simple query or 'read' action script as follows: 61 | 62 | ```bash 63 | python3 get-statistics.py 64 | ``` 65 | 66 | To run a 'write' action, sending a command into Vega, make sure you are authenticated first and have edited the file to your requirements: 67 | 68 | ```bash 69 | python3 submit-amend-cancel-order.py 70 | ``` 71 | 72 | Finally to run a streaming action (the code is set to exit after 30 seconds): 73 | 74 | ```bash 75 | python3 stream-market-data.py 76 | ``` 77 | 78 | -------------------------------------------------------------------------------- /rest/get-assets.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # G E T A S S E T S # 5 | ############################################################################### 6 | 7 | # How to get Vega asset information from a Data Node using REST calls: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is supported [default page size is 1000] 10 | # -> Check out pagination.py for example usage 11 | # ---------------------------------------------------------------------- 12 | # The list can be filtered by various parameters, including: 13 | # assetId: Vega asset id 14 | # ---------------------------------------------------------------------- 15 | # For full details see the REST Reference API docs at https://docs.vega.xyz 16 | 17 | import json 18 | import requests 19 | import helpers 20 | import sys 21 | 22 | # Load Vega data node API v2 URL, this is set using 'source vega-config' 23 | # located in the root folder of the sample-api-scripts repository 24 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 25 | 26 | ############################################################################### 27 | # L I S T A S S E T S # 28 | ############################################################################### 29 | 30 | # __get_assets: 31 | # Request a list of assets available and select the first one 32 | url = f"{data_node_url_rest}/assets" 33 | response = requests.get(url) 34 | helpers.check_response(response) 35 | print("Assets:\n{}".format( 36 | json.dumps(response.json(), indent=2, sort_keys=True))) 37 | # :get_assets__ 38 | 39 | # Find asset with name tDAI (available on Fairground Testnet) 40 | asset_id = None 41 | assets = response.json()["assets"]["edges"] 42 | for asset in assets: 43 | if asset["node"]["details"]["symbol"] == "tDAI": 44 | print("Found an asset with symbol tDAI") 45 | asset_id = asset["node"]["id"] 46 | break 47 | 48 | if asset_id is None: 49 | print("tDAI asset not found on specified Vega network" ) 50 | sys.exit(1) 51 | 52 | ############################################################################### 53 | # S I N G L E A S S E T # 54 | ############################################################################### 55 | 56 | # __get_asset: 57 | # Request a specific asset using a pre-defined asset id 58 | url = f"{data_node_url_rest}/asset/{asset_id}" 59 | response = requests.get(url) 60 | helpers.check_response(response) 61 | print("Asset:\n{}".format( 62 | json.dumps(response.json(), indent=2, sort_keys=True))) 63 | # :get_asset__ 64 | -------------------------------------------------------------------------------- /rest/get-governance-proposals.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # G E T G O V E R N A N C E P R O P O S A L S # 5 | ############################################################################### 6 | 7 | # How to get proposals information from a Data Node using REST calls: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is supported [default page size is 1000] 10 | # -> Check out pagination.py for example usage 11 | # ---------------------------------------------------------------------- 12 | # The list can be filtered by various parameters, including: 13 | # proposalState: Proposal state e.g. STATE_OPEN 14 | # proposalType: Proposal type e.g. TYPE_NEW_MARKET 15 | # proposerPartyId: Party id (public key) of a proposer 16 | # proposalReference: Custom proposal reference (set by the proposer) 17 | # ---------------------------------------------------------------------- 18 | # For full details see the REST Reference API docs at https://docs.vega.xyz 19 | 20 | import json 21 | import requests 22 | import helpers 23 | 24 | # Load Vega node API v2 URL, this is set using 'source vega-config' 25 | # located in the root folder of the sample-api-scripts repository 26 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 27 | 28 | ############################################################################### 29 | # L I S T P R O P O S A L S # 30 | ############################################################################### 31 | 32 | # __get_proposals: 33 | # Request proposal data for a Vega network 34 | url = f"{data_node_url_rest}/governances" 35 | response = requests.get(url) 36 | helpers.check_response(response) 37 | print("Governance (proposals) data for network:\n{}".format( 38 | json.dumps(response.json(), indent=2, sort_keys=True) 39 | )) 40 | # :get_proposals__ 41 | 42 | # Find the first delegation in the list (above) 43 | first_proposal = response.json()["connection"]["edges"][0]["node"]["proposal"] 44 | proposal_id = first_proposal["id"] 45 | 46 | ############################################################################### 47 | # P R O P O S A L B Y I D # 48 | ############################################################################### 49 | 50 | print(f"Governance proposal for id: {proposal_id}") 51 | 52 | # __get_proposal_by_id: 53 | # Request proposal data for a specific proposal id 54 | url = f"{data_node_url_rest}/governance?proposalId={proposal_id}" 55 | response = requests.get(url) 56 | helpers.check_response(response) 57 | print("Proposal:\n{}".format( 58 | json.dumps(response.json(), indent=2, sort_keys=True) 59 | )) 60 | # :get_proposal_by_id__ 61 | -------------------------------------------------------------------------------- /rest/stream-delegations.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # S T R E A M D E L E G A T I O N S # 5 | ############################################################################### 6 | 7 | # How to stream delegation information from a Data Node using Websockets: 8 | # ---------------------------------------------------------------------- 9 | # Pagination and Date Range are not supported, this is a realtime stream. 10 | # ---------------------------------------------------------------------- 11 | # The stream can be filtered by various parameters, including: 12 | # partyId: Vega party id (public key) 13 | # nodeId: Vega node id 14 | # > Include none, one or both to refine the stream of data from Vega 15 | # ---------------------------------------------------------------------- 16 | # For full details see the REST Reference API docs at https://docs.vega.xyz 17 | 18 | import websocket 19 | import threading 20 | import json 21 | import helpers 22 | 23 | # Load Vega node API v2 URL, this is set using 'source vega-config' 24 | # located in the root folder of the sample-api-scripts repository 25 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 26 | 27 | # Connect to the data node with a WSS based endpoint, this is not a HTTPS:// url 28 | # Hint: to include/filter data from a party add the param `partyId` or add 29 | # param `nodeId` to filter by Vega node 30 | # e.g. ?nodeId=xxx&partyId=yyy 31 | url = f"{data_node_url_rest}/stream/delegations".replace("https://", "wss://") 32 | res = [] 33 | event = threading.Event() 34 | 35 | # __stream_delegations: 36 | # Request a stream of delegation updates on a Vega network 37 | 38 | def on_message(wsa, line): 39 | # Vega data-node v2 returns the json line by line so we need to wait 40 | # for a full structure before we can parse to valid JSON in python 41 | if line == "{": 42 | del res[:] 43 | res.append(line) 44 | elif line == "}": 45 | res.append(line) 46 | obj = json.loads(''.join(res)) 47 | if "delegation" in obj["result"]: 48 | print(f"Delegation data found:") 49 | print(obj["result"]["delegation"]) 50 | else: 51 | res.append(line) 52 | 53 | def on_error(wsa, error): 54 | print(error) 55 | 56 | 57 | def on_close(wsa, close_status_code, close_msg): 58 | print(f"Delegations stream closed: {url}") 59 | 60 | 61 | def on_open(wsa): 62 | print(f"Delegations stream open: {url}") 63 | 64 | 65 | def timeout(): 66 | while not event.wait(timeout=30): 67 | ws.close() 68 | exit(1) 69 | 70 | 71 | thread = threading.Thread(target=timeout) 72 | thread.start() 73 | 74 | ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) 75 | ws.on_open = on_open 76 | ws.run_forever() 77 | # :stream_delegations__ 78 | -------------------------------------------------------------------------------- /rest/get-ledger-entries.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # G E T L E D G E R E N T R I E S # 5 | ############################################################################### 6 | 7 | # How to get ledger entries from a Data Node using REST calls: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is supported [default page size is 1000] 10 | # -> Check out pagination.py for example usage 11 | # ---------------------------------------------------------------------- 12 | # The list can be filtered by various parameters, including: 13 | 14 | # ---------------------------------------------------------------------- 15 | # For full details see the REST Reference API docs at https://docs.vega.xyz 16 | 17 | import json 18 | import requests 19 | import helpers 20 | 21 | # Vega wallet interaction helper, see login.py for detail 22 | # from login import pubkey 23 | 24 | # Load Vega data node API v2 URL, this is set using 'source vega-config' 25 | # located in the root folder of the sample-api-scripts repository 26 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 27 | 28 | ############################################################################### 29 | # L I S T L E D G E R E N T R I E S # 30 | ############################################################################### 31 | 32 | party_id = helpers.env_party_id() 33 | assert party_id != "" 34 | party_id = "d8742dbe34198241b96381012be71615a48da2b1c60f76f25ae5ed87fea9c500" 35 | 36 | # __get_ledger_entries_from_account: 37 | # List ledger entries with filtering on the sending account (accountFrom...) 38 | url = f"{data_node_url_rest}/ledgerentry/history?filter.accountFromFilter.partyIds={party_id}" 39 | print(url) 40 | response = requests.get(url) 41 | helpers.check_response(response) 42 | response_json = response.json() 43 | print("Ledger entries (sending account):\n{}".format( 44 | json.dumps(response_json, indent=2, sort_keys=True) 45 | )) 46 | # :get_ledger_entries_from_account__ 47 | 48 | 49 | # __get_ledger_entries_to_account: 50 | # List ledger entries with filtering on the receiving account (accountFrom...) 51 | url = f"{data_node_url_rest}/ledgerentry/history?filter.accountToFilter.partyIds={party_id}" 52 | print(url) 53 | response = requests.get(url) 54 | helpers.check_response(response) 55 | response_json = response.json() 56 | print("Ledger entries (receiving account):\n{}".format( 57 | json.dumps(response_json, indent=2, sort_keys=True) 58 | )) 59 | # :get_ledger_entries_to_account__ 60 | 61 | # todo: can also refine further with a particular asset id, market id or account type 62 | # todo: can also refine further with a particular asset id, market id or account type 63 | # todo: list ledger entries with filtering on the sending AND receiving account 64 | # todo: list ledger entries with filtering on the transfer type (on top of above or as a standalone) 65 | -------------------------------------------------------------------------------- /rest/stream-votes.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # S T R E A M V O T E S # 5 | ############################################################################### 6 | 7 | # How to stream vote information from a Data Node using Websockets: 8 | # ---------------------------------------------------------------------- 9 | # Pagination and Date Range are not supported, this is a realtime stream. 10 | # ---------------------------------------------------------------------- 11 | # The stream can be filtered by various parameters, including: 12 | # partyId: Vega party id (public key) 13 | # proposalId: Optional proposal id 14 | # > Include one or both to refine the stream of data from Vega 15 | # ---------------------------------------------------------------------- 16 | # For full details see the REST Reference API docs at https://docs.vega.xyz 17 | 18 | import websocket 19 | import threading 20 | import json 21 | import helpers 22 | 23 | # Load Vega node API v2 URL, this is set using 'source vega-config' 24 | # located in the root folder of the sample-api-scripts repository 25 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 26 | 27 | # Load Vega party id 28 | party_id = helpers.env_party_id() 29 | assert party_id != "" 30 | 31 | # Connect to the data node with a WSS based endpoint, this is not a HTTPS:// url 32 | # Hint: to include/filter data from a proposal id add the param `proposalId` 33 | # e.g. ?partyId=xxx&proposalId=yyy 34 | url = f"{data_node_url_rest}/stream/votes?partyId={party_id}".replace("https://", "wss://") 35 | res = [] 36 | event = threading.Event() 37 | 38 | # __stream_votes_by_party: 39 | # Request a stream of votes for a party id on a Vega network 40 | 41 | def on_message(wsa, line): 42 | # Vega data-node v2 returns the json line by line so we need to wait 43 | # for a full structure before we can parse to valid JSON in python 44 | if line == "{": 45 | del res[:] 46 | res.append(line) 47 | elif line == "}": 48 | res.append(line) 49 | obj = json.loads(''.join(res)) 50 | if "vote" in obj["result"]: 51 | # Result contains reward data for party 52 | print(f"Vote data found:") 53 | print(obj["result"]["vote"]) 54 | else: 55 | res.append(line) 56 | 57 | 58 | def on_error(wsa, error): 59 | print(error) 60 | 61 | 62 | def on_close(wsa, close_status_code, close_msg): 63 | print(f"Votes stream closed: {url}") 64 | 65 | 66 | def on_open(wsa): 67 | print(f"Votes stream open: {url}") 68 | 69 | 70 | def timeout(): 71 | while not event.wait(timeout=30): 72 | ws.close() 73 | exit(1) 74 | 75 | 76 | thread = threading.Thread(target=timeout) 77 | thread.start() 78 | 79 | ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) 80 | ws.on_open = on_open 81 | ws.run_forever() 82 | # :stream_votes_by_party__ 83 | -------------------------------------------------------------------------------- /rest/stream-rewards.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # S T R E A M R E W A R D S # 5 | ############################################################################### 6 | 7 | # How to stream reward information from a Data Node using Websockets: 8 | # ---------------------------------------------------------------------- 9 | # Pagination and Date Range are not supported, this is a realtime stream. 10 | # ---------------------------------------------------------------------- 11 | # The stream can be filtered by various parameters, including: 12 | # partyId: Vega party id (public key) 13 | # marketId: Vega market id 14 | # > Include none, one or both to refine the stream of data from Vega 15 | # ---------------------------------------------------------------------- 16 | # For full details see the REST Reference API docs at https://docs.vega.xyz 17 | 18 | import websocket 19 | import threading 20 | import json 21 | import helpers 22 | 23 | # Load Vega node API v2 URL, this is set using 'source vega-config' 24 | # located in the root folder of the sample-api-scripts repository 25 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 26 | 27 | # Load Vega market id 28 | market_id = helpers.env_market_id() 29 | assert market_id != "" 30 | 31 | # Load Vega party id 32 | party_id = helpers.env_party_id() 33 | assert party_id != "" 34 | 35 | # Connect to the data node with a WSS based endpoint, this is not a HTTPS:// url 36 | # Hint: to include/filter data from a party add the param `partyId` 37 | # e.g. ?assetId=xxx&partyId=yyy 38 | url = f"{data_node_url_rest}/stream/rewards?partyId={party_id}".replace("https://", "wss://") 39 | res = [] 40 | event = threading.Event() 41 | 42 | # __stream_rewards: 43 | # Request a stream of rewards on a Vega network 44 | 45 | def on_message(wsa, line): 46 | # Vega data-node v2 returns the json line by line so we need to wait 47 | # for a full structure before we can parse to valid JSON in python 48 | if line == "{": 49 | del res[:] 50 | res.append(line) 51 | elif line == "}": 52 | res.append(line) 53 | obj = json.loads(''.join(res)) 54 | if "reward" in obj["result"]: 55 | # Result contains reward data for party 56 | print(f"Reward data found:") 57 | print(obj["result"]["reward"]) 58 | else: 59 | res.append(line) 60 | 61 | 62 | def on_error(wsa, error): 63 | print(error) 64 | 65 | 66 | def on_close(wsa, close_status_code, close_msg): 67 | print(f"Rewards stream closed: {url}") 68 | 69 | 70 | def on_open(wsa): 71 | print(f"Rewards stream open: {url}") 72 | 73 | 74 | def timeout(): 75 | while not event.wait(timeout=30): 76 | ws.close() 77 | exit(1) 78 | 79 | 80 | thread = threading.Thread(target=timeout) 81 | thread.start() 82 | 83 | ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) 84 | ws.on_open = on_open 85 | ws.run_forever() 86 | # :stream_rewards__ 87 | -------------------------------------------------------------------------------- /rest/stream-market-data.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # S T R E A M M A R K E T D A T A # 5 | ############################################################################### 6 | 7 | # How to stream market data information from a Data Node using Websockets: 8 | # ---------------------------------------------------------------------- 9 | # Pagination and Date Range are not supported, this is a realtime stream. 10 | # ---------------------------------------------------------------------- 11 | # The stream requires the following parameter/filter: 12 | # marketIds: Vega market id (a repeated param) for one or more markets 13 | # ---------------------------------------------------------------------- 14 | # For full details see the REST Reference API docs at https://docs.vega.xyz 15 | 16 | import websocket 17 | import threading 18 | import json 19 | import helpers 20 | 21 | # Load Vega node API v2 URL, this is set using 'source vega-config' 22 | # located in the root folder of the sample-api-scripts repository 23 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 24 | 25 | # Load Vega market id 26 | market_id = helpers.env_market_id() 27 | assert market_id != "" 28 | 29 | # Connect to the data node with a WSS based endpoint, this is not a HTTPS:// url 30 | # Hint: to include data from multiple markets repeat the param `marketIds` 31 | # e.g. marketIds=xxx&marketIds=yyy&marketIds=zzz 32 | url = f"{data_node_url_rest}/stream/markets/data?marketIds={market_id}".replace("https://", "wss://") 33 | res = [] 34 | event = threading.Event() 35 | 36 | # __stream_market_data_by_markets: 37 | # Request a stream of live market data for one or more market ids on a Vega network 38 | 39 | def on_message(wsa, line): 40 | # Vega data-node v2 returns the json line by line so we need to wait 41 | # for a full structure before we can parse to valid JSON in python 42 | if line == "{": 43 | del res[:] 44 | res.append(line) 45 | elif line == "}": 46 | res.append(line) 47 | obj = json.loads(''.join(res)) 48 | if "marketData" in obj["result"]: 49 | # Result contains each market-data update (may be multiple) 50 | found_market = obj["result"]["marketData"][0]["market"] 51 | print(f"Market data found for {found_market}:") 52 | print(obj["result"]["marketData"]) 53 | else: 54 | res.append(line) 55 | 56 | def on_error(wsa, error): 57 | print(error) 58 | 59 | 60 | def on_close(wsa, close_status_code, close_msg): 61 | print(f"Market-data stream closed: {url}") 62 | 63 | 64 | def on_open(wsa): 65 | print(f"Market-data stream open: {url}") 66 | 67 | 68 | def timeout(): 69 | while not event.wait(timeout=30): 70 | ws.close() 71 | exit(1) 72 | 73 | 74 | thread = threading.Thread(target=timeout) 75 | thread.start() 76 | 77 | ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) 78 | ws.on_open = on_open 79 | ws.run_forever() 80 | # :stream_market_data_by_markets__ 81 | -------------------------------------------------------------------------------- /rest/liquidity-commitment-amend.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import json 4 | import requests 5 | import helpers 6 | 7 | # Vega wallet interaction helper, see login.py for detail 8 | from login import token, pubkey 9 | 10 | # Load Vega node API v2 URL, this is set using 'source vega-config' 11 | # located in the root folder of the sample-api-scripts repository 12 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 13 | # Load Vega wallet server URL, set in same way as above 14 | wallet_server_url = helpers.get_from_env("WALLET_SERVER_URL") 15 | 16 | # Load Vega market id 17 | market_id = helpers.env_market_id() 18 | assert market_id != "" 19 | 20 | # Set to False to ONLY submit/amend a liquidity commitment (no cancellation) 21 | CANCEL_LP_AFTER_SUBMISSION = True 22 | 23 | # Set market id in ENV or uncomment the line below to override market id directly 24 | market_id = "e503cadb437861037cddfd7263d25b69102098a97573db23f8e5fc320cea1ce9" 25 | 26 | ##################################################################################### 27 | # A M E N D L I Q U I D I T Y C O M M I T M E N T # 28 | ##################################################################################### 29 | 30 | # __amend_liquidity_commitment: 31 | # Compose a liquidity commitment order message 32 | # (it will now serve as an amendment request): 33 | # modify fields you want to be amended 34 | submission = { 35 | "liquidityProvisionAmendment": { 36 | "marketId": market_id, 37 | "commitmentAmount": "500000000000000000000", 38 | "fee": "0.005", 39 | "buys": [ 40 | { 41 | "offset": "1", 42 | "proportion": "1", 43 | "reference": "PEGGED_REFERENCE_MID" 44 | } 45 | ], 46 | "sells": [ 47 | { 48 | "offset": "1", 49 | "proportion": "1", 50 | "reference": "PEGGED_REFERENCE_MID" 51 | } 52 | ] 53 | }, 54 | "pubKey": pubkey, 55 | "propagate": True 56 | } 57 | # :amend_liquidity_commitment__ 58 | 59 | print("Liquidity commitment amendment:\n{}".format( 60 | json.dumps(submission, indent=2, sort_keys=True) 61 | )) 62 | 63 | # __sign_tx_liquidity_amend: 64 | # Sign the transaction with an order submission command 65 | url = "http://localhost:1789/api/v2/requests" 66 | 67 | payload1 = { 68 | "id": "1", 69 | "jsonrpc": "2.0", 70 | "method": "client.send_transaction", 71 | "params": { 72 | "publicKey": pubkey, 73 | "sendingMode": "TYPE_SYNC", 74 | "transaction": submission 75 | } 76 | } 77 | 78 | payload = json.dumps(payload1) 79 | 80 | headers = { 81 | 'Content-Type': 'application/json-rpc', 82 | 'Accept': 'application/json-rpc', 83 | 'Origin': 'application/json-rpc', 84 | 'Authorization': f'{token}' 85 | } 86 | 87 | response = requests.request("POST", url, headers=headers, data=payload) 88 | 89 | print(response.text) 90 | # :sign_tx_liquidity_amend__ 91 | 92 | print("Signed liquidity commitment amendment and sent to Vega") 93 | 94 | if CANCEL_LP_AFTER_SUBMISSION is not True: 95 | exit(1) 96 | -------------------------------------------------------------------------------- /rest/stream-trades.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # S T R E A M T R A D E S # 5 | ############################################################################### 6 | 7 | # How to stream trade information from a Data Node using Websockets: 8 | # ---------------------------------------------------------------------- 9 | # Pagination and Date Range are not supported, this is a realtime stream. 10 | # ---------------------------------------------------------------------- 11 | # The stream can be filtered by various parameters, including: 12 | # partyId: Vega party id (public key) 13 | # marketId: Vega market id 14 | # > Include none, one or both to refine the stream of data from Vega 15 | # ---------------------------------------------------------------------- 16 | # For full details see the REST Reference API docs at https://docs.vega.xyz 17 | 18 | import websocket 19 | import threading 20 | import json 21 | import helpers 22 | 23 | # Load Vega node API v2 URL, this is set using 'source vega-config' 24 | # located in the root folder of the sample-api-scripts repository 25 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 26 | 27 | # Load Vega market id 28 | market_id = helpers.env_market_id() 29 | assert market_id != "" 30 | 31 | # Connect to the data node with a WSS based endpoint, this is not a HTTPS:// url 32 | # Hint: to include/filter data from a party add the param `partyId` 33 | # e.g. ?marketIds=xxx&partyId=yyy 34 | url = f"{data_node_url_rest}/stream/trades?marketId={market_id}".replace("https://", "wss://") 35 | res = [] 36 | event = threading.Event() 37 | 38 | # __stream_trades_by_market: 39 | # Request a stream of trades and updates for a market id on a Vega network 40 | 41 | def on_message(wsa, line): 42 | # Vega data-node v2 returns the json line by line so we need to wait 43 | # for a full structure before we can parse to valid JSON in python 44 | if line == "{": 45 | del res[:] 46 | res.append(line) 47 | elif line == "}": 48 | res.append(line) 49 | obj = json.loads(''.join(res)) 50 | if "trades" in obj["result"]: 51 | # Result contains each trade update (may be multiple) 52 | total_in_update = len(obj["result"]["trades"]) 53 | print(f"Trade data found [{total_in_update}]:") 54 | print(obj["result"]["trades"]) 55 | else: 56 | res.append(line) 57 | 58 | 59 | def on_error(wsa, error): 60 | print(error) 61 | 62 | 63 | def on_close(wsa, close_status_code, close_msg): 64 | print(f"Trades stream closed: {url}") 65 | 66 | 67 | def on_open(wsa): 68 | print(f"Trades stream open: {url}") 69 | 70 | 71 | def timeout(): 72 | while not event.wait(timeout=30): 73 | ws.close() 74 | exit(1) 75 | 76 | 77 | thread = threading.Thread(target=timeout) 78 | thread.start() 79 | 80 | ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) 81 | ws.on_open = on_open 82 | ws.run_forever() 83 | # :stream_trades_by_market__ 84 | -------------------------------------------------------------------------------- /rest/stream-margin-levels.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # S T R E A M M A R G I N L E V E L S # 5 | ############################################################################### 6 | 7 | # How to stream margin levels information from a Data Node using Websockets: 8 | # ---------------------------------------------------------------------- 9 | # Pagination and Date Range are not supported, this is a realtime stream. 10 | # ---------------------------------------------------------------------- 11 | # The stream has two required parameters, as follows: 12 | # partyId: Vega party id (public key) 13 | # marketId: Vega market id 14 | # > Both are required to stream margin level data 15 | # ---------------------------------------------------------------------- 16 | # For full details see the REST Reference API docs at https://docs.vega.xyz 17 | 18 | import websocket 19 | import threading 20 | import json 21 | import helpers 22 | 23 | # Vega wallet interaction helper, see login.py for detail 24 | from login import pubkey 25 | 26 | # Load Vega node API v2 URL, this is set using 'source vega-config' 27 | # located in the root folder of the sample-api-scripts repository 28 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 29 | 30 | # Load Vega market id 31 | market_id = helpers.env_market_id() 32 | assert market_id != "" 33 | 34 | # Connect to the data node with a WSS based endpoint, this is not a HTTPS:// url 35 | # e.g. ?marketId=xxx&partyId=yyy 36 | url = f"{data_node_url_rest}/stream/margin/levels?partyId={pubkey}&marketId={market_id}"\ 37 | .replace("https://", "wss://") 38 | res = [] 39 | event = threading.Event() 40 | 41 | # __stream_margin_levels: 42 | # Request a stream of margin level updates for a party and market id on a Vega network 43 | 44 | def on_message(wsa, line): 45 | # Vega data-node v2 returns the json line by line so we need to wait 46 | # for a full structure before we can parse to valid JSON in python 47 | if line == "{": 48 | del res[:] 49 | res.append(line) 50 | elif line == "}": 51 | res.append(line) 52 | obj = json.loads(''.join(res)) 53 | if "marginLevels" in obj["result"]: 54 | # Result contains margin level update for party on a market 55 | print(f"Margin level data found:") 56 | print(obj["result"]["marginLevels"]) 57 | else: 58 | res.append(line) 59 | 60 | 61 | def on_error(wsa, error): 62 | print(error) 63 | 64 | 65 | def on_close(wsa, close_status_code, close_msg): 66 | print(f"Margin levels stream closed: {url}") 67 | 68 | 69 | def on_open(wsa): 70 | print(f"Margin levels stream open: {url}") 71 | 72 | 73 | def timeout(): 74 | while not event.wait(timeout=30): 75 | ws.close() 76 | exit(1) 77 | 78 | 79 | thread = threading.Thread(target=timeout) 80 | thread.start() 81 | 82 | ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) 83 | ws.on_open = on_open 84 | ws.run_forever() 85 | # :stream_margin_levels__ 86 | -------------------------------------------------------------------------------- /rest/get-node-data.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # G E T V E G A N O D E D A T A # 5 | ############################################################################### 6 | # How to get Vega node information from a Data Node using REST calls: 7 | # ---------------------------------------------------------------------- 8 | # Pagination is supported by list nodes only [default page size is 1000] 9 | # -> Check out pagination.py for example usage 10 | # ---------------------------------------------------------------------- 11 | # The list nodes endpoint can be filtered by the following parameter: 12 | # epochSeq: Epoch number 13 | # ---------------------------------------------------------------------- 14 | # For full details see the REST Reference API docs at https://docs.vega.xyz 15 | 16 | import requests 17 | import helpers 18 | import json 19 | 20 | # Load Vega data node API v2 URL, this is set using 'source vega-config' 21 | # located in the root folder of the sample-api-scripts repository 22 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 23 | 24 | ############################################################################### 25 | # L I S T N O D E S D A T A # 26 | ############################################################################### 27 | 28 | # __get_nodes: 29 | # Request a list of information on the set of Vega nodes on a network 30 | url = f"{data_node_url_rest}/nodes" 31 | response = requests.get(url) 32 | helpers.check_response(response) 33 | response_json = response.json() 34 | print("Vega nodes:\n{}".format( 35 | json.dumps(response_json, indent=2, sort_keys=True) 36 | )) 37 | # :get_nodes__ 38 | 39 | node_id = response.json()['nodes']['edges'][0]['node']['id'] 40 | assert node_id != "" 41 | 42 | print() 43 | print(f"Selected node with id: {node_id}") 44 | print() 45 | 46 | ############################################################################### 47 | # N O D E D A T A # 48 | ############################################################################### 49 | 50 | # __get_node_data: 51 | # Request the node data for an id on a Vega network 52 | url = f"{data_node_url_rest}/node/{node_id}" 53 | response = requests.get(url) 54 | helpers.check_response(response) 55 | print("Node data:\n{}".format( 56 | json.dumps(response_json, indent=2, sort_keys=True) 57 | )) 58 | # :get_node_data__ 59 | 60 | ############################################################################### 61 | # N O D E S I G N A T U R E S # 62 | ############################################################################### 63 | 64 | # __get_node_signatures: 65 | # Request a list of node signatures on a Vega network 66 | url = f"{data_node_url_rest}/node/signatures?id={node_id}" 67 | response = requests.get(url) 68 | helpers.check_response(response) 69 | response_json = response.json() 70 | print("Vega node signatures:\n{}".format( 71 | json.dumps(response_json, indent=2, sort_keys=True) 72 | )) 73 | # :get_node_signatures__ 74 | -------------------------------------------------------------------------------- /rest/estimate-fees-and-margin.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # E S T I M A T E F E E S & M A R G I N # 5 | ############################################################################### 6 | 7 | # How to get Vega account information from a Data Node using REST calls: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is supported [default page size is 1000] 10 | # -> Check out pagination.py for example usage 11 | # ---------------------------------------------------------------------- 12 | # The list can be filtered by various parameters, including: 13 | # filter.partyIds: Vega party ids (public keys) 14 | # filter.marketIds: Vega market ids 15 | # filter.assets: Specific assets e.g. tDAI, tBTC, etc 16 | # filter.accountTypes: Account types e.g. infrastructure, general, etc 17 | # ---------------------------------------------------------------------- 18 | # For full details see the REST Reference API docs at https://docs.vega.xyz 19 | 20 | import json 21 | import requests 22 | import helpers 23 | 24 | # Vega wallet interaction helper, see login.py for detail 25 | from login import pubkey 26 | 27 | # Load Vega data node API v2 URL, this is set using 'source vega-config' 28 | # located in the root folder of the sample-api-scripts repository 29 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 30 | 31 | ##################################################################################### 32 | # F E E E S T I M A T I O N # 33 | ##################################################################################### 34 | 35 | market_id = helpers.env_market_id() 36 | assert market_id != "" 37 | 38 | # __get_fees_estimate: 39 | # Request to estimate trading fees on a Vega network 40 | order_price = "100000" 41 | order_size = "100" 42 | url = f"{data_node_url_rest}/estimate/fee?marketId={market_id}&price={order_price}&size={order_size}" 43 | response = requests.get(url) 44 | helpers.check_response(response) 45 | estimatedFees = response.json() 46 | print("Estimated fee for order:\n{}".format( 47 | json.dumps(estimatedFees, indent=2, sort_keys=True))) 48 | # :get_fees_estimate__ 49 | 50 | ##################################################################################### 51 | # M A R G I N E S T I M A T I O N # 52 | ##################################################################################### 53 | 54 | # __get_margins_estimate: 55 | # Request to estimate trading margin on a Vega network 56 | order_price = "600000" 57 | order_size = "10" 58 | order_side = "SIDE_BUY" 59 | order_type = "TYPE_LIMIT" 60 | 61 | url = f"{data_node_url_rest}/estimate/margin?marketId={market_id}&partyId={pubkey}" \ 62 | f"&price={order_price}&size={order_size}&side={order_side}&type={order_type}" 63 | response = requests.get(url) 64 | helpers.check_response(response) 65 | estimatedMargin = response.json() 66 | print("Estimated margin for order:\n{}".format( 67 | json.dumps(estimatedMargin, indent=2, sort_keys=True))) 68 | # :get_margins_estimate__ 69 | -------------------------------------------------------------------------------- /rest/get-transfers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # G E T T R A N S F E R S # 5 | ############################################################################### 6 | 7 | # How to get transfer information from a Data Node using REST calls: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is supported [default page size is 1000] 10 | # -> Check out pagination.py for example usage 11 | # ---------------------------------------------------------------------- 12 | # The list can be filtered by various parameters, including: 13 | # pubkey: Vega party id (public key) 14 | # direction: Which direction the transfer took place, e.g. 15 | # TRANSFER_DIRECTION_TRANSFER_FROM 16 | # TRANSFER_DIRECTION_TRANSFER_TO 17 | # TRANSFER_DIRECTION_TRANSFER_TO_OR_FROM 18 | # ---------------------------------------------------------------------- 19 | # For full details see the REST Reference API docs at https://docs.vega.xyz 20 | 21 | import json 22 | import requests 23 | import helpers 24 | 25 | # Load Vega node API v2 URL, this is set using 'source vega-config' 26 | # located in the root folder of the sample-api-scripts repository 27 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 28 | 29 | ############################################################################### 30 | # L I S T T R A N S F E R S # 31 | ############################################################################### 32 | 33 | # __get_transfers: 34 | # Request a list of transfers for a Vega network 35 | url = f"{data_node_url_rest}/transfers" 36 | response = requests.get(url) 37 | helpers.check_response(response) 38 | print("Transfers for network:\n{}".format( 39 | json.dumps(response.json(), indent=2, sort_keys=True) 40 | )) 41 | # :get_transfers__ 42 | 43 | from_pubkey = "e4a81f9e67acee66406a84ace9fe2f70512a775c62301fbeb17eb6ecec83b2b9" 44 | if helpers.check_nested_response(response, "transfers"): 45 | first_transfer = helpers.get_nested_response(response, "transfers")[0]["node"] 46 | from_pubkey = first_transfer["from"] 47 | 48 | # Uncomment the following two lines to use an env specified party id 49 | # from_pubkey = helpers.env_party_id() 50 | # assert from_pubkey != "" 51 | 52 | ############################################################################### 53 | # 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 # 54 | ############################################################################### 55 | 56 | # Hint: Both party (pubkey) and direction are required when specifying a pubkey 57 | 58 | # __get_transfers_by_party: 59 | # Request a list of transfers for a party (and direction) on a Vega network 60 | url = f"{data_node_url_rest}/transfers?pubkey={from_pubkey}&direction=TRANSFER_DIRECTION_TRANSFER_TO" 61 | response = requests.get(url) 62 | helpers.check_response(response) 63 | print("Transfers for a specific party and direction (TRANSFER_DIRECTION_TRANSFER_TO):\n{}".format( 64 | json.dumps(response.json(), indent=2, sort_keys=True) 65 | )) 66 | # :get_transfers_by_party__ 67 | -------------------------------------------------------------------------------- /rest/get-parties.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # G E T P A R T I E S # 5 | ############################################################################### 6 | 7 | # How to get Vega party information from a Data Node using REST calls: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is supported [default page size is 1000] 10 | # -> Check out pagination.py for example usage 11 | # ---------------------------------------------------------------------- 12 | # The list can be filtered by the following parameter: 13 | # partyId: Vega party id (public key) 14 | # ---------------------------------------------------------------------- 15 | # For full details see the REST Reference API docs at https://docs.vega.xyz 16 | 17 | import json 18 | import requests 19 | import helpers 20 | 21 | # Vega wallet interaction helper, see login.py for detail 22 | from login import pubkey 23 | 24 | # Load Vega data node API v2 URL, this is set using 'source vega-config' 25 | # located in the root folder of the sample-api-scripts repository 26 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 27 | 28 | ############################################################################### 29 | # P A R T I E S B Y M A R K E T # 30 | ############################################################################### 31 | 32 | # TODO: this needs implementing in api 33 | 34 | market_id = helpers.env_market_id() 35 | assert market_id != "" 36 | 37 | # __get_parties_by_market: 38 | # Request a list of parties for a single market (repeat the filter for multiple markets) 39 | # url = f"{data_node_url_rest}/accounts?filter.marketIds={market_id}" 40 | # response = requests.get(url) 41 | # helpers.check_response(response) 42 | # response_json = response.json() 43 | # print("Accounts filtered by market:\n{}".format( 44 | # json.dumps(response_json, indent=2, sort_keys=True) 45 | # )) 46 | # :get_parties_by_market__ 47 | 48 | ############################################################################### 49 | # L I S T P A R T I E S # 50 | ############################################################################### 51 | 52 | # __get_parties: 53 | url = f"{data_node_url_rest}/parties" 54 | response = requests.get(url) 55 | helpers.check_response(response) 56 | print("Parties for network:\n{}".format( 57 | json.dumps(response.json(), indent=2, sort_keys=True) 58 | )) 59 | # :get_parties__ 60 | 61 | ############################################################################### 62 | # P A R T Y B Y I D # 63 | ############################################################################### 64 | 65 | party_id = helpers.env_party_id() 66 | assert party_id != "" 67 | 68 | # __get_party: 69 | # Request a specific party using a pre-defined party id (pubkey) 70 | url = f"{data_node_url_rest}/parties?partyId={party_id}" 71 | response = requests.get(url) 72 | helpers.check_response(response) 73 | print("Party:\n{}".format( 74 | json.dumps(response.json(), indent=2, sort_keys=True))) 75 | # :get_party__ 76 | -------------------------------------------------------------------------------- /rest/stream-orders.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # S T R E A M O R D E R S # 5 | ############################################################################### 6 | 7 | # How to stream order information from a Data Node using Websockets: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is not supported, but the initial snapshot may contain 10 | # multiple pages. Date Range is not supported, this is a realtime stream. 11 | # ---------------------------------------------------------------------- 12 | # The stream can be filtered by various parameters, including: 13 | # partyId: Vega party id (public key) 14 | # marketId: Vega market id 15 | # > Include none, one or both to refine the stream of data from Vega 16 | # ---------------------------------------------------------------------- 17 | # For full details see the REST Reference API docs at https://docs.vega.xyz 18 | 19 | import websocket 20 | import threading 21 | import json 22 | import helpers 23 | 24 | # Load Vega node API v2 URL, this is set using 'source vega-config' 25 | # located in the root folder of the sample-api-scripts repository 26 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 27 | 28 | # Load Vega market id 29 | market_id = helpers.env_market_id() 30 | assert market_id != "" 31 | 32 | # Connect to the data node with a WSS based endpoint, this is not a HTTPS:// url 33 | # Hint: to include/filter data from a party add the param `partyId` 34 | # e.g. ?marketIds=xxx&partyId=yyy 35 | url = f"{data_node_url_rest}/stream/orders?marketId={market_id}".replace("https://", "wss://") 36 | res = [] 37 | event = threading.Event() 38 | 39 | # __stream_orders_by_market: 40 | # Request a stream of live orders and updates for a market id on a Vega network 41 | 42 | def on_message(wsa, line): 43 | # Vega data-node v2 returns the json line by line so we need to wait 44 | # for a full structure before we can parse to valid JSON in python 45 | if line == "{": 46 | del res[:] 47 | res.append(line) 48 | elif line == "}": 49 | res.append(line) 50 | obj = json.loads(''.join(res)) 51 | if "snapshot" in obj["result"]: 52 | # An 'initial image' snapshot containing current live orders (may be multiple pages) 53 | print("Snapshot found:") 54 | print(obj["result"]["snapshot"]) 55 | if "updates" in obj["result"]: 56 | # A list of order updates typically from the last block 57 | print("Updates found:") 58 | print(obj["result"]["updates"]) 59 | else: 60 | res.append(line) 61 | 62 | 63 | def on_error(wsa, error): 64 | print(error) 65 | 66 | 67 | def on_close(wsa, close_status_code, close_msg): 68 | print(f"Orders stream closed: {url}") 69 | 70 | 71 | def on_open(wsa): 72 | print(f"Orders stream open: {url}") 73 | 74 | 75 | def timeout(): 76 | while not event.wait(timeout=30): 77 | ws.close() 78 | exit(1) 79 | 80 | 81 | thread = threading.Thread(target=timeout) 82 | thread.start() 83 | 84 | ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) 85 | ws.on_open = on_open 86 | ws.run_forever() 87 | # :stream_orders_by_market__ 88 | -------------------------------------------------------------------------------- /rest/stream-positions.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # S T R E A M P O S I T I O N S # 5 | ############################################################################### 6 | 7 | # How to stream position information from a Data Node using Websockets: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is not supported, but the initial snapshot may contain 10 | # multiple pages. Date Range is not supported, this is a realtime stream. 11 | # ---------------------------------------------------------------------- 12 | # The stream can be filtered by various parameters, including: 13 | # partyId: Vega party id (public key) 14 | # marketId: Vega market id 15 | # > Include none, one or both to refine the stream of data from Vega 16 | # ---------------------------------------------------------------------- 17 | # For full details see the REST Reference API docs at https://docs.vega.xyz 18 | 19 | import websocket 20 | import threading 21 | import json 22 | import helpers 23 | 24 | # Load Vega node API v2 URL, this is set using 'source vega-config' 25 | # located in the root folder of the sample-api-scripts repository 26 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 27 | 28 | # Load Vega market id 29 | market_id = helpers.env_market_id() 30 | assert market_id != "" 31 | 32 | # Connect to the data node with a WSS based endpoint, this is not a HTTPS:// url 33 | # Hint: to include/filter data from a party add the param `partyId` and same 34 | # for a market id: 35 | # e.g. ?marketId=xxx&partyId=yyy 36 | url = f"{data_node_url_rest}/stream/positions".replace("https://", "wss://") 37 | res = [] 38 | event = threading.Event() 39 | 40 | # __stream_positions: 41 | # Request a stream of positions for a market id on a Vega network 42 | 43 | def on_message(wsa, line): 44 | # Vega data-node v2 returns the json line by line so we need to wait 45 | # for a full structure before we can parse to valid JSON in python 46 | if line == "{": 47 | del res[:] 48 | res.append(line) 49 | elif line == "}": 50 | res.append(line) 51 | obj = json.loads(''.join(res)) 52 | if "snapshot" in obj["result"]: 53 | # An 'initial image' snapshot containing current positions (may be multiple pages) 54 | print("Snapshot found:") 55 | print(obj["result"]["snapshot"]["positions"]) 56 | if "updates" in obj["result"]: 57 | # A list of position updates typically from the last block 58 | print("Updates found:") 59 | print(obj["result"]["updates"]["positions"]) 60 | else: 61 | res.append(line) 62 | 63 | 64 | def on_error(wsa, error): 65 | print(error) 66 | 67 | 68 | def on_close(wsa, close_status_code, close_msg): 69 | print(f"Positions stream closed: {url}") 70 | 71 | 72 | def on_open(wsa): 73 | print(f"Positions stream open: {url}") 74 | 75 | 76 | def timeout(): 77 | while not event.wait(timeout=30): 78 | ws.close() 79 | exit(1) 80 | 81 | 82 | thread = threading.Thread(target=timeout) 83 | thread.start() 84 | 85 | ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) 86 | ws.on_open = on_open 87 | ws.run_forever() 88 | # :stream_positions__ 89 | -------------------------------------------------------------------------------- /rest/get-deposits.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # G E T D E P O S I T S # 5 | ############################################################################### 6 | 7 | # How to get deposit information from a Data Node using REST calls: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is supported [default page size is 1000] 10 | # -> Check out pagination.py for example usage 11 | # ---------------------------------------------------------------------- 12 | # The list can be filtered by various parameters, including: 13 | # partyId: Vega party id (public key) 14 | # ---------------------------------------------------------------------- 15 | # For full details see the REST Reference API docs at https://docs.vega.xyz 16 | 17 | import json 18 | import requests 19 | import helpers 20 | 21 | # Vega wallet interaction helper, see login.py for detail 22 | from login import pubkey 23 | 24 | # Load Vega node API v2 URL, this is set using 'source vega-config' 25 | # located in the root folder of the sample-api-scripts repository 26 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 27 | 28 | ############################################################################### 29 | # L I S T D E P O S I T S # 30 | ############################################################################### 31 | 32 | # __get_deposits: 33 | # Request a list of deposits for a Vega network 34 | url = f"{data_node_url_rest}/deposits" 35 | response = requests.get(url) 36 | helpers.check_response(response) 37 | print("Deposits for network:\n{}".format( 38 | json.dumps(response.json(), indent=2, sort_keys=True) 39 | )) 40 | # :get_deposits__ 41 | 42 | # Find the first deposit in the list (above) if it exists 43 | deposit_id = "3a834328d835cf79880dfc238a989c238fe32a62562690d717ab1ff42ad5003f" 44 | if helpers.check_nested_response(response, "deposits"): 45 | first_deposit = helpers.get_nested_response(response, "deposits")[0]["node"] 46 | deposit_id = first_deposit["id"] 47 | 48 | ############################################################################### 49 | # D E P O S I T S B Y P A R T Y # 50 | ############################################################################### 51 | 52 | # __get_deposits_by_party: 53 | # Request a list of deposits for a party on a Vega network 54 | url = f"{data_node_url_rest}/deposits?partyId={pubkey}" 55 | response = requests.get(url) 56 | helpers.check_response(response) 57 | print("Deposits for a specific party:\n{}".format( 58 | json.dumps(response.json(), indent=2, sort_keys=True) 59 | )) 60 | # :get_deposits_by_party__ 61 | 62 | ############################################################################### 63 | # D E P O S I T B Y I D # 64 | ############################################################################### 65 | 66 | # __get_deposit_by_id: 67 | # Request a single deposit for deposit id 68 | url = f"{data_node_url_rest}/deposit/{deposit_id}" 69 | response = requests.get(url) 70 | helpers.check_response(response) 71 | print("Deposit for id:\n{}".format( 72 | json.dumps(response.json(), indent=2, sort_keys=True) 73 | )) 74 | # :get_deposit_by_id__ 75 | -------------------------------------------------------------------------------- /rest/stream-accounts.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # S T R E A M A C C O U N T S # 5 | ############################################################################### 6 | 7 | # How to stream account information from a Data Node using Websockets: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is not supported, but the initial snapshot may contain 10 | # multiple pages. Date Range is not supported, this is a realtime stream. 11 | # ---------------------------------------------------------------------- 12 | # The stream can be filtered by various parameters, including: 13 | # partyId: Vega party id (public key) 14 | # marketId: Vega market id 15 | # asset: Vega asset id 16 | # type: Account type 17 | # ---------------------------------------------------------------------- 18 | # For full details see the REST Reference API docs at https://docs.vega.xyz 19 | 20 | import websocket 21 | import threading 22 | import json 23 | import helpers 24 | 25 | # Load Vega node API v2 URL, this is set using 'source vega-config' 26 | # located in the root folder of the sample-api-scripts repository 27 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 28 | 29 | # Load Vega market id 30 | market_id = helpers.env_market_id() 31 | assert market_id != "" 32 | 33 | # Connect to the data node with a WSS based endpoint, this is not a HTTPS:// url 34 | # Hint: to include/filter data from a party, asset or account types: 35 | # e.g. ?marketId=xxx&partyId=yyy&asset=zzz&type=ccc 36 | url = f"{data_node_url_rest}/stream/accounts?marketId={market_id}".replace("https://", "wss://") 37 | res = [] 38 | event = threading.Event() 39 | 40 | # __stream_accounts_by_market: 41 | # Request a stream of accounts and updates for a market id on a Vega network 42 | 43 | def on_message(wsa, line): 44 | # Vega data-node v2 returns the json line by line so we need to wait 45 | # for a full structure before we can parse to valid JSON in python 46 | if line == "{": 47 | del res[:] 48 | res.append(line) 49 | elif line == "}": 50 | res.append(line) 51 | obj = json.loads(''.join(res)) 52 | if "snapshot" in obj["result"]: 53 | # An 'initial image' snapshot containing current accounts state (may be multiple pages) 54 | print("Snapshot found:") 55 | print(obj["result"]["snapshot"]["accounts"]) 56 | if "updates" in obj["result"]: 57 | # A list of account updates typically from the last block 58 | print("Updates found:") 59 | print(obj["result"]["updates"]["accounts"]) 60 | else: 61 | res.append(line) 62 | 63 | def on_error(wsa, error): 64 | print(error) 65 | 66 | 67 | def on_close(wsa, close_status_code, close_msg): 68 | print(f"Accounts stream closed: {url}") 69 | 70 | 71 | def on_open(wsa): 72 | print(f"Accounts stream open: {url}") 73 | 74 | 75 | def timeout(): 76 | while not event.wait(timeout=30): 77 | ws.close() 78 | exit(1) 79 | 80 | 81 | thread = threading.Thread(target=timeout) 82 | thread.start() 83 | 84 | ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) 85 | ws.on_open = on_open 86 | ws.run_forever() 87 | # :stream_accounts_by_market__ 88 | -------------------------------------------------------------------------------- /rest/stream-market-depth.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # S T R E A M M A R K E T D E P T H # 5 | ############################################################################### 6 | 7 | # IMPORTANT: This streaming endpoint returns the entire market depth/order 8 | # book on each update, if you're looking for a stream of differences see 9 | # the script `stream-market-depth-updates.py` 10 | 11 | # How to stream market depth information from a Data Node using Websockets: 12 | # ---------------------------------------------------------------------- 13 | # Pagination and Date Range are not supported, this is a realtime stream. 14 | # ---------------------------------------------------------------------- 15 | # The stream requires the following parameter/filter: 16 | # marketIds: Vega market id (a repeated param) for one or more markets 17 | # ---------------------------------------------------------------------- 18 | # For full details see the REST Reference API docs at https://docs.vega.xyz 19 | 20 | import websocket 21 | import threading 22 | import json 23 | import helpers 24 | 25 | 26 | # Load Vega node API v2 URL, this is set using 'source vega-config' 27 | # located in the root folder of the sample-api-scripts repository 28 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 29 | 30 | # Load Vega market id 31 | market_id = helpers.env_market_id() 32 | assert market_id != "" 33 | 34 | # Connect to the data node with a WSS based endpoint, this is not a HTTPS:// url 35 | # Hint: to include data from multiple markets repeat the param `marketIds` 36 | # e.g. marketIds=xxx&marketIds=yyy&marketIds=zzz 37 | url = f"{data_node_url_rest}/stream/markets/depth?marketIds={market_id}".replace("https://", "wss://") 38 | res = [] 39 | event = threading.Event() 40 | 41 | print(url) 42 | 43 | # __stream_market_depth_by_markets: 44 | # Request a stream of live market depth data for one or more market ids on a Vega network 45 | 46 | def on_message(wsa, line): 47 | # Vega data-node v2 returns the json line by line so we need to wait 48 | # for a full structure before we can parse to valid JSON in python 49 | if line == "{": 50 | del res[:] 51 | res.append(line) 52 | elif line == "}": 53 | res.append(line) 54 | obj = json.loads(''.join(res)) 55 | if "marketDepth" in obj["result"]: 56 | # Result contains each market-depth update (may be multiple) 57 | found_market = obj["result"]["marketDepth"][0]["marketId"] 58 | print(f"Market depth data found for {found_market}:") 59 | print(obj["result"]["marketDepth"][0]) 60 | else: 61 | res.append(line) 62 | 63 | 64 | def on_error(wsa, error): 65 | print(error) 66 | 67 | 68 | def on_close(wsa, close_status_code, close_msg): 69 | print(f"Market-depth stream closed: {url}") 70 | 71 | 72 | def on_open(wsa): 73 | print(f"Market-depth stream open: {url}") 74 | 75 | 76 | def timeout(): 77 | while not event.wait(timeout=30): 78 | ws.close() 79 | exit(1) 80 | 81 | 82 | thread = threading.Thread(target=timeout) 83 | thread.start() 84 | 85 | ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) 86 | ws.on_open = on_open 87 | ws.run_forever() 88 | # :stream_market_depth_by_markets__ 89 | -------------------------------------------------------------------------------- /rest/stream-market-depth-updates.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # S T R E A M M A R K E T D E P T H U P D A T E S # 5 | ############################################################################### 6 | 7 | # IMPORTANT: This streaming endpoint returns only the changes to market depth 8 | # /order book on each update, if you're looking for a stream of the full order 9 | # book, see the script `stream-market-depth.py` 10 | 11 | # How to stream market depth information from a Data Node using Websockets: 12 | # ---------------------------------------------------------------------- 13 | # Pagination and Date Range are not supported, this is a realtime stream. 14 | # ---------------------------------------------------------------------- 15 | # The stream requires the following parameter/filter: 16 | # marketIds: Vega market id (a repeated param) for one or more markets 17 | # ---------------------------------------------------------------------- 18 | # For full details see the REST Reference API docs at https://docs.vega.xyz 19 | 20 | import websocket 21 | import threading 22 | import json 23 | import helpers 24 | 25 | # Load Vega node API v2 URL, this is set using 'source vega-config' 26 | # located in the root folder of the sample-api-scripts repository 27 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 28 | 29 | # Load Vega market id 30 | market_id = helpers.env_market_id() 31 | assert market_id != "" 32 | 33 | # Connect to the data node with a WSS based endpoint, this is not a HTTPS:// url 34 | # Hint: to include data from multiple markets repeat the param `marketIds` 35 | # e.g. marketIds=xxx&marketIds=yyy&marketIds=zzz 36 | url = f"{data_node_url_rest}/stream/markets/depth/updates?marketIds={market_id}"\ 37 | .replace("https://", "wss://") 38 | res = [] 39 | event = threading.Event() 40 | 41 | print(url) 42 | 43 | # __stream_market_depth_updates_by_markets: 44 | # Request a stream of live market depth update data for one or more market ids on a Vega network 45 | 46 | def on_message(wsa, line): 47 | # Vega data-node v2 returns the json line by line so we need to wait 48 | # for a full structure before we can parse to valid JSON in python 49 | if line == "{": 50 | del res[:] 51 | res.append(line) 52 | elif line == "}": 53 | res.append(line) 54 | obj = json.loads(''.join(res)) 55 | if "update" in obj["result"]: 56 | # Result contains each market-depth update (may be multiple) 57 | found_market = obj["result"]["update"][0]["marketId"] 58 | print(f"Market depth data found for {found_market}:") 59 | print(obj["result"]["update"][0]) 60 | else: 61 | res.append(line) 62 | 63 | 64 | def on_error(wsa, error): 65 | print(error) 66 | 67 | 68 | def on_close(wsa, close_status_code, close_msg): 69 | print(f"Market-depth stream closed: {url}") 70 | 71 | 72 | def on_open(wsa): 73 | print(f"Market-depth stream open: {url}") 74 | 75 | 76 | def timeout(): 77 | while not event.wait(timeout=30): 78 | ws.close() 79 | exit(1) 80 | 81 | 82 | thread = threading.Thread(target=timeout) 83 | thread.start() 84 | 85 | ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) 86 | ws.on_open = on_open 87 | ws.run_forever() 88 | # :stream_market_depth_updates_by_markets__ 89 | -------------------------------------------------------------------------------- /rest/get-withdrawals.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # G E T W I T H D R A W A L S # 5 | ############################################################################### 6 | 7 | # How to get withdrawal information from a Data Node using REST calls: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is supported [default page size is 1000] 10 | # -> Check out pagination.py for example usage 11 | # ---------------------------------------------------------------------- 12 | # The list can be filtered by various parameters, including: 13 | # partyId: Vega party id (public key) 14 | # ---------------------------------------------------------------------- 15 | # For full details see the REST Reference API docs at https://docs.vega.xyz 16 | 17 | import json 18 | import requests 19 | import helpers 20 | 21 | # Vega wallet interaction helper, see login.py for detail 22 | from login import pubkey 23 | 24 | # Load Vega node API v2 URL, this is set using 'source vega-config' 25 | # located in the root folder of the sample-api-scripts repository 26 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 27 | 28 | ############################################################################### 29 | # L I S T W I T H D R A W A L S # 30 | ############################################################################### 31 | 32 | # __get_withdrawals: 33 | # Request a list of withdrawals for a Vega network 34 | url = f"{data_node_url_rest}/withdrawals" 35 | response = requests.get(url) 36 | helpers.check_response(response) 37 | print("Withdrawals for network:\n{}".format( 38 | json.dumps(response.json(), indent=2, sort_keys=True) 39 | )) 40 | # :get_withdrawals__ 41 | 42 | # Find the first withdrawal in the list (above) if it exists 43 | withdrawal_id = "3a834328d835cf79880dfc238a989c238fe32a62562690d717ab1ff42ad5003f" 44 | if helpers.check_nested_response(response, "withdrawals"): 45 | first_withdrawal = helpers.get_nested_response(response, "withdrawals")[0]["node"] 46 | withdrawal_id = first_withdrawal["id"] 47 | 48 | ############################################################################### 49 | # W I T H D R A W A L S B Y P A R T Y # 50 | ############################################################################### 51 | 52 | # __get_withdrawals_by_party: 53 | # Request a list of withdrawals for a party on a Vega network 54 | url = f"{data_node_url_rest}/withdrawals?partyId={pubkey}" 55 | response = requests.get(url) 56 | helpers.check_response(response) 57 | print("Withdrawals for a specific party:\n{}".format( 58 | json.dumps(response.json(), indent=2, sort_keys=True) 59 | )) 60 | # :get_withdrawals_by_party__ 61 | 62 | ############################################################################### 63 | # W I T H D R A W A L B Y I D # 64 | ############################################################################### 65 | 66 | # __get_withdrawal_by_id: 67 | # Request a single withdrawal for withdrawal id 68 | url = f"{data_node_url_rest}/withdrawal/{withdrawal_id}" 69 | response = requests.get(url) 70 | helpers.check_response(response) 71 | print("Withdrawal for id:\n{}".format( 72 | json.dumps(response.json(), indent=2, sort_keys=True) 73 | )) 74 | # :get_withdrawal_by_id__ 75 | -------------------------------------------------------------------------------- /rest/get-liquidity-provisions.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # G E T L I Q U I D I T Y P R O V I S I O N S # 5 | ############################################################################### 6 | 7 | # How to get LP information from a Data Node using REST calls: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is supported [default page size is 1000] 10 | # -> Check out pagination.py for example usage 11 | # ---------------------------------------------------------------------- 12 | # The list can be filtered by various parameters, including: 13 | # partyId: Vega party id (public key) 14 | # marketId: Vega market id 15 | # reference: A unique/custom reference 16 | # Note that with a reference, a marketId or partyId is also required 17 | # ---------------------------------------------------------------------- 18 | # For full details see the REST Reference API docs at https://docs.vega.xyz 19 | 20 | import json 21 | import requests 22 | import helpers 23 | 24 | # Load Vega node API v2 URL, this is set using 'source vega-config' 25 | # located in the root folder of the sample-api-scripts repository 26 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 27 | market_id = helpers.env_market_id() 28 | 29 | ############################################################################### 30 | # L P S B Y M A R K E T # 31 | ############################################################################### 32 | 33 | # __get_lps_by_market: 34 | # Request liquidity provisions for a market on a Vega network 35 | url = f"{data_node_url_rest}/liquidity/provisions?marketId={market_id}" 36 | response = requests.get(url) 37 | helpers.check_response(response) 38 | print("Liquidity Provisions for market:\n{}".format( 39 | json.dumps(response.json(), indent=2, sort_keys=True) 40 | )) 41 | # :get_lps_by_market__ 42 | 43 | # Find the first delegation in the list (above) 44 | first_lp = response.json()["liquidityProvisions"]["edges"][0]["node"] 45 | party_id = first_lp["partyId"] 46 | custom_ref = first_lp["reference"] 47 | 48 | ############################################################################### 49 | # L P S B Y P A R T Y # 50 | ############################################################################### 51 | 52 | # __get_lps_by_party: 53 | # Request liquidity provisions for a party on a Vega network 54 | url = f"{data_node_url_rest}/liquidity/provisions?partyId={party_id}" 55 | response = requests.get(url) 56 | helpers.check_response(response) 57 | print("Liquidity Provisions for party:\n{}".format( 58 | json.dumps(response.json(), indent=2, sort_keys=True) 59 | )) 60 | # :get_lps_by_party__ 61 | 62 | ############################################################################### 63 | # L P S B Y R E F E R E N C E # 64 | ############################################################################### 65 | 66 | # __get_lps_by_reference: 67 | # Request liquidity provisions for a reference on a Vega network 68 | # Note: A partyId or marketId must be supplied with the reference field 69 | url = f"{data_node_url_rest}/liquidity/provisions?marketId={market_id}&reference={custom_ref}" 70 | response = requests.get(url) 71 | helpers.check_response(response) 72 | print("Liquidity Provisions for reference:\n{}".format( 73 | json.dumps(response.json(), indent=2, sort_keys=True) 74 | )) 75 | # :get_lps_by_reference__ 76 | -------------------------------------------------------------------------------- /rest/get-candles.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # G E T C A N D L E S # 5 | ############################################################################### 6 | 7 | # How to get Vega candle (ohlc) information from a Data Node using REST calls: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is supported [default page size is 1000] 10 | # -> Check out pagination.py for example usage 11 | # ---------------------------------------------------------------------- 12 | # The specific candles are obtained using parameters: 13 | # candleId: Vega candle id (contains interval) see List Candle Intervals 14 | # Date range is supported but by using the following required params: 15 | # fromTimestamp: Starting timestamp for candles in nanoseconds since the epoch 16 | # toTimestamp: Ending timestamp for candles in nanoseconds since the epoch 17 | # 18 | # ---------------------------------------------------------------------- 19 | # For full details see the REST Reference API docs at https://docs.vega.xyz 20 | 21 | import json 22 | import requests 23 | import helpers 24 | 25 | # Load Vega data node API v2 URL, this is set using 'source vega-config' 26 | # located in the root folder of the sample-api-scripts repository 27 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 28 | market_id = helpers.env_market_id() 29 | assert market_id != "" 30 | 31 | ############################################################################### 32 | # L I S T C A N D L E I N T E R V A L S # 33 | ############################################################################### 34 | 35 | # Hint: In order to get candles of a suitable bucket size e.g. 5 minutes and 36 | # market id e.g. 13b081fe5bc8fd256b0a374dc04d94b904118312dd0d942e891a5f57ce0c556c 37 | # you should use the list candle intervals API to get back a candle id: 38 | 39 | # __get_candle_intervals: 40 | # Request a list of candle intervals available for a market and select a candle id 41 | url = f"{data_node_url_rest}/candle/intervals?marketId={market_id}" 42 | response = requests.get(url) 43 | helpers.check_response(response) 44 | print("Candle intervals for market:\n{}".format( 45 | json.dumps(response.json(), indent=2, sort_keys=True))) 46 | # :get_candle_intervals__ 47 | 48 | # Find the first candle id in the list e.g. trades_candle_5_minutes_ etc 49 | candle_id = response.json()["intervalToCandleId"][0]["candleId"] 50 | assert candle_id != "" 51 | print(f"Candle found: {candle_id}") 52 | 53 | ############################################################################### 54 | # C A N D L E S ( F I L T E R E D ) # 55 | ############################################################################### 56 | 57 | # Calculate the time window for the candles period to return e.g. last 24 hours 58 | time_now = helpers.ts_now() 59 | fromTime = helpers.get_nano_ts(time_now, 24*60*60) # 1 day ago 60 | toTime = helpers.get_nano_ts(time_now, 0) # to now 61 | 62 | # __get_candles_by_id: 63 | # Request specific candles for a market using candle id (from above) 64 | url = f"{data_node_url_rest}/candle?candleId={candle_id}" \ 65 | f"&fromTimestamp={fromTime}" \ 66 | f"&toTimestamp={toTime}" 67 | print(url) 68 | response = requests.get(url) 69 | helpers.check_response(response) 70 | print("Candles for id and ns timestamp window:\n{}".format( 71 | json.dumps(response.json(), indent=2, sort_keys=True))) 72 | # :get_candles_by_id__ 73 | -------------------------------------------------------------------------------- /rest/get-market-data.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # G E T M A R K E T D A T A # 5 | ############################################################################### 6 | 7 | # How to get market data from a Data Node using REST calls: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is supported [default page size is 1000] 10 | # -> Check out pagination.py for example usage 11 | # Date Range is supported 12 | # -> Check out date-range.py for example usage 13 | # ---------------------------------------------------------------------- 14 | # The following path parameter is required when getting latest data and 15 | # historic data, it is not required for listing market data for all markets: 16 | # marketId: Vega market id 17 | # ---------------------------------------------------------------------- 18 | # For full details see the REST Reference API docs at https://docs.vega.xyz 19 | 20 | import json 21 | import requests 22 | import helpers 23 | 24 | # Load Vega node API v2 URL, this is set using 'source vega-config' 25 | # located in the root folder of the sample-api-scripts repository 26 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 27 | 28 | # Load Vega market id 29 | market_id = helpers.env_market_id() 30 | 31 | ############################################################################### 32 | # M A R K E T D A T A H I S T O R Y # 33 | ############################################################################### 34 | 35 | # __get_market_data: 36 | # Calculate the time window for the history period to return e.g. last 24 hours 37 | time_now = helpers.ts_now() 38 | fromTime = helpers.get_nano_ts(time_now, 24*60*60) # 1 day ago 39 | toTime = helpers.get_nano_ts(time_now, 0) # to now 40 | 41 | # Request market data history for a specific market using a market id 42 | # Important! The startTimestamp and endTimestamp are REQUIRED fields 43 | url = f"{data_node_url_rest}/market/data/{market_id}?startTimestamp={fromTime}&endTimestamp={toTime}" 44 | print(url) 45 | response = requests.get(url) 46 | helpers.check_response(response) 47 | print("Market data:\n{}".format( 48 | json.dumps(response.json(), indent=2, sort_keys=True) 49 | )) 50 | # :get_market_data__ 51 | 52 | ############################################################################### 53 | # L A T E S T M A R K E T D A T A # 54 | ############################################################################### 55 | 56 | # __get_latest_market_data: 57 | # Request market data for a specific market using a market id 58 | url = f"{data_node_url_rest}/market/data/{market_id}/latest" 59 | response = requests.get(url) 60 | helpers.check_response(response) 61 | print("Market data for market:\n{}".format( 62 | json.dumps(response.json(), indent=2, sort_keys=True) 63 | )) 64 | # :get_latest_market_data__ 65 | 66 | ############################################################################### 67 | # M A R K E T S D A T A # 68 | ############################################################################### 69 | 70 | # __get_markets_data: 71 | # Request latest market data for ALL markets on a Vega network 72 | url = f"{data_node_url_rest}/markets/data" 73 | response = requests.get(url) 74 | helpers.check_response(response) 75 | print("Markets data:\n{}".format( 76 | json.dumps(response.json(), indent=2, sort_keys=True) 77 | )) 78 | # :get_markets_data__ 79 | 80 | -------------------------------------------------------------------------------- /rest/get-balances.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # G E T H I S T O R I C B A L A N C E S # 5 | ############################################################################### 6 | 7 | # How to get balance changes for accounts from a Data Node using REST calls: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is supported [default page size is 1000] 10 | # -> Check out pagination.py for example usage 11 | # Date Range is supported 12 | # -> Check out date-range.py for example usage 13 | # ---------------------------------------------------------------------- 14 | # The list can be filtered by various parameters, including: 15 | # filter.assetId: Specific asset id 16 | # filter.partyIds: Vega party ids (public keys) 17 | # filter.marketIds: Vega market ids 18 | # filter.accountTypes: Account types e.g. infrastructure, general, etc 19 | # ---------------------------------------------------------------------- 20 | # For full details see the REST Reference API docs at https://docs.vega.xyz 21 | 22 | import json 23 | import requests 24 | import helpers 25 | 26 | # Vega wallet interaction helper, see login.py for detail 27 | from login import pubkey 28 | 29 | # Load Vega data node API v2 URL, this is set using 'source vega-config' 30 | # located in the root folder of the sample-api-scripts repository 31 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 32 | 33 | ############################################################################### 34 | # 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 # 35 | ############################################################################### 36 | 37 | # Hint: Include multiple party ids as repeated filter.partyIds=XYZ query params 38 | # The same principle works for account types as shown below: 39 | 40 | # __get_balances_by_party_and_account_type: 41 | # Request a list of historic balance changes for a Vega party id and account types 42 | url = f"{data_node_url_rest}/balance/changes?filter.partyIds={pubkey}" \ 43 | f"&filter.accountTypes=ACCOUNT_TYPE_GENERAL&filter.accountTypes=ACCOUNT_TYPE_MARGIN" 44 | print(url) 45 | response = requests.get(url) 46 | helpers.check_response(response) 47 | response_json = response.json() 48 | print("Historic balance changes filtered by party and account types:\n{}".format( 49 | json.dumps(response_json, indent=2, sort_keys=True) 50 | )) 51 | # :get_balances_by_party_and_account_type__ 52 | 53 | # Load Vega market id 54 | market_id = helpers.env_market_id() 55 | assert market_id != "" 56 | 57 | ############################################################################### 58 | # 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 # 59 | ############################################################################### 60 | 61 | # Hint: Include multiple market ids as repeated filter.marketIds=XYZ query params 62 | # This is the same principle as in the previous example 63 | 64 | # __get_balances_by_market_and_account_type: 65 | # Request a list of historic balance changes for a Vega party id and account types 66 | url = f"{data_node_url_rest}/balance/changes?filter.marketIds={market_id}" \ 67 | f"&filter.accountTypes=ACCOUNT_TYPE_MARGIN" 68 | print(url) 69 | response = requests.get(url) 70 | helpers.check_response(response) 71 | response_json = response.json() 72 | print("Historic balance changes filtered by market and account types:\n{}".format( 73 | json.dumps(response_json, indent=2, sort_keys=True) 74 | )) 75 | # __get_balances_by_market_and_account_type: 76 | 77 | 78 | 79 | 80 | 81 | 82 | -------------------------------------------------------------------------------- /rest/stream-candles.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # S T R E A M C A N D L E S # 5 | ############################################################################### 6 | 7 | # How to stream candle information from a Data Node using Websockets: 8 | # ---------------------------------------------------------------------- 9 | # Pagination and Date Range are not supported, this is a realtime stream. 10 | # ---------------------------------------------------------------------- 11 | # The stream requires the following parameter: 12 | # candleId: Candle id (see below on how to retrieve this) 13 | # ---------------------------------------------------------------------- 14 | # For full details see the REST Reference API docs at https://docs.vega.xyz 15 | 16 | import websocket 17 | import threading 18 | import json 19 | import requests 20 | import helpers 21 | 22 | # Load Vega node API v2 URL, this is set using 'source vega-config' 23 | # located in the root folder of the sample-api-scripts repository 24 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 25 | 26 | # Load Vega market id 27 | market_id = helpers.env_market_id() 28 | assert market_id != "" 29 | 30 | # Hint: In order to get candles of a suitable bucket size e.g. 5 minutes and 31 | # market id e.g. 13b081fe5bc8fd256b0a374dc04d94b904118312dd0d942e891a5f57ce0c556c 32 | # you should use the list candle intervals API to get back a candle id: 33 | 34 | # __get_candle_intervals: 35 | # Request a list of candle intervals available for a market and select a candle id 36 | url = f"{data_node_url_rest}/candle/intervals?marketId={market_id}" 37 | response = requests.get(url) 38 | helpers.check_response(response) 39 | print("Candle intervals for market:\n{}".format( 40 | json.dumps(response.json(), indent=2, sort_keys=True))) 41 | # :get_candle_intervals__ 42 | 43 | # Find the first candle id in the list e.g. trades_candle_5_minutes_ etc 44 | candle_id = response.json()["intervalToCandleId"][0]["candleId"] 45 | assert candle_id != "" 46 | print(f"Candle found: {candle_id}") 47 | 48 | # Connect to the data node with a WSS based endpoint, this is not a HTTPS:// url 49 | # Hint: to include/filter data from a party add the param `partyId` 50 | # e.g. ?marketIds=xxx&partyId=yyy 51 | url = f"{data_node_url_rest}/stream/candle/data?candleId={candle_id}".replace("https://", "wss://") 52 | res = [] 53 | event = threading.Event() 54 | 55 | # __stream_candles_by_market: 56 | # Request a stream of candle updates for a market id and time bucket (e.g. candle id) on a Vega network 57 | 58 | def on_message(wsa, line): 59 | # Vega data-node v2 returns the json line by line so we need to wait 60 | # for a full structure before we can parse to valid JSON in python 61 | if line == "{": 62 | del res[:] 63 | res.append(line) 64 | elif line == "}": 65 | res.append(line) 66 | obj = json.loads(''.join(res)) 67 | if "candle" in obj["result"]: 68 | # When a new candle update arrives print the changes 69 | print(f"Candle data found:") 70 | print(obj["result"]["candle"]) 71 | else: 72 | res.append(line) 73 | 74 | 75 | def on_error(wsa, error): 76 | print(error) 77 | 78 | 79 | def on_close(wsa, close_status_code, close_msg): 80 | print(f"Candle stream closed: {url}") 81 | 82 | 83 | def on_open(wsa): 84 | print(f"Candle stream open: {url}") 85 | 86 | 87 | def timeout(): 88 | while not event.wait(timeout=30): 89 | ws.close() 90 | exit(1) 91 | 92 | 93 | thread = threading.Thread(target=timeout) 94 | thread.start() 95 | 96 | ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) 97 | ws.on_open = on_open 98 | ws.run_forever() 99 | # :stream_candles_by_market__ 100 | -------------------------------------------------------------------------------- /rest/liquidity-commitment-submit.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import json 4 | import time 5 | import requests 6 | import helpers 7 | 8 | # Vega wallet interaction helper, see login.py for detail 9 | from login import token, pubkey 10 | 11 | # Load Vega node API v2 URL, this is set using 'source vega-config' 12 | # located in the root folder of the sample-api-scripts repository 13 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 14 | # Load Vega wallet server URL, set in same way as above 15 | wallet_server_url = helpers.get_from_env("WALLET_SERVER_URL") 16 | 17 | # Load Vega market id 18 | market_id = helpers.env_market_id() 19 | assert market_id != "" 20 | 21 | # Set to False to ONLY submit/amend a liquidity commitment (no cancellation) 22 | CANCEL_LP_AFTER_SUBMISSION = True 23 | 24 | # Set market id in ENV or uncomment the line below to override market id directly 25 | market_id = "e503cadb437861037cddfd7263d25b69102098a97573db23f8e5fc320cea1ce9" 26 | 27 | ##################################################################################### 28 | # 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 # 29 | ##################################################################################### 30 | 31 | # Hint: commitmentAmount is an integer. For example 123456 is a price of 1.23456, 32 | # for a market which is configured to have a precision of 5 decimal places. 33 | 34 | # __create_liquidity_commitment: 35 | # Compose your submit liquidity provision command 36 | # Set your own user specific reference to find the commitment by reference and 37 | # as a foreign key to your local client/trading application 38 | liquidity_ref = f"{pubkey}-{helpers.generate_id(30)}" 39 | submission = { 40 | "liquidityProvisionSubmission": { 41 | "marketId": market_id, 42 | "commitmentAmount": "100", 43 | "fee": "0.01", 44 | "buys": [ 45 | { 46 | "offset": "1", 47 | "proportion": "1", 48 | "reference": "PEGGED_REFERENCE_MID" 49 | }, 50 | { 51 | "offset": "2", 52 | "proportion": "2", 53 | "reference": "PEGGED_REFERENCE_MID" 54 | } 55 | ], 56 | "sells": [ 57 | { 58 | "offset": "1", 59 | "proportion": "1", 60 | "reference": "PEGGED_REFERENCE_MID" 61 | }, 62 | { 63 | "offset": "2", 64 | "proportion": "2", 65 | "reference": "PEGGED_REFERENCE_MID" 66 | }, 67 | { 68 | "offset": "3", 69 | "proportion": "5", 70 | "reference": "PEGGED_REFERENCE_MID" 71 | } 72 | ], 73 | "reference": liquidity_ref 74 | }, 75 | "pubKey": pubkey, 76 | "propagate": True 77 | } 78 | # :create_liquidity_commitment__ 79 | 80 | print("Liquidity commitment submission:\n{}".format( 81 | json.dumps(submission, indent=2, sort_keys=True) 82 | )) 83 | 84 | # __sign_tx_liquidity_submit: 85 | # Sign the transaction with an liquidity commitment command 86 | # Hint: Setting propagate to true will also submit to a Vega node 87 | url = "http://localhost:1789/api/v2/requests" 88 | 89 | payload1 = { 90 | "id": "1", 91 | "jsonrpc": "2.0", 92 | "method": "client.send_transaction", 93 | "params": { 94 | "publicKey": pubkey, 95 | "sendingMode": "TYPE_SYNC", 96 | "transaction": submission 97 | } 98 | } 99 | 100 | payload = json.dumps(payload1) 101 | 102 | headers = { 103 | 'Content-Type': 'application/json-rpc', 104 | 'Accept': 'application/json-rpc', 105 | 'Origin': 'application/json-rpc', 106 | 'Authorization': f'{token}' 107 | } 108 | 109 | response = requests.request("POST", url, headers=headers, data=payload) 110 | 111 | print(response.text) 112 | # :sign_tx_liquidity_submit__ 113 | 114 | print(json.dumps(response.json(), indent=4, sort_keys=True)) 115 | print() 116 | 117 | print("Signed liquidity commitment and sent to Vega") 118 | print() 119 | 120 | # Wait for cancellation to be included in a block 121 | print("Waiting for blockchain...") 122 | time.sleep(3) 123 | -------------------------------------------------------------------------------- /rest/get-margin-levels.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # G E T M A R G I N L E V E L S # 5 | ############################################################################### 6 | 7 | # How to get margin level information from a Data Node using REST calls: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is supported [default page size is 1000] 10 | # -> Check out pagination.py for example usage 11 | # ---------------------------------------------------------------------- 12 | # The list can be filtered by various parameters, including: 13 | # partyId: Vega party id (public key) 14 | # marketId: Vega market id 15 | # ---------------------------------------------------------------------- 16 | # For full details see the REST Reference API docs at https://docs.vega.xyz 17 | 18 | import json 19 | import requests 20 | import helpers 21 | 22 | # Load Vega node API v2 URL, this is set using 'source vega-config' 23 | # located in the root folder of the sample-api-scripts repository 24 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 25 | market_id = helpers.env_market_id() 26 | party_id = helpers.env_party_id() 27 | 28 | ############################################################################### 29 | # L I S T M A R G I N L E V E L S # 30 | ############################################################################### 31 | 32 | # __get_margin_levels: 33 | # Request all margin level data for a Vega network 34 | url = f"{data_node_url_rest}/margin/levels" 35 | response = requests.get(url) 36 | helpers.check_response(response) 37 | print("Margin level data for network:\n{}".format( 38 | json.dumps(response.json(), indent=2, sort_keys=True) 39 | )) 40 | # :get_margin_levels__ 41 | 42 | # Find the first party and market id in the list (above) if they exists 43 | # Hint: Comment out following 4 lines to always use env party/market id values 44 | if helpers.check_nested_response(response, "marginLevels"): 45 | first_level = helpers.get_nested_response(response, "marginLevels")[0]["node"] 46 | party_id = first_level["partyId"] 47 | market_id = first_level["marketId"] 48 | 49 | ############################################################################### 50 | # M A R G I N L E V E L S B Y P A R T Y # 51 | ############################################################################### 52 | 53 | # __get_margin_levels_by_party: 54 | # Request margin level data for a specific party id (pubkey) 55 | url = f"{data_node_url_rest}/margin/levels?partyId={party_id}" 56 | response = requests.get(url) 57 | helpers.check_response(response) 58 | print("Margin level data for party:\n{}".format( 59 | json.dumps(response.json(), indent=2, sort_keys=True) 60 | )) 61 | # :get_margin_levels_by_party__ 62 | 63 | ############################################################################### 64 | # M A R G I N L E V E L S B Y M A R K E T # 65 | ############################################################################### 66 | 67 | # __get_margin_levels_by_market: 68 | # Request margin level data for a specific market id 69 | url = f"{data_node_url_rest}/margin/levels?marketId={market_id}" 70 | response = requests.get(url) 71 | helpers.check_response(response) 72 | print("Margin level data for market:\n{}".format( 73 | json.dumps(response.json(), indent=2, sort_keys=True) 74 | )) 75 | # :get_margin_levels_by_market__ 76 | 77 | ############################################################################### 78 | # 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 # 79 | ############################################################################### 80 | 81 | # __get_margin_levels_by_market_and_party: 82 | # Request margin level data for a specific market and party id 83 | url = f"{data_node_url_rest}/margin/levels?marketId={market_id}&partyId={party_id}" 84 | response = requests.get(url) 85 | helpers.check_response(response) 86 | print("Margin level data for market and party:\n{}".format( 87 | json.dumps(response.json(), indent=2, sort_keys=True) 88 | )) 89 | # :get_margin_levels_by_market_and_party__ 90 | -------------------------------------------------------------------------------- /rest/get-delegations.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # G E T D E L E G A T I O N S # 5 | ############################################################################### 6 | 7 | # How to get delegation (staking) information from a Data Node using REST calls: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is supported [default page size is 1000] 10 | # -> Check out pagination.py for example usage 11 | # ---------------------------------------------------------------------- 12 | # The list can be filtered by various parameters, including: 13 | # partyId: Vega party id (public key) 14 | # nodeId: Vega node id 15 | # epochId: Vega epoch id 16 | # ---------------------------------------------------------------------- 17 | # For full details see the REST Reference API docs at https://docs.vega.xyz 18 | 19 | import json 20 | import requests 21 | import helpers 22 | 23 | # Load Vega node API v2 URL, this is set using 'source vega-config' 24 | # located in the root folder of the sample-api-scripts repository 25 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 26 | 27 | ############################################################################### 28 | # L I S T D E L E G A T I O N S # 29 | ############################################################################### 30 | 31 | # __get_delegations: 32 | # Request a list of all delegations for a Vega network 33 | url = f"{data_node_url_rest}/delegations" 34 | response = requests.get(url) 35 | helpers.check_response(response) 36 | print("Delegations for network:\n{}".format( 37 | json.dumps(response.json(), indent=2, sort_keys=True) 38 | )) 39 | # :get_delegations__ 40 | 41 | # Find the first delegation in the list (above) and set epochId / nodeId vars 42 | first_delegation = helpers.get_nested_response(response, "delegations")[0] 43 | nodeId = first_delegation["node"]["nodeId"] 44 | epochId = first_delegation["node"]["epochSeq"] 45 | partyId = first_delegation["node"]["party"] 46 | 47 | # Tip: You can combine the filters epochId, partyId, and nodeId to refine the 48 | # returned delegation data, for instance, all delegations for party to a node 49 | # Each filter is shown below, but they can be combined as described... 50 | 51 | ############################################################################### 52 | # D E L E G A T I O N S B Y P A R T Y # 53 | ############################################################################### 54 | 55 | # __get_delegations_by_party: 56 | # Request a list of all delegations for a party (pubkey) 57 | url = f"{data_node_url_rest}/delegations?partyId={partyId}" 58 | response = requests.get(url) 59 | helpers.check_response(response) 60 | print("Delegations filtered by party:\n{}".format( 61 | json.dumps(response.json(), indent=2, sort_keys=True) 62 | )) 63 | # :get_delegations_by_party__ 64 | 65 | ############################################################################### 66 | # D E L E G A T I O N S B Y E P O C H # 67 | ############################################################################### 68 | 69 | # __get_delegations_by_epoch: 70 | # Request a list of all delegations for a specific epoch number 71 | url = f"{data_node_url_rest}/delegations?epochId={epochId}" 72 | response = requests.get(url) 73 | helpers.check_response(response) 74 | print("Delegations filtered by epoch:\n{}".format( 75 | json.dumps(response.json(), indent=2, sort_keys=True) 76 | )) 77 | # :get_delegations_by_epoch__ 78 | 79 | ############################################################################### 80 | # D E L E G A T I O N S B Y N O D E # 81 | ############################################################################### 82 | 83 | # __get_delegations_by_epoch: 84 | # Request a list of all delegations for a specific Vega node 85 | url = f"{data_node_url_rest}/delegations?nodeId={nodeId}" 86 | response = requests.get(url) 87 | helpers.check_response(response) 88 | print("Delegations filtered by Vega node:\n{}".format( 89 | json.dumps(response.json(), indent=2, sort_keys=True) 90 | )) 91 | # :get_delegations_by_epoch__ 92 | -------------------------------------------------------------------------------- /rest/date-range.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # D A T E / T I M E R A N G E S # 5 | ############################################################################### 6 | 7 | # Querying results within a particular date/time range is available on 8 | # selected Vega data node APIs. 9 | # 10 | # For example, a client may need to look at orders within a specific time 11 | # window or only find trades on a particular market from the last week. 12 | # 13 | # The examples shown below illustrate the basic concepts used with data returned 14 | # from most list endpoints in the Vega APIs, including (but not limited to): 15 | # - Trades 16 | # - Orders 17 | # - Parties 18 | # - Candles ( IMPORTANT: to/from candle time window is specified with to/fromTimestamp) 19 | # - Withdrawals 20 | # - Deposits 21 | # - Ledger entries 22 | # - Balance changes 23 | # - Liquidity provisions 24 | # - etc. 25 | # 26 | # The following parameters are typically used to control pagination: 27 | # dateRange.startTimestamp: Starting timestamp in nanoseconds past epoch 28 | # dateRange.endTimestamp: Ending timestamp in nanoseconds past epoch 29 | # 30 | # For full details see the REST Reference API docs at https://docs.vega.xyz 31 | 32 | import json 33 | import requests 34 | import helpers 35 | import datetime 36 | 37 | # Load Vega node API v2 URL, this is set using 'source vega-config' 38 | # located in the root folder of the sample-api-scripts repository 39 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 40 | 41 | # Load Vega market ID 42 | market_id = helpers.env_market_id() 43 | assert market_id != "" 44 | 45 | ############################################################################### 46 | # T I M E S T A M P G E N E R A T I O N # 47 | ############################################################################### 48 | 49 | # The majority of timestamps seen on Vega's APIs are of type RFC3339Nano, an 50 | # integer based representation of the number of nanoseconds that have passed 51 | # since Thursday 1 January 1970 00:00:00 UTC. 52 | # 53 | # When generating timestamps for a time window to be used in API queries the 54 | # caller needs to pay particular attention to the conversion. In most modern 55 | # programming languages a Unix timestamp can be generated relatively easily. 56 | # 57 | # The code example below shows how to convert a time to nanosecond timestamp 58 | # with a delta in seconds (subtract or add a number of seconds from time now): 59 | 60 | seconds_delta = 60 * 60 * 2 # Minus two hours from date/time now 61 | time_now = datetime.datetime.now() 62 | new_dt = time_now - datetime.timedelta(seconds=seconds_delta) 63 | ns_ts_from = str(int(new_dt.replace(tzinfo=datetime.timezone.utc).timestamp())*1000000000) 64 | ns_ts_to = str(int(time_now.replace(tzinfo=datetime.timezone.utc).timestamp())*1000000000) 65 | 66 | print(f"Current Time: {time_now}") 67 | print(f"Offset Time: {new_dt}") 68 | print(f"Current Timestamp: {ns_ts_to}") 69 | print(f"Offset: {ns_ts_from}") 70 | 71 | # Hint: In a decentralised system such as Vega we need to ideally use the time 72 | # provided by Vega's blockchain. It is advised that the caller use vega time 73 | # (see get-vega-time.py) for more information and examples. 74 | # 75 | # When using a date range, the result set will be paginated and the caller will 76 | # need to page the results (see pagination.py) 77 | 78 | ############################################################################### 79 | # T R A D E S D A T E / T I M E R A N G E # 80 | ############################################################################### 81 | 82 | # __get_trades_by_market_trades_date_range: 83 | # Request a list of trades for a market for the given date/time window 84 | url = f"{data_node_url_rest}/trades?marketId={market_id}" \ 85 | f"&dateRange.startTimestamp={ns_ts_from}" \ 86 | f"&dateRange.endTimestamp={ns_ts_to}" 87 | print(url) 88 | response = requests.get(url) 89 | helpers.check_response(response) 90 | response_json = response.json() 91 | print("Trades filtered by market (date/time range):\n{}".format( 92 | json.dumps(response_json, indent=2, sort_keys=True) 93 | )) 94 | # :get_trades_by_market_trades_date_range__ 95 | -------------------------------------------------------------------------------- /rest/pegged-order-cancel.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import requests 4 | import time 5 | import helpers 6 | import json 7 | 8 | # Vega wallet interaction helper, see login.py for detail 9 | from login import token, pubkey 10 | 11 | # Load Vega node API v2 URL, this is set using 'source vega-config' 12 | # located in the root folder of the sample-api-scripts repository 13 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 14 | # Load Vega wallet server URL, set in same way as above 15 | wallet_server_url = helpers.get_from_env("WALLET_SERVER_URL") 16 | 17 | # Load Vega market id 18 | market_id = helpers.env_market_id() 19 | assert market_id != "" 20 | 21 | # Set to False to ONLY submit/amend an order (no cancellation) 22 | # e.g. orders will remain on the book 23 | CANCEL_ORDER_AFTER_SUBMISSION = True 24 | 25 | # Set market id in ENV or uncomment the line below to override market id directly 26 | market_id = "e503cadb437861037cddfd7263d25b69102098a97573db23f8e5fc320cea1ce9" 27 | 28 | # Grab order reference from original order submission 29 | order_ref = "" 30 | 31 | url = f"{data_node_url_rest}/orders?partyId={pubkey}&reference={order_ref}" 32 | response = requests.get(url) 33 | 34 | found_order = helpers.get_nested_response(response, "orders")[0]["node"] 35 | 36 | orderID = found_order["id"] 37 | orderStatus = found_order["status"] 38 | createVersion = found_order["version"] 39 | orderPegged = found_order["peggedOrder"] 40 | ##################################################################################### 41 | # B L O C K C H A I N T I M E # 42 | ##################################################################################### 43 | 44 | # __get_expiry_time: 45 | # Request the current blockchain time, calculate an expiry time 46 | response = requests.get(f"{data_node_url_rest}/vega/time") 47 | helpers.check_response(response) 48 | blockchain_time = int(response.json()["timestamp"]) 49 | expiresAt = str(int(blockchain_time + 120 * 1e9)) # expire in 2 minutes 50 | # :get_expiry_time__ 51 | 52 | assert blockchain_time > 0 53 | print(f"Blockchain time: {blockchain_time}") 54 | 55 | ##################################################################################### 56 | # C A N C E L P E G G E D O R D E R # 57 | ##################################################################################### 58 | 59 | # Hint: For a full example with combinations please see submit-amend-cancel-order.py 60 | 61 | # __cancel_pegged_order: 62 | # # Cancellation command for the specific order 63 | cancellation = { 64 | "orderCancellation": { 65 | # Include market and order identifier fields to cancel single order. 66 | "marketId": market_id, 67 | "orderId": orderID, 68 | }, 69 | "pubKey": pubkey, 70 | "propagate": True, 71 | } 72 | # :cancel_pegged_order__ 73 | 74 | print() 75 | print("Pegged order cancellation: ", json.dumps(cancellation, indent=2, sort_keys=True)) 76 | print() 77 | 78 | # __sign_tx_pegged_cancel: 79 | # Sign the transaction for cancellation 80 | url = "http://localhost:1789/api/v2/requests" 81 | 82 | payload1 = { 83 | "id": "1", 84 | "jsonrpc": "2.0", 85 | "method": "client.send_transaction", 86 | "params": { 87 | "publicKey": pubkey, 88 | "sendingMode": "TYPE_SYNC", 89 | "transaction": cancellation 90 | } 91 | } 92 | 93 | payload = json.dumps(payload1) 94 | 95 | headers = { 96 | 'Content-Type': 'application/json-rpc', 97 | 'Accept': 'application/json-rpc', 98 | 'Origin': 'application/json-rpc', 99 | 'Authorization': f'{token}' 100 | } 101 | 102 | response = requests.request("POST", url, headers=headers, data=payload) 103 | 104 | print(response.text) 105 | # :sign_tx_pegged_cancel__ 106 | 107 | print("Signed pegged cancellation and sent to Vega") 108 | print() 109 | 110 | # Wait for cancellation to be included in a block 111 | print("Waiting for blockchain...") 112 | time.sleep(3) 113 | 114 | url = f"{data_node_url_rest}/orders?partyId={pubkey}&reference={order_ref}" 115 | response = requests.get(url) 116 | 117 | found_order = helpers.get_nested_response(response, "orders")[0]["node"] 118 | 119 | orderID = found_order["id"] 120 | orderStatus = found_order["status"] 121 | 122 | print("Cancelled pegged order:") 123 | print(f"ID: {orderID}, Status: {orderStatus}") 124 | if orderStatus == "STATUS_REJECTED": 125 | print("The pegged order cancellation was rejected by Vega") 126 | exit(1) # Halt processing at this stage 127 | 128 | print("Pegged order cancelled") 129 | -------------------------------------------------------------------------------- /rest/order-submit.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import requests 4 | import time 5 | import helpers 6 | import json 7 | 8 | # Vega wallet interaction helper, see login.py for detail 9 | from login import token, pubkey 10 | 11 | # Load Vega node API v2 URL, this is set using 'source vega-config' 12 | # located in the root folder of the sample-api-scripts repository 13 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 14 | # Load Vega wallet server URL, set in same way as above 15 | wallet_server_url = helpers.get_from_env("WALLET_SERVER_URL") 16 | 17 | # Load Vega market id 18 | market_id = helpers.env_market_id() 19 | assert market_id != "" 20 | 21 | # Set to False to ONLY submit/amend an order (no cancellation) 22 | # e.g. orders will remain on the book 23 | CANCEL_ORDER_AFTER_SUBMISSION = True 24 | 25 | # Set market id in ENV or uncomment the line below to override market id directly 26 | # market_id = "e503cadb437861037cddfd7263d25b69102098a97573db23f8e5fc320cea1ce9" 27 | 28 | ############################################################################### 29 | # B L O C K C H A I N T I M E # 30 | ############################################################################### 31 | 32 | # __get_expiry_time: 33 | # Request the current blockchain time, calculate an expiry time 34 | response = requests.get(f"{data_node_url_rest}/vega/time") 35 | helpers.check_response(response) 36 | blockchain_time = int(response.json()["timestamp"]) 37 | expiresAt = str(int(blockchain_time + 120 * 1e9)) # expire in 2 minutes 38 | # :get_expiry_time__ 39 | 40 | assert blockchain_time > 0 41 | print(f"Blockchain time: {blockchain_time}") 42 | 43 | 44 | ############################################################################### 45 | # S U B M I T O R D E R # 46 | ############################################################################### 47 | 48 | # __submit_order: 49 | # Compose your submit order command, with desired deal ticket information 50 | # Set your own user specific reference to find the order in next step and 51 | # as a foreign key to your local client/trading application 52 | order_ref = f"{pubkey}-{helpers.generate_id(30)}" 53 | submission = { 54 | "orderSubmission": { 55 | "marketId": market_id, 56 | "price": "1", # Hint: price is an integer. For example 123456 57 | "size": "100", # is a price of 1.23456, assuming 5 decimal places. 58 | "side": "SIDE_BUY", 59 | "timeInForce": "TIME_IN_FORCE_GTT", 60 | "expiresAt": expiresAt, 61 | "type": "TYPE_LIMIT", 62 | "reference": order_ref 63 | }, 64 | "pubKey": pubkey, 65 | "propagate": True 66 | } 67 | # :submit_order__ 68 | 69 | print("Order submission: ", json.dumps(submission, indent=2, sort_keys=True)) 70 | print() 71 | 72 | # __sign_tx_order: 73 | # Sign the transaction with an order submission command 74 | url = "http://localhost:1789/api/v2/requests" 75 | 76 | payload1 = { 77 | "id": "1", 78 | "jsonrpc": "2.0", 79 | "method": "client.send_transaction", 80 | "params": { 81 | "publicKey": pubkey, 82 | "sendingMode": "TYPE_SYNC", 83 | "transaction": submission 84 | } 85 | } 86 | 87 | payload = json.dumps(payload1) 88 | 89 | headers = { 90 | 'Content-Type': 'application/json-rpc', 91 | 'Accept': 'application/json-rpc', 92 | 'Origin': 'application/json-rpc', 93 | 'Authorization': f'{token}' 94 | } 95 | 96 | response = requests.request("POST", url, headers=headers, data=payload) 97 | 98 | print(response.text) 99 | # :sign_tx_order__ 100 | 101 | print(json.dumps(response.json(), indent=4, sort_keys=True)) 102 | print() 103 | 104 | print("Signed order and sent to Vega") 105 | 106 | # Wait for order submission to be included in a block 107 | print("Waiting for blockchain...", end="", flush=True) 108 | url = f"{data_node_url_rest}/orders?partyId={pubkey}&reference={order_ref}" 109 | response = requests.get(url) 110 | while helpers.check_nested_response(response, "orders") is not True: 111 | time.sleep(0.5) 112 | print(".", end="", flush=True) 113 | response = requests.get(url) 114 | 115 | found_order = helpers.get_nested_response(response, "orders")[0]["node"] 116 | 117 | orderID = found_order["id"] 118 | orderStatus = found_order["status"] 119 | createVersion = found_order["version"] 120 | 121 | print() 122 | print(f"\nOrder processed, ID: {orderID}, Status: {orderStatus}, Version: {createVersion}") 123 | if orderStatus == "STATUS_REJECTED": 124 | print("The order was rejected by Vega") 125 | exit(1) # Halt processing at this stage 126 | -------------------------------------------------------------------------------- /rest/pegged-order-submit.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import requests 4 | import time 5 | import helpers 6 | import json 7 | 8 | # Vega wallet interaction helper, see login.py for detail 9 | from login import token, pubkey 10 | 11 | # Load Vega node API v2 URL, this is set using 'source vega-config' 12 | # located in the root folder of the sample-api-scripts repository 13 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 14 | # Load Vega wallet server URL, set in same way as above 15 | wallet_server_url = helpers.get_from_env("WALLET_SERVER_URL") 16 | 17 | # Load Vega market id 18 | market_id = helpers.env_market_id() 19 | assert market_id != "" 20 | 21 | # Set to False to ONLY submit/amend an order (no cancellation) 22 | # e.g. orders will remain on the book 23 | CANCEL_ORDER_AFTER_SUBMISSION = True 24 | 25 | # Set market id in ENV or uncomment the line below to override market id directly 26 | market_id = "e503cadb437861037cddfd7263d25b69102098a97573db23f8e5fc320cea1ce9" 27 | 28 | ##################################################################################### 29 | # B L O C K C H A I N T I M E # 30 | ##################################################################################### 31 | 32 | # __get_expiry_time: 33 | # Request the current blockchain time, calculate an expiry time 34 | response = requests.get(f"{data_node_url_rest}/vega/time") 35 | helpers.check_response(response) 36 | blockchain_time = int(response.json()["timestamp"]) 37 | expiresAt = str(int(blockchain_time + 120 * 1e9)) # expire in 2 minutes 38 | # :get_expiry_time__ 39 | 40 | assert blockchain_time > 0 41 | print(f"Blockchain time: {blockchain_time}") 42 | 43 | ##################################################################################### 44 | # S U B M I T P E G G E D O R D E R # 45 | ##################################################################################### 46 | 47 | # __submit_pegged_order: 48 | # Compose your submit pegged order command 49 | # Set your own user specific reference to find the order in next step and 50 | # as a foreign key to your local client/trading application 51 | order_ref = f"{pubkey}-{helpers.generate_id(30)}" 52 | submission = { 53 | "orderSubmission": { 54 | "marketId": market_id, 55 | "size": "50", 56 | "side": "SIDE_BUY", 57 | "timeInForce": "TIME_IN_FORCE_GTT", 58 | "expiresAt": expiresAt, 59 | "type": "TYPE_LIMIT", 60 | "reference": order_ref, 61 | "peggedOrder": { 62 | "offset": "5", 63 | "reference": "PEGGED_REFERENCE_MID" 64 | } 65 | }, 66 | "pubKey": pubkey, 67 | "propagate": True 68 | } 69 | # :submit_pegged_order__ 70 | 71 | print() 72 | print("Pegged order submission: ", json.dumps(submission, indent=2, sort_keys=True)) 73 | print() 74 | 75 | # __sign_tx_pegged_order: 76 | # Sign the transaction with a pegged order submission command 77 | url = "http://localhost:1789/api/v2/requests" 78 | 79 | payload1 = { 80 | "id": "1", 81 | "jsonrpc": "2.0", 82 | "method": "client.send_transaction", 83 | "params": { 84 | "publicKey": pubkey, 85 | "sendingMode": "TYPE_SYNC", 86 | "transaction": submission 87 | } 88 | } 89 | 90 | payload = json.dumps(payload1) 91 | 92 | headers = { 93 | 'Content-Type': 'application/json-rpc', 94 | 'Accept': 'application/json-rpc', 95 | 'Origin': 'application/json-rpc', 96 | 'Authorization': f'{token}' 97 | } 98 | 99 | response = requests.request("POST", url, headers=headers, data=payload) 100 | 101 | print(response.text) 102 | # :sign_tx_pegged_order__ 103 | 104 | print(json.dumps(response.json(), indent=4, sort_keys=True)) 105 | print() 106 | 107 | print("Signed pegged order and sent to Vega") 108 | 109 | # Wait for order submission to be included in a block 110 | print("Waiting for blockchain...", end="", flush=True) 111 | url = f"{data_node_url_rest}/orders?partyId={pubkey}&reference={order_ref}" 112 | response = requests.get(url) 113 | while helpers.check_nested_response(response, "orders") is not True: 114 | time.sleep(0.5) 115 | print(".", end="", flush=True) 116 | response = requests.get(url) 117 | 118 | found_order = helpers.get_nested_response(response, "orders")[0]["node"] 119 | 120 | orderID = found_order["id"] 121 | orderStatus = found_order["status"] 122 | createVersion = found_order["version"] 123 | orderPegged = found_order["peggedOrder"] 124 | 125 | print() 126 | print(f"\nPegged order processed, ID: {orderID}, Status: {orderStatus}, Version: {createVersion}") 127 | if orderStatus == "STATUS_REJECTED": 128 | print("The pegged order was rejected by Vega") 129 | exit(1) # Halt processing at this stage 130 | else: 131 | print(f"Pegged at: {orderPegged}") -------------------------------------------------------------------------------- /rest/order-amend.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import requests 4 | import time 5 | import helpers 6 | import json 7 | 8 | # Vega wallet interaction helper, see login.py for detail 9 | from login import token, pubkey 10 | 11 | # Load Vega node API v2 URL, this is set using 'source vega-config' 12 | # located in the root folder of the sample-api-scripts repository 13 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 14 | # Load Vega wallet server URL, set in same way as above 15 | wallet_server_url = helpers.get_from_env("WALLET_SERVER_URL") 16 | 17 | # Load Vega market id 18 | market_id = helpers.env_market_id() 19 | assert market_id != "" 20 | 21 | # Set to False to ONLY submit/amend an order (no cancellation) 22 | # e.g. orders will remain on the book 23 | CANCEL_ORDER_AFTER_SUBMISSION = True 24 | 25 | # Set market id in ENV or uncomment the line below to override market id directly 26 | market_id = "e503cadb437861037cddfd7263d25b69102098a97573db23f8e5fc320cea1ce9" 27 | 28 | # Grab order reference from original order submission 29 | order_ref = "" 30 | url = f"{data_node_url_rest}/orders?partyId={pubkey}&reference={order_ref}" 31 | response = requests.get(url) 32 | 33 | found_order = helpers.get_nested_response(response, "orders")[0]["node"] 34 | 35 | orderID = found_order["id"] 36 | orderStatus = found_order["status"] 37 | createVersion = found_order["version"] 38 | 39 | ############################################################################### 40 | # B L O C K C H A I N T I M E # 41 | ############################################################################### 42 | 43 | # __get_expiry_time: 44 | # Request the current blockchain time, calculate an expiry time 45 | response = requests.get(f"{data_node_url_rest}/vega/time") 46 | helpers.check_response(response) 47 | blockchain_time = int(response.json()["timestamp"]) 48 | expiresAt = str(int(blockchain_time + 120 * 1e9)) # expire in 2 minutes 49 | # :get_expiry_time__ 50 | 51 | assert blockchain_time > 0 52 | print(f"Blockchain time: {blockchain_time}") 53 | 54 | ##################################################################################### 55 | # A M E N D O R D E R # 56 | ##################################################################################### 57 | 58 | # __amend_order: 59 | # Compose your amend order command, with changes to existing order 60 | amendment = { 61 | "orderAmendment": { 62 | "orderId": orderID, 63 | "marketId": market_id, 64 | "price": "2", 65 | "sizeDelta": "-25", 66 | "timeInForce": "TIME_IN_FORCE_GTC", 67 | }, 68 | "pubKey": pubkey, 69 | "propagate": True 70 | } 71 | # :amend_order__ 72 | 73 | print() 74 | print("Order amendment: ", json.dumps(amendment, indent=2, sort_keys=True)) 75 | print() 76 | 77 | # __sign_tx_amend: 78 | # Sign the transaction with an order amendment command 79 | url = "http://localhost:1789/api/v2/requests" 80 | 81 | payload1 = { 82 | "id": "1", 83 | "jsonrpc": "2.0", 84 | "method": "client.send_transaction", 85 | "params": { 86 | "publicKey": pubkey, 87 | "sendingMode": "TYPE_SYNC", 88 | "transaction": amendment 89 | } 90 | } 91 | 92 | payload = json.dumps(payload1) 93 | 94 | headers = { 95 | 'Content-Type': 'application/json-rpc', 96 | 'Accept': 'application/json-rpc', 97 | 'Origin': 'application/json-rpc', 98 | 'Authorization': f'{token}' 99 | } 100 | 101 | response = requests.request("POST", url, headers=headers, data=payload) 102 | 103 | print(response.text) 104 | # :sign_tx_amend__ 105 | 106 | print("Signed amendment and sent to Vega") 107 | 108 | # Wait for amendment to be included in a block 109 | print("Waiting for blockchain...", end="", flush=True) 110 | time.sleep(3) 111 | 112 | url = f"{data_node_url_rest}/orders?partyId={pubkey}&reference={order_ref}" 113 | response = requests.get(url) 114 | 115 | found_order = helpers.get_nested_response(response, "orders")[0]["node"] 116 | 117 | orderID = found_order["id"] 118 | orderPrice = found_order["price"] 119 | orderSize = found_order["size"] 120 | orderTif = found_order["timeInForce"] 121 | orderStatus = found_order["status"] 122 | orderVersion = found_order["version"] 123 | 124 | print() 125 | print("Amended Order:") 126 | print(f"ID: {orderID}, Status: {orderStatus}, Price(Old): 1, " 127 | f"Price(New): {orderPrice}, Size(Old): 100, Size(New): {orderSize}, " 128 | f"TimeInForce(Old): TIME_IN_FORCE_GTT, TimeInForce(New): {orderTif}, " 129 | f"Version(Old): {createVersion}, Version(new): {orderVersion}") 130 | if orderStatus == "STATUS_REJECTED": 131 | print("The order amendment was rejected by Vega") 132 | exit(1) # Halt processing at this stage 133 | 134 | if CANCEL_ORDER_AFTER_SUBMISSION is not True: 135 | exit(1) 136 | -------------------------------------------------------------------------------- /rest/order-cancel.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import requests 4 | import time 5 | import helpers 6 | import json 7 | 8 | # Vega wallet interaction helper, see login.py for detail 9 | from login import token, pubkey 10 | 11 | # Load Vega node API v2 URL, this is set using 'source vega-config' 12 | # located in the root folder of the sample-api-scripts repository 13 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 14 | # Load Vega wallet server URL, set in same way as above 15 | wallet_server_url = helpers.get_from_env("WALLET_SERVER_URL") 16 | 17 | # Load Vega market id 18 | market_id = helpers.env_market_id() 19 | assert market_id != "" 20 | 21 | # Set market id in ENV or uncomment the line below to override market id directly 22 | market_id = "e503cadb437861037cddfd7263d25b69102098a97573db23f8e5fc320cea1ce9" 23 | 24 | # Grab order reference from original order submission 25 | order_ref = "" 26 | url = f"{data_node_url_rest}/orders?partyId={pubkey}&reference={order_ref}" 27 | response = requests.get(url) 28 | 29 | found_order = helpers.get_nested_response(response, "orders")[0]["node"] 30 | 31 | orderID = found_order["id"] 32 | orderStatus = found_order["status"] 33 | createVersion = found_order["version"] 34 | 35 | ############################################################################### 36 | # B L O C K C H A I N T I M E # 37 | ############################################################################### 38 | 39 | # __get_expiry_time: 40 | # Request the current blockchain time, calculate an expiry time 41 | response = requests.get(f"{data_node_url_rest}/vega/time") 42 | helpers.check_response(response) 43 | blockchain_time = int(response.json()["timestamp"]) 44 | expiresAt = str(int(blockchain_time + 120 * 1e9)) # expire in 2 minutes 45 | # :get_expiry_time__ 46 | 47 | assert blockchain_time > 0 48 | print(f"Blockchain time: {blockchain_time}") 49 | 50 | ##################################################################################### 51 | # C A N C E L O R D E R S # 52 | ##################################################################################### 53 | 54 | # Select the mode to cancel orders from the following (comment out others), default = 3 55 | 56 | # __cancel_order_req1: 57 | # 1 - Cancel single order for party (pubkey) 58 | cancellation = { 59 | "orderCancellation": { 60 | # Include market and order identifier fields to cancel single order. 61 | "marketId": market_id, 62 | "orderId": orderID, 63 | }, 64 | "pubKey": pubkey, 65 | "propagate": True, 66 | } 67 | # :cancel_order_req1__ 68 | 69 | # __cancel_order_req2: 70 | # 2 - Cancel all orders on market for party (pubkey) 71 | cancellation = { 72 | "orderCancellation": { 73 | # Only include market identifier field. 74 | "marketId": market_id, 75 | }, 76 | "pubKey": pubkey, 77 | "propagate": True, 78 | } 79 | # :cancel_order_req2__ 80 | 81 | # __cancel_order_req3: 82 | # 3 - Cancel all orders on all markets for party (pubkey) 83 | cancellation = { 84 | "orderCancellation": {}, 85 | "pubKey": pubkey, 86 | "propagate": True, 87 | } 88 | # :cancel_order_req3__ 89 | 90 | print() 91 | print("Order cancellation: ", json.dumps(cancellation, indent=2, sort_keys=True)) 92 | print() 93 | 94 | # __sign_tx_cancel: 95 | # Sign the transaction for cancellation 96 | url = "http://localhost:1789/api/v2/requests" 97 | 98 | payload1 = { 99 | "id": "1", 100 | "jsonrpc": "2.0", 101 | "method": "client.send_transaction", 102 | "params": { 103 | "publicKey": pubkey, 104 | "sendingMode": "TYPE_SYNC", 105 | "transaction": cancellation 106 | } 107 | } 108 | 109 | payload = json.dumps(payload1) 110 | 111 | headers = { 112 | 'Content-Type': 'application/json-rpc', 113 | 'Accept': 'application/json-rpc', 114 | 'Origin': 'application/json-rpc', 115 | 'Authorization': f'{token}' 116 | } 117 | 118 | response = requests.request("POST", url, headers=headers, data=payload) 119 | 120 | print(response.text) 121 | # :sign_tx_cancel__ 122 | 123 | print("Signed cancellation and sent to Vega") 124 | print() 125 | 126 | # Wait for cancellation to be included in a block 127 | print("Waiting for blockchain...") 128 | time.sleep(3) 129 | 130 | url = f"{data_node_url_rest}/orders?partyId={pubkey}&reference={order_ref}" 131 | response = requests.get(url) 132 | 133 | found_order = helpers.get_nested_response(response, "orders")[0]["node"] 134 | 135 | orderID = found_order["id"] 136 | orderStatus = found_order["status"] 137 | 138 | print("Cancelled Order(s):") 139 | print(f"ID: {orderID}, Status: {orderStatus}") 140 | if orderStatus == "STATUS_REJECTED": 141 | print("The order cancellation was rejected by Vega") 142 | exit(1) # Halt processing at this stage 143 | 144 | print("Order(s) cancelled") 145 | -------------------------------------------------------------------------------- /rest/pegged-order-amend.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import requests 4 | import time 5 | import helpers 6 | import json 7 | 8 | # Vega wallet interaction helper, see login.py for detail 9 | from login import token, pubkey 10 | 11 | # Load Vega node API v2 URL, this is set using 'source vega-config' 12 | # located in the root folder of the sample-api-scripts repository 13 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 14 | # Load Vega wallet server URL, set in same way as above 15 | wallet_server_url = helpers.get_from_env("WALLET_SERVER_URL") 16 | 17 | # Load Vega market id 18 | market_id = helpers.env_market_id() 19 | assert market_id != "" 20 | 21 | # Set to False to ONLY submit/amend an order (no cancellation) 22 | # e.g. orders will remain on the book 23 | CANCEL_ORDER_AFTER_SUBMISSION = True 24 | 25 | # Set market id in ENV or uncomment the line below to override market id directly 26 | market_id = "e503cadb437861037cddfd7263d25b69102098a97573db23f8e5fc320cea1ce9" 27 | 28 | # Grab order reference from original order submission 29 | order_ref = "" 30 | 31 | url = f"{data_node_url_rest}/orders?partyId={pubkey}&reference={order_ref}" 32 | response = requests.get(url) 33 | 34 | found_order = helpers.get_nested_response(response, "orders")[0]["node"] 35 | 36 | orderID = found_order["id"] 37 | orderStatus = found_order["status"] 38 | createVersion = found_order["version"] 39 | orderPegged = found_order["peggedOrder"] 40 | 41 | ##################################################################################### 42 | # B L O C K C H A I N T I M E # 43 | ##################################################################################### 44 | 45 | # __get_expiry_time: 46 | # Request the current blockchain time, calculate an expiry time 47 | response = requests.get(f"{data_node_url_rest}/vega/time") 48 | helpers.check_response(response) 49 | blockchain_time = int(response.json()["timestamp"]) 50 | expiresAt = str(int(blockchain_time + 120 * 1e9)) # expire in 2 minutes 51 | # :get_expiry_time__ 52 | 53 | assert blockchain_time > 0 54 | print(f"Blockchain time: {blockchain_time}") 55 | 56 | ##################################################################################### 57 | # A M E N D P E G G E D O R D E R # 58 | ##################################################################################### 59 | 60 | # __amend_pegged_order: 61 | # Compose your amend order command, with changes to existing order 62 | amendment = { 63 | "orderAmendment": { 64 | "orderId": orderID, 65 | "marketId": market_id, 66 | "sizeDelta": "25", 67 | "timeInForce": "TIME_IN_FORCE_GTC", 68 | "peggedReference": "PEGGED_REFERENCE_BEST_BID", 69 | "peggedOffset": "-100", 70 | }, 71 | "pubKey": pubkey, 72 | "propagate": True 73 | } 74 | # :amend_pegged_order__ 75 | 76 | print() 77 | print("Pegged order amendment: ", json.dumps(amendment, indent=2, sort_keys=True)) 78 | print() 79 | 80 | # __sign_tx_pegged_amend: 81 | # Sign the transaction with a pegged order amendment command 82 | url = "http://localhost:1789/api/v2/requests" 83 | 84 | payload1 = { 85 | "id": "1", 86 | "jsonrpc": "2.0", 87 | "method": "client.send_transaction", 88 | "params": { 89 | "publicKey": pubkey, 90 | "sendingMode": "TYPE_SYNC", 91 | "transaction": amendment 92 | } 93 | } 94 | 95 | payload = json.dumps(payload1) 96 | 97 | headers = { 98 | 'Content-Type': 'application/json-rpc', 99 | 'Accept': 'application/json-rpc', 100 | 'Origin': 'application/json-rpc', 101 | 'Authorization': f'{token}' 102 | } 103 | 104 | response = requests.request("POST", url, headers=headers, data=payload) 105 | 106 | print(response.text) 107 | # :sign_tx_pegged_amend__ 108 | 109 | print("Signed pegged order amendment and sent to Vega") 110 | 111 | # Wait for order amendment to be included in a block 112 | print("Waiting for blockchain...") 113 | time.sleep(3) 114 | 115 | url = f"{data_node_url_rest}/orders?partyId={pubkey}&reference={order_ref}" 116 | response = requests.get(url) 117 | 118 | found_order = helpers.get_nested_response(response, "orders")[0]["node"] 119 | 120 | orderID = found_order["id"] 121 | orderStatus = found_order["status"] 122 | orderVersion = found_order["version"] 123 | orderPegged = found_order["peggedOrder"] 124 | orderPrice = found_order["price"] 125 | orderSize = found_order["size"] 126 | orderTif = found_order["timeInForce"] 127 | 128 | print() 129 | print("Amended pegged order:") 130 | print(f"ID: {orderID}, Status: {orderStatus}, " 131 | f"Size(Old): 50, Size(New): {orderSize}, " 132 | f"TimeInForce(Old): TIME_IN_FORCE_GTT, TimeInForce(New): {orderTif}, " 133 | f"Version(Old): {createVersion}, Version(new): {orderVersion}") 134 | 135 | if orderStatus == "STATUS_REJECTED": 136 | print("The pegged order amendment was rejected by Vega") 137 | exit(1) # Halt processing at this stage 138 | else: 139 | print(f"Pegged at: {orderPegged}") 140 | -------------------------------------------------------------------------------- /rest/get-trades.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # G E T T R A D E S # 5 | ############################################################################### 6 | 7 | # How to get trade information from a Data Node using REST calls: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is supported [default page size is 1000] 10 | # -> Check out pagination.py for example usage 11 | # Date Range is supported 12 | # -> Check out date-range.py for example usage 13 | # ---------------------------------------------------------------------- 14 | # The list can be filtered by various parameters, including: 15 | # partyId: Vega party id (public key) 16 | # marketId: Vega market id 17 | # orderId: Vega order id 18 | # ---------------------------------------------------------------------- 19 | # For full details see the REST Reference API docs at https://docs.vega.xyz 20 | 21 | import json 22 | import requests 23 | import helpers 24 | 25 | # Vega wallet interaction helper, see login.py for detail 26 | from login import pubkey 27 | 28 | # Load Vega node API v2 URL, this is set using 'source vega-config' 29 | # located in the root folder of the sample-api-scripts repository 30 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 31 | 32 | ############################################################################### 33 | # T R A D E S B Y M A R K E T # 34 | ############################################################################### 35 | 36 | market_id = helpers.env_market_id() 37 | assert market_id != "" 38 | 39 | # __get_trades_by_market: 40 | # Request a list of trades for a market 41 | url = f"{data_node_url_rest}/trades?marketId={market_id}" 42 | response = requests.get(url) 43 | helpers.check_response(response) 44 | response_json = response.json() 45 | print("Trades filtered by market:\n{}".format( 46 | json.dumps(response_json, indent=2, sort_keys=True) 47 | )) 48 | # :get_trades_by_market__ 49 | 50 | # Find the first trade in the list (above) if it exists 51 | trade_id = "6a834328d835ca79880dfc238a989c238fe32a62562690d717ab1ff42ad5004d" 52 | order_id = "165968e2f7d488bc2d55b5da6a9137af207b839c3241352253ef1c2c253eb620" 53 | if helpers.check_nested_response(response, "trades"): 54 | first_trade = helpers.get_nested_response(response, "trades")[0]["node"] 55 | trade_id = first_trade["id"] 56 | order_id = first_trade["buyOrder"] 57 | 58 | ############################################################################### 59 | # T R A D E S B Y P A R T Y # 60 | ############################################################################### 61 | 62 | # __get_trades_by_party: 63 | # Request a list of trades for a party (pubkey) on a Vega network 64 | url = f"{data_node_url_rest}/trades?partyId={pubkey}" 65 | print(url) 66 | response = requests.get(url) 67 | helpers.check_response(response) 68 | response_json = response.json() 69 | print("Trades filtered by party:\n{}".format( 70 | json.dumps(response_json, indent=2, sort_keys=True) 71 | )) 72 | # :get_trades_by_party__ 73 | 74 | ############################################################################### 75 | # T R A D E S B Y O R D E R I D # 76 | ############################################################################### 77 | 78 | # __get_trades_by_order: 79 | # Request a list of orders with a matching custom reference string 80 | url = f"{data_node_url_rest}/trades?orderId={order_id}" 81 | print(url) 82 | response = requests.get(url) 83 | helpers.check_response(response) 84 | print("Trades by order:\n{}".format( 85 | json.dumps(response.json(), indent=2, sort_keys=True))) 86 | # :get_trades_by_order__ 87 | 88 | ############################################################################### 89 | # T R A D E B Y I D # 90 | ############################################################################### 91 | # todo: uncomment below when work done to add trade by ID to v2 API 92 | 93 | # Note: Requesting a trade by ID is a different REST route to listing trades 94 | # and therefore it does not have filters or pagination (unlike the above requests) 95 | 96 | # __get_trade_by_id: 97 | # Request a specific trade using a pre-defined trade id 98 | # url = f"{data_node_url_rest}/trade/{trade_id}" 99 | # response = requests.get(url) 100 | # helpers.check_response(response) 101 | # print("Trade:\n{}".format( 102 | # json.dumps(response.json(), indent=2, sort_keys=True))) 103 | # :get_trade_by_id__ 104 | 105 | ############################################################################### 106 | # L A T E S T T R A D E # 107 | ############################################################################### 108 | 109 | # __get_latest_trade: 110 | # Request the latest trade on a given Vega market 111 | url = f"{data_node_url_rest}/market/{market_id}/trade/latest" 112 | response = requests.get(url) 113 | helpers.check_response(response) 114 | print("Latest trade:\n{}".format( 115 | json.dumps(response.json(), indent=2, sort_keys=True))) 116 | # :get_latest_trade__ 117 | 118 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Sample API Scripts 3 | 4 | **This repo is not maintained and scripts may be out of date.** 5 | 6 | This repo contains Vega code examples in Python. These scripts use the Vega data-node and wallet APIs to interact with a Vega network. 7 | 8 | With Vega users can consume APIs on the network using three different options (navigate through to your desired set of scripts): 9 | 10 | * **[REST](./rest#readme)** 11 | * **[GraphQL](./graphql#readme)** 12 | 13 | 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. 14 | 15 | For example, show me a list of trades on a particular market, stream my latest orders or submit a new liquidity commitment, etc. 16 | 17 | 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** 18 | 19 | ## Gitpod 20 | 21 | 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. 22 | 23 | [![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) 24 | 25 | Click on the "Gitpod ready-to-code" button above to load a browser based linux development environment and start experimenting straight away. 26 | 27 | ## Getting started for Unix based systems (Gitpod, Mac OS & Linux) 28 | 29 | 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. 30 | ```bash 31 | git clone https://github.com/vegaprotocol/sample-api-scripts.git 32 | ``` 33 | This should create you a folder named `sample-api-scripts` that you will use for the rest of this README. 34 | *Note: When running on Gitpod this is already done for you.* 35 | 36 | 1. Import the appropriate `vega-config` into your local environment for the network you want to test against (default vega-config is Fairground testnet). 37 | ``` 38 | source vega-config 39 | ``` 40 | 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.* 41 | 42 | 1. Navigate to the API transport you would like to explore, for example: 43 | ``` 44 | cd ./rest 45 | ``` 46 | 47 | 1. Follow the sub-folder README.md information on how to run the samples. 48 | 49 | 1. For most scripts, you will have to run the login script **before** running the script in question. It's also important to note that you should have a desktop or CLI wallet connection open as you run this script, otherwise the connection will be refused. 50 | 51 | ``` 52 | python3 login.py 53 | ``` 54 | 55 | # Getting started for Windows 56 | 57 | 1. Clone this repo onto your local machine so you have access to all the files and can change them as you need. 58 | ```bash 59 | git clone git@github.com:vegaprotocol/sample-api-scripts.git 60 | ``` 61 | This should create you a folder named `sample-api-scripts` that you will use for the rest of this README. 62 | 63 | 1. Import the appropriate `vega-config-win.bat` into your local environment for the network you want to test against (default is Fairground testnet). Simply run this batch script in your terminal: 64 | ``` 65 | vega-config-win.bat 66 | ``` 67 | 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. *Note: Don't forget to rerun this after making any config changes.* 68 | 69 | 70 | 1. Navigate to the API transport you would like to explore, for example: 71 | ``` 72 | cd rest 73 | ``` 74 | 75 | 1. Follow the sub-folder README.md information on how to run the samples. 76 | 77 | 1. For most scripts, you will have to run the login script **before** running the script in question. It's also important to note that you should have a desktop or CLI wallet connection open as you run this script, otherwise the connection will be refused. 78 | 79 | ``` 80 | python3 login.py 81 | ``` 82 | 83 | # Video Walkthrough 84 | 85 | This quick [video](https://www.loom.com/share/09407b46492a49afa0ad7ae4d6098559) walks you through how to log in to the sample scripts. 86 | 87 | # Future Improvements 88 | 89 | We are constantly trying to improve these sample scripts and keep them up to date with Vega's most recent software releases. Below is a future roadmap for the sample-api-scripts, including what we will add next: 90 | 91 | - Add more transaction scripts 92 | - Basic CI support through Github Actions 93 | - Add support for gRPC 94 | 95 | 96 | # Contributing or raising issues 97 | 98 | 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/). 99 | 100 | 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. 101 | -------------------------------------------------------------------------------- /rest/get-accounts.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ############################################################################### 4 | # G E T A C C O U N T S # 5 | ############################################################################### 6 | 7 | # How to get Vega account information from a Data Node using REST calls: 8 | # ---------------------------------------------------------------------- 9 | # Pagination is supported [default page size is 1000] 10 | # -> Check out pagination.py for example usage 11 | # ---------------------------------------------------------------------- 12 | # The list can be filtered by various parameters, including: 13 | # filter.partyIds: Vega party ids (public keys) 14 | # filter.marketIds: Vega market ids 15 | # filter.assets: Specific asset ids e.g. if for tDAI, tBTC, etc 16 | # filter.accountTypes: Account types e.g. infrastructure, general, etc 17 | # ---------------------------------------------------------------------- 18 | # For full details see the REST Reference API docs at https://docs.vega.xyz 19 | 20 | import json 21 | import requests 22 | import helpers 23 | 24 | # Vega wallet interaction helper, see login.py for detail 25 | from login import pubkey 26 | 27 | # Load Vega data node API v2 URL, this is set using 'source vega-config' 28 | # located in the root folder of the sample-api-scripts repository 29 | data_node_url_rest = helpers.get_from_env("DATA_NODE_URL_REST") 30 | 31 | ############################################################################### 32 | # A C C O U N T S B Y M A R K E T ( 1 ) # 33 | ############################################################################### 34 | 35 | market_id = helpers.env_market_id() 36 | assert market_id != "" 37 | 38 | # __get_accounts_by_market: 39 | # Request a list of accounts for a single market (repeat the filter for multiple markets) 40 | url = f"{data_node_url_rest}/accounts?filter.marketIds={market_id}" 41 | response = requests.get(url) 42 | helpers.check_response(response) 43 | print("Accounts filtered by market:\n{}".format( 44 | json.dumps(response.json(), indent=2, sort_keys=True) 45 | )) 46 | # :get_accounts_by_market__ 47 | 48 | # Hint: Multiple filtering examples further down in this example script 49 | 50 | ############################################################################### 51 | # A C C O U N T S B Y P A R T Y ( 1 ) # 52 | ############################################################################### 53 | 54 | # __get_accounts_by_party: 55 | # Request a list of accounts for a single party/pubkey (repeat the filter for multiple parties) 56 | url = f"{data_node_url_rest}/accounts?filter.partyIds={pubkey}" 57 | response = requests.get(url) 58 | helpers.check_response(response) 59 | print("Accounts filtered by party:\n{}".format( 60 | json.dumps(response.json(), indent=2, sort_keys=True) 61 | )) 62 | # :get_accounts_by_party__ 63 | 64 | # Hint: Multiple filtering examples further down in this example script 65 | 66 | ############################################################################### 67 | # A C C O U N T S B Y A S S E T # 68 | ############################################################################### 69 | 70 | # Request a list of assets and select the first one 71 | url = f"{data_node_url_rest}/assets" 72 | response = requests.get(url) 73 | helpers.check_response(response) 74 | asset_id = response.json()["assets"]["edges"][0]["node"]["id"] 75 | 76 | assert asset_id != "" 77 | print(f"Asset found: {asset_id}") 78 | 79 | # __get_accounts_by_asset: 80 | # Request a list of accounts for a single asset 81 | url = f"{data_node_url_rest}/accounts?filter.assetId={asset_id}" 82 | response = requests.get(url) 83 | helpers.check_response(response) 84 | print("Accounts filtered by asset:\n{}".format( 85 | json.dumps(response.json(), indent=2, sort_keys=True) 86 | )) 87 | # :get_accounts_by_asset__ 88 | 89 | ############################################################################### 90 | # A C C O U N T S B Y M A R K E T ( 2 ) # 91 | ############################################################################### 92 | 93 | # __get_accounts_by_market_filtered: 94 | # Request a list of accounts for a market and asset with a specific account type (general) 95 | url = f"{data_node_url_rest}/accounts?" \ 96 | f"filter.marketIds={market_id}" \ 97 | f"&filter.assetId={asset_id}" \ 98 | f"&filter.accountTypes=ACCOUNT_TYPE_GENERAL" 99 | response = requests.get(url) 100 | helpers.check_response(response) 101 | print("Accounts filtered by market and account type:\n{}".format( 102 | json.dumps(response.json(), indent=2, sort_keys=True) 103 | )) 104 | # :get_accounts_by_market_filtered__ 105 | 106 | ############################################################################### 107 | # A C C O U N T S B Y P A R T Y ( 2 ) # 108 | ############################################################################### 109 | 110 | # __get_accounts_by_party_filtered: 111 | # Request a list of accounts for a party with a specific account types (general & margin) 112 | url = f"{data_node_url_rest}/accounts?" \ 113 | f"filter.partyIds={pubkey}" \ 114 | f"&filter.accountTypes=ACCOUNT_TYPE_GENERAL" \ 115 | f"&filter.accountTypes=ACCOUNT_TYPE_MARGIN" 116 | response = requests.get(url) 117 | helpers.check_response(response) 118 | print("Accounts filtered by party and account type:\n{}".format( 119 | json.dumps(response.json(), indent=2, sort_keys=True) 120 | )) 121 | # :get_accounts_by_party_filtered__ 122 | --------------------------------------------------------------------------------