Search code examples
pythonoauthetrade-api

generating oauth_signature for ETrade API using Python


The E*Trade API allows you to use RESTful to log on to the site and manipulate an account or retrieve quote information. Though I am having trouble generating an oauth_signature that matches their "practice problem" located toward the bottom of https://us.etrade.com/ctnt/dev-portal/getContent?contentId=306a9d46-58c2-4cac-85f6-7717aea056bd

The simple HMAC-SMA1 algorithm has been coded below and reproduces the oauth core 1.0a signature value from here https://oauth.net/core/1.0a/#sig_base_example. Though I cannot get E*Trade signature value to reproduce.

def generate_oauth_signature():
    from urllib.parse import quote_plus
    from hashlib import sha1
    import binascii
    import hmac

    key = quote_plus('7d30246211192cda43ede3abd9b393b9') + \
          '&' + \
          quote_plus('XCF9RzyQr4UEPloA+WlC06BnTfYC1P0Fwr3GUw/B0Es=')
    key = key.encode()
    raw = quote_plus('GET') + '&' + \
          quote_plus('https://etws.etrade.com/accounts/rest/accountlist') + '&' + \
          quote_plus('oauth_consumer_key=c5bb4dcb7bd6826c7c4340df3f791188&oauth_nonce=0bba225a40d1bbac2430aa0c6163ce44&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1344885636&oauth_token=VbiNYl63EejjlKdQM6FeENzcnrLACrZ2JYD6NQROfVI=')
    raw = raw.encode()
    hashed = hmac.new(key, raw, sha1)
    sig = hashed.digest()
    oauth_signature = quote_plus(binascii.b2a_base64(hashed.digest())[:-1])

The function is supposed to yield "%2FXiv96DzZabnUG2bzPZIH2RARHM%3D", but I'm not there yet. Has anyone worked out the hashing for the E*Trade API?

I am aware of the etradepy.py, which is a nice package, but is a little outdated and does not match the current E*Trade website.


Solution

  • One problem is that the oauth_token needs to be encoded in the parameter string (it will end up being double encoded). Mine is the following:

    oauth_consumer_key=c5bb4dcb7bd6826c7c4340df3f791188&oauth_nonce=0bba225a40d1bbac2430aa0c6163ce44&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1344885636&oauth_token=VbiNYl63EejjlKdQM6FeENzcnrLACrZ2JYD6NQROfVI%3D