Home > Mobile >  how can I call a function and pass params in a Python class?
how can I call a function and pass params in a Python class?

Time:02-24

I am attempting to use the Woo exchange trading api. They provided a snippet of code which is an impressive Python class structure. Copied below.

My question is how can I use it?

I have tried to run:

get_orders(self, 'BTCUSDT')

which throws an error "NameError: name 'self' is not defined"

and

get_orders('BTCUSDT')

which throws "TypeError: get_orders() missing 1 required positional argument: 'symbol'"

Here is the code (class structure) the kind woo guys provided:

import requests
import datetime
import time
import hmac
import hashlib
from collections import OrderedDict
#Application ID 9d4d96f6-3d3b-4430-966d-8733aa3dc3bc

#API Key
api_key = 'my_api_key'
#API Secret
api_secret = 'my_api_secret'

class Client():
    def __init__(self, api_key=None, api_secret=None):
        self.api_key = api_key
        self.api_secret = api_secret
        self.base_api = "https://api.woo.network/v1/"

    def get_signature(self, params, timestamp):
        query_string = '&'.join(["{}={}".format(k, v) for k, v in params.items()])   f"|{timestamp}"
        signature = hmac.new(
            self.api_secret.encode('utf-8'),
            query_string.encode('utf-8'),
            hashlib.sha256
        ).hexdigest()
        return signature

    def get_orders(self, symbol):
        url = self.base_api   "orders/"
        params = {
            "symbol": 'BTCUSDT'
        }
        params = OrderedDict(sorted(params.items()))
        timestamp = str(int(time.time() * 1000))
        signature = self.get_signature(params, timestamp)
        headers = {
            'Content-Type': "application/x-www-form-urlencoded",
            'x-api-key': self.api_key,
            'x-api-signature': signature,
            'x-api-timestamp': timestamp,
            'cache-control': 'no-cache'
        }
        resp = requests.get(url=url, params=params, headers=headers).json()

So, to repeat and summarize, when I write my own code to use this class, how can I call the function get_orders() and, more generally, reference the elements in the class structure? Thanks, in advance, for help.

CodePudding user response:

Looks like you've truncated the code because get_orders doesn't appear to return anything.

However, you would start by constructing an instance of Client like this:

client = Client(api_key, api_secret)

...then...

client.get_orders(None)

That may look a little strange but get_orders requires one parameter but it's never used. I don't think the implementation of get_orders is quite how it was intended to be because it will always use BTCUSDT

  • Related