Developers
Search…
Example
Fetch user's on-chain portfolio
The following example connects to the Zerion Websocket API and fetches the portfolio of a given Ethereum address.
JavaScript
Python

1. Copy and paste the example below to quickstart.js

1
let io = require('socket.io-client');
2
3
const BASE_URL = 'wss://api-v4.zerion.io/';
4
5
function verify(request, response) {
6
const keys = ['address', 'currency'];
7
return keys.every(key => request.payload[key] === response.meta[key]);
8
}
9
10
const addressSocket = {
11
namespace: 'address',
12
socket: io(`${BASE_URL}address`, {
13
transports: ['websocket'],
14
timeout: 60000,
15
query: {
16
api_token: 'Demo.ukEVQp6L5vfgxcz4sBke7XvS873GMYHy',
17
},
18
}),
19
};
20
21
function get(socketNamespace, requestBody) {
22
return new Promise(resolve => {
23
const { socket, namespace } = socketNamespace;
24
function handleReceive(data) {
25
if (verify(requestBody, data)) {
26
unsubscribe();
27
resolve(data);
28
}
29
}
30
const model = requestBody.scope[0];
31
function unsubscribe() {
32
socket.off(`received ${namespace} ${model}`, handleReceive);
33
socket.emit('unsubscribe', requestBody);
34
}
35
socket.emit('get', requestBody);
36
socket.on(`received ${namespace} ${model}`, handleReceive);
37
});
38
}
39
40
get(addressSocket, {
41
scope: ['portfolio'],
42
payload: {
43
address: '0x7e5ce10826ee167de897d262fcc9976f609ecd2b',
44
currency: 'usd',
45
portfolio_fields: 'all',
46
},
47
}).then(response => {
48
console.log(response.payload.portfolio);
49
});
Copied!

2. Run it using node

1
node quickstart.js
Copied!

1. Copy and paste the example below to quickstart.py

1
import asyncio
2
import socketio
3
4
URI = 'wss://api-v4.zerion.io/'
5
API_TOKEN = 'Demo.ukEVQp6L5vfgxcz4sBke7XvS873GMYHy'
6
ORIGIN = 'http://localhost:3000'
7
8
sio = socketio.AsyncClient(logger=False, engineio_logger=False)
9
10
CONNECTED_TO_SOCKET = False
11
12
ADDRESS_PORTFOLIO = None
13
ADDRESS_ASSETS = None
14
ADDRESS_DEPOSITS = None
15
ADDRESS_LOANS = None
16
ADDRESS_STAKED_ASSETS = None
17
ADDRESS_LOCKED_ASSETS = None
18
19
20
@sio.event(namespace='/address')
21
async def connect():
22
global CONNECTED_TO_SOCKET
23
print('Connected to /address namespace!')
24
CONNECTED_TO_SOCKET = True
25
26
27
async def connect_to_socket():
28
await sio.connect(
29
f'{URI}/?api_token={API_TOKEN}',
30
headers={'Origin': ORIGIN},
31
namespaces=['/address'],
32
transports=['websocket']
33
)
34
35
36
@sio.on('received address portfolio', namespace='/address')
37
def received_address_portfolio(data):
38
global ADDRESS_PORTFOLIO
39
print('Address portfolio is received')
40
ADDRESS_PORTFOLIO = data['payload']['portfolio']
41
42
@sio.on('received address assets', namespace='/address')
43
def received_address_assets(data):
44
global ADDRESS_ASSETS
45
print('Address assets are received')
46
ADDRESS_ASSETS = data['payload']['assets']
47
48
@sio.on('received address deposits', namespace='/address')
49
def received_address_assets(data):
50
global ADDRESS_DEPOSITS
51
print('Address deposits are received')
52
ADDRESS_DEPOSITS = data['payload']['deposits']
53
54
@sio.on('received address loans', namespace='/address')
55
def received_address_assets(data):
56
global ADDRESS_LOANS
57
print('Address loans are received')
58
ADDRESS_LOANS = data['payload']['loans']
59
60
@sio.on('received address staked-assets', namespace='/address')
61
def received_address_assets(data):
62
global ADDRESS_STAKED_ASSETS
63
print('Address staked assets are received')
64
ADDRESS_STAKED_ASSETS = data['payload']['staked-assets']
65
66
@sio.on('received address locked-assets', namespace='/address')
67
def received_address_assets(data):
68
global ADDRESS_LOCKED_ASSETS
69
print('Address locked assets are received')
70
ADDRESS_LOCKED_ASSETS = data['payload']['locked-assets']
71
72
def results_ready() -> bool:
73
requested_entities = (
74
ADDRESS_PORTFOLIO, ADDRESS_ASSETS, ADDRESS_DEPOSITS,
75
ADDRESS_LOANS, ADDRESS_STAKED_ASSETS, ADDRESS_LOCKED_ASSETS
76
)
77
return not any(x is None for x in requested_entities)
78
79
async def main(address: str):
80
# Initiate the connection with the websocket
81
await connect_to_socket()
82
83
# Wait until the connection is established
84
while not CONNECTED_TO_SOCKET:
85
await asyncio.sleep(0)
86
87
# Request address information
88
await sio.emit('subscribe', {
89
'scope': ['portfolio', 'assets', 'deposits', 'loans', 'staked-assets', 'locked-assets'],
90
'payload': {
91
'address': address,
92
'currency': 'usd',
93
'portfolio_fields': 'all'
94
}
95
}, namespace='/address')
96
97
# Wait until all information about the address is received
98
while not results_ready():
99
await asyncio.sleep(0)
100
101
print('------')
102
print(
103
f'Address {address} has:',
104
f' - {len(ADDRESS_ASSETS)} assets worth of ${ADDRESS_PORTFOLIO["assets_value"]}',
105
f' - {len(ADDRESS_DEPOSITS)} deposits worth of ${ADDRESS_PORTFOLIO["deposited_value"]}',
106
f' - {len(ADDRESS_LOANS)} loans worth of ${ADDRESS_PORTFOLIO["borrowed_value"]}',
107
f' - {len(ADDRESS_STAKED_ASSETS)} staked assets worth of ${ADDRESS_PORTFOLIO["staked_value"]}',
108
f' - {len(ADDRESS_LOCKED_ASSETS)} locked assets worth of ${ADDRESS_PORTFOLIO["locked_value"]}',
109
sep='\n',
110
)
111
112
if __name__ == '__main__':
113
test_address = '0x7e5ce10826ee167de897d262fcc9976f609ecd2b'
114
loop = asyncio.get_event_loop()
115
loop.run_until_complete(main(test_address))
Copied!

2. Run it using python

1
python3 quickstart.py
Copied!
Copy link