Skip to content
This repository has been archived by the owner on Oct 12, 2021. It is now read-only.

Add API examples #289

Draft
wants to merge 17 commits into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
__pycache__
.venv
venv
credentials.*
credentials
*.tmp
.idea
.DS_Store
token.temp
tools/
5 changes: 5 additions & 0 deletions .gitpod.Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
FROM gitpod/workspace-full:latest

# Install gq
ENV PATH="$PATH:$HOME/node_modules/.bin"
RUN npm install [email protected]
12 changes: 12 additions & 0 deletions .gitpod.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---

image:
file: .gitpod.Dockerfile

tasks:
- init: pipenv install -r requirements.txt --python 3.8
- command: |
pipenv shell
source examples-config

ports: []
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@ The per-language API clients are found in [`grpc/clients/`](https://github.com/v

Pull requests for additional languages are gratefully received.

# Examples
# Example API scripts

[![Gitpod ready-to-code](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/vegaprotocol/api/tree/198-api-examples/)

Some example/demonstration programs are maintained in this repository. They are
intended to be stand-alone programs that can be run by people copying and
Expand Down
13 changes: 13 additions & 0 deletions examples-config
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#!/usr/bin/env bash

# Default server configuration used by REST/GRPC/GRAPHQL examples

NODE_URL_REST="https://lb.testnet.vega.xyz"
NODE_URL_GRAPHQL="https://lb.testnet.vega.xyz/query"
NODE_URL_GRPC="n06.testnet.vega.xyz:3002"
WALLETSERVER_URL="https://wallet.testnet.vega.xyz"

export NODE_URL_GRPC
export NODE_URL_REST
export NODE_URL_GRAPHQL
export WALLETSERVER_URL
9 changes: 9 additions & 0 deletions examples-config.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Set env variable on a Window computer
$Env:WALLET_NAME="example_wallet_name"
$Env:WALLET_PASSPHRASE="example_wallet_passphrase"

# Do not edit below this line:
$Env:WALLETSERVER_URL="https://wallet.testnet.vega.xyz"
$Env:NODE_URL_REST="https://lb.testnet.vega.xyz"
$Env:NODE_URL_GRAPHQL="https://lb.testnet.vega.xyz/query"
$Env:NODE_URL_GRPC="n06.testnet.vega.xyz:3002"
8 changes: 6 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,15 @@ module github.com/vegaprotocol/api
go 1.16

require (
code.vegaprotocol.io/go-wallet v0.8.0
github.com/golang/protobuf v1.5.2
github.com/mwitkow/go-proto-validators v0.3.2
github.com/pkg/errors v0.9.1
github.com/satori/go.uuid v1.2.0
github.com/stretchr/testify v1.7.0
google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84
google.golang.org/grpc v1.38.0
golang.org/x/net v0.0.0-20210610132358-84b48f89b13b
golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b
google.golang.org/genproto v0.0.0-20210716133855-ce7ef5c701ea
google.golang.org/grpc v1.39.0
google.golang.org/protobuf v1.27.1
)
253 changes: 192 additions & 61 deletions go.sum

Large diffs are not rendered by default.

136 changes: 136 additions & 0 deletions graphql/examples/event-bus/stream-events.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
#!/usr/bin/env bash

# Script language: bash

# Talks to:
# - Vega node (GraphQL)
#
# Apps/Libraries:
# - GraphQL: graphqurl (https://github.com/hasura/graphqurl)

# Note: this file uses smart-tags in comments to section parts of the code to
# show them as snippets in our documentation. They are not necessary to be
# included when creating your own custom code.
#
# Example of smart-tags:
# __something:
# some code here
# :something__
#

source helpers.sh
check_url "NODE_URL_REST" || exit 1
check_url "NODE_URL_GRAPHQL" || exit 1

# __get_market:
# Request the identifier for a market
url="$NODE_URL_REST/markets"
response="$(curl -s "$url")"
marketID="$(echo "$response" | jq -r '.markets[0].id')"
echo $marketID
# :get_market__

# __stream_events:
# Subscribe to the events bus stream for the marketID specified,
# Required: type field - Switch the event type with '... on [TYPE]' syntax, NOTE: All event is not supported by GraphQL API.
# Required: batchSize field - Default: 0 - Total number of events to batch on server before sending to client.
# Optional: Market identifier - filter by market
# Party identifier - filter by party
# By default, all events on all markets for all parties will be returned on the stream.
# Event types and schema can be found here: https://docs.testnet.vega.xyz/docs/api-howtos/event-stream/
gq $NODE_URL_GRAPHQL -q 'subscription { busEvents(batchSize: 0, types: [Order], marketID: "'$marketID'" ) {
type
event
{
... on Order {
id
side
price
timeInForce
side
market { id }
size
remaining
party { id }
createdAt
expiresAt
status
reference
trades { id, size, aggressor }
type
rejectionReason
version
updatedAt
}
... on TimeUpdate {
timestamp
}
}
}}'
# :stream_events__

# Another example, with even deeper graphql nesting would be to select on Governance Proposals:
#
# gq $NODE_URL_GRAPHQL -q 'subscription { busEvents(batchSize: 0, types: [Proposal] ) {
# type
# event
# {
# ... on Proposal {
# id
# datetime
# yesVotes {
# value
# party { id }
# }
# noVotes {
# value
# party { id }
# }
# party {
# id
# }
# reference
# state
# terms {
# closingDatetime
# enactmentDatetime
# change {
# ... on NewMarket {
# instrument {
# code
# }
# decimalPlaces
# tradingMode {
# ... on ContinuousTrading {
# tickSize
# }
# ... on DiscreteTrading {
# tickSize
# duration
# }
# }
# riskParameters {
# ... on LogNormalRiskModel {
# tau
# riskAversionParameter
# params {
# r
# sigma
# mu
# }
# }
# }
# }
# ... on NewAsset {
# source {
# ... on BuiltinAsset {
# id
# }
# }
# }
# }
# }
# }
# }
# }
# }'
32 changes: 32 additions & 0 deletions graphql/examples/orders-and-trades/stream-orders.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#!/usr/bin/env bash

