0

I'm trying to read the TradesHistory from krakenn but it doesn't work with the index. It only works if I enter the right trade. How can I step through each individual trade individually?

With the following command I get all the trades. It works.

print(resp.json()['result']['trades'])

If I wanted to access the first index now, it doesn't work.

print(resp.json()['result']['trades'][0]['ordertxid'])

Only after entering the correct trade id can I access the following index.

print(resp.json()['result']['trades']['12345-abcde-ZYXWE']['ordertxid'])

What am I doing wrong? How can I access the correct index without first knowing the ID?

{
   "error":[
      
   ],
   "result":{
      "count":2,
      "trades":{
         "12345-abcde-ZYXWE":{},
         "ZYXWE-12345-abcde":{
            "ordertxid":"xyz",
         }
      }
   }
}

various Python index commands with different JSON formats

Bas H
  • 2,114
  • 10
  • 14
  • 23
Crusha
  • 3
  • 1
  • It looks like you are dealing with `JSON`, `JSON` is a dictionary that works like `key: value`. In order to access any value you have to know the key, **YOU DO NOT HAVE INDEXES IN DICTIONARIES** – David Mar 12 '23 at 09:46
  • And why does this work for /public/Ticker which is also a JSON format?: /public/Ticker?pair=XBTUSD ``` resp.json()['result']['XXBTZUSD'][a][4] ``` – Crusha Mar 12 '23 at 09:55
  • maybe what it is in the `a` location is a list, tuple, string, or something that supports the use of indexes. – David Mar 12 '23 at 10:00

2 Answers2

0

In order to go over all the trades, you can loop over the trades that were made and extract their information.

You can use a for loop like this:

trades = resp.json()['result']['trades']
for trade in trades: # accessing each trades
    if trades[trade] == {}:
        print('trade {} is empty.'.format(trade))
        continue
    print('{}\'s trade information:'.format(trade))
    for value in trades[trade]: # accessing each value inside the trade dictionary
        print(value, ':', trades[trade][value])
David
  • 85
  • 8
  • Ok this will definitely help me. I wouldn't have thought of doing it with a loop first. Thanks very much! – Crusha Mar 12 '23 at 10:12
0

I tried with this code below it is working.

import json
f = open('test.json')
test  = json.load(f)
test['result']['trades']['ZYXWE-12345-abcde']['ordertxid']

Output
'xyz'

And looking at your code it looks like you are referring to wrong index here ['12345-abcde-ZYXWE']

Abdul
  • 176
  • 3
  • 19