# Script language: bash

# Talks to:
# - Vega node (GraphQL)
#
# Apps/Libraries:
# - GraphQL: graphqurl (https://github.com/hasura/graphqurl)

# Note: this file uses smart-tags in comments to section parts of the code to
# show them as snippets in our documentation. They are not necessary to be
# included when creating your own custom code.
#
# Example of smart-tags:
# __something:
# some code here
# :something__
#

source helpers.sh
check_url "NODE_URL_GRAPHQL" || exit 1

# __stream_orders_by_ref:
# Stream orders by reference on a Vega network
# Note: This is an example and order reference will be provided in the response
# from a prepareSubmitOrder request in the field named `submitID` or similar.
reference="4617844f-6fab-4cf6-8852-e29dbd96e5f1"
pubkey="94c21a5bfc212c0b4ee6e3593e8481559972ad31f1fb453491f255e72bdb6fdb"
gq $NODE_URL_GRAPHQL -q 'subscription { orders(partyId: "'$pubkey'") { id, reference } }'
# In target language, filter the result stream and search for orders matching the reference
# :stream_orders_by_ref__
65 changes: 65 additions & 0 deletions grpc/examples/go/get-accounts.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package main

import (
"fmt"

"github.com/vegaprotocol/api/grpc/clients/go/generated/code.vegaprotocol.io/vega/proto/api"
"github.com/vegaprotocol/api/grpc/examples/go/helpers"

"golang.org/x/net/context"
"google.golang.org/grpc"
)

func main() {
// Helpers include logic to authenticate with a Vega wallet service
// including token storage/public key operations/signing of commands
// visit ./helpers/wallet.go for more detail
pubkey := helpers.GetPubKey()

nodeURLGrpc := helpers.GetFromEnv("NODE_URL_GRPC")
conn, err := grpc.Dial(nodeURLGrpc, grpc.WithInsecure())
if err != nil {
panic(err)
}
defer conn.Close()

dataClient := api.NewTradingDataServiceClient(conn)

// Get market
marketRequest := api.MarketsRequest{}
markets, err := dataClient.Markets(context.Background(), &marketRequest)
if err != nil {
panic(err)
}
marketID := markets.Markets[0].Id

// __get_accounts_by_market:
// Request a list of accounts for a market on a Vega network
accountsReq := api.MarketAccountsRequest{MarketId: marketID}
acconutsResp, err := dataClient.MarketAccounts(context.Background(), &accountsReq)
if err != nil {
panic(err)
}
fmt.Printf("Market accounts: %v\n", acconutsResp)
// :get_accounts_by_market__

// __get_accounts_by_party:
// Request a list of accounts for a party (pubkey) on a Vega network
partyReq := api.PartyAccountsRequest{PartyId: pubkey}
partyResp, err := dataClient.PartyAccounts(context.Background(), &partyReq)
if err != nil {
panic(err)
}
fmt.Printf("Party accounts: %v\n", partyResp)
// :get_accounts_by_party__

// __get_positions_by_party:
// Request a list of positions for a party (pubkey) on a Vega network
partyPosReq := api.PositionsByPartyRequest{PartyId: pubkey}
partyPosResp, err := dataClient.PositionsByParty(context.Background(), &partyPosReq)
if err != nil {
panic(err)
}
fmt.Printf("Party positions: %v\n", partyPosResp)
// :get_positions_by_party__
}
60 changes: 60 additions & 0 deletions grpc/examples/go/get-assets.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package main

import (
"context"
"fmt"

"github.com/vegaprotocol/api/grpc/clients/go/generated/code.vegaprotocol.io/vega/proto/api"
"github.com/vegaprotocol/api/grpc/examples/go/helpers"

"google.golang.org/grpc"
)

func main() {
nodeURLGrpc := helpers.GetFromEnv("NODE_URL_GRPC")
conn, err := grpc.Dial(nodeURLGrpc, grpc.WithInsecure())
if err != nil {
panic(err)
}
defer conn.Close()

dataClient := api.NewTradingDataServiceClient(conn)

// __get_assets:
// Request a list of assets available on a Vega network
request := api.AssetsRequest{}
assets, err := dataClient.Assets(context.Background(), &request)
if err != nil {
panic(err)
}
// :get_assets__

// Find asset with name DAI
assetFound := false
var assetId string
for _, asset := range assets.Assets {
fmt.Printf("Assets: %s \n", asset.Details.Name)
fmt.Printf("Assets: %s \n", asset.Details.Symbol)
if asset.Details.Symbol == "tDAI" {
fmt.Println("Found an asset with name tDAI:")
assetId = asset.Id
assetFound = true
break
}
}

if !assetFound {
panic("tDAI asset not found on specified Vega network, please propose and create the tDAI asset")
}

// __get_asset:
// Request a single asset by identifier on a Vega network
requestAsset := api.AssetByIDRequest{Id: assetId}
assetObject, err := dataClient.AssetByID(context.Background(), &requestAsset)
if err != nil {
panic(err)
}
// :get_asset__

fmt.Printf("Asset by id: %s", assetObject.Asset)
}
Loading