Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error on LIVE, not on DEMO: KeyError: 'cst' #41

Closed
alienoia opened this issue Feb 23, 2017 · 10 comments
Closed

Error on LIVE, not on DEMO: KeyError: 'cst' #41

alienoia opened this issue Feb 23, 2017 · 10 comments

Comments

@alienoia
Copy link

alienoia commented Feb 23, 2017

Dear @femtotrader,
DEMO version is ok. When I change from DEMO to LIVE (username, password etc... are changed), I get the folloging error: KeyError: 'cst' (see below).

Any help?
Thank you in advance,
Gilberto

This is the error output:

KeyError                                  Traceback (most recent call last)
<ipython-input-10-de3f99b49acd> in <module>()
     74 
     75 if __name__ == '__main__':
---> 76     main()

<ipython-input-10-de3f99b49acd> in main()
     34 
     35     ig_stream_service = IGStreamService(ig_service)
---> 36     ig_session = ig_stream_service.create_session()
     37     accountId = ig_session[u'accounts'][0][u'accountId']
     38     ig_stream_service.connect(accountId)

/Users/gb/anaconda/lib/python3.5/site-packages/trading_ig/stream.py in create_session(self)
     19 
     20     def create_session(self):
---> 21         ig_session = self.ig_service.create_session()
     22         self.ig_session = ig_session
     23         return ig_session

/Users/gb/anaconda/lib/python3.5/site-packages/trading_ig/rest.py in create_session(self, session)
    942         action = 'create'
    943         # this is the first create (BASIC_HEADERS)
--> 944         response = self._req(action, endpoint, params, session)
    945         data = self.parse_response(response.text)
    946         self.ig_session = data # store IG session

/Users/gb/anaconda/lib/python3.5/site-packages/trading_ig/rest.py in _req(self, action, endpoint, params, session)
    202         """Creates a CRUD request and returns response"""
    203         session = self._get_session(session)
--> 204         response = self.crud_session.req(action, endpoint, params, session)
    205         return response
    206 

/Users/gb/anaconda/lib/python3.5/site-packages/trading_ig/rest.py in req(self, action, endpoint, params, session)
    119             'delete': self.delete
    120         }
--> 121         return d_actions[action](endpoint, params, session)
    122 
    123     def _set_headers(self, response_headers, update_cst):

/Users/gb/anaconda/lib/python3.5/site-packages/trading_ig/rest.py in _create_first(self, endpoint, params, session)
     70                                 data=json.dumps(params),
     71                                 headers=self.HEADERS['BASIC'])
---> 72         self._set_headers(response.headers, True)
     73         self.create = self._create_logged_in
     74         return response

/Users/gb/anaconda/lib/python3.5/site-packages/trading_ig/rest.py in _set_headers(self, response_headers, update_cst)
    124         """Sets headers"""
    125         if update_cst:
--> 126             self.CLIENT_TOKEN = response_headers['CST']
    127 
    128         if 'X-SECURITY-TOKEN' in response_headers:

/Users/gb/anaconda/lib/python3.5/site-packages/requests/structures.py in __getitem__(self, key)
     52 
     53     def __getitem__(self, key):
---> 54         return self._store[key.lower()][1]
     55 
     56     def __delitem__(self, key):

KeyError: 'cst'

This is the main code (modules and credentials account imports are omitted):

#!/usr/bin/env python
#-*- coding:utf-8 -*-

"""
IG Markets Stream API sample with Python
2015 FemtoTrader
"""

import time
import sys
import traceback
import logging

from trading_ig import (IGService, IGStreamService)
#from trading_ig.config import config
from trading_ig.lightstreamer import Subscription


# A simple function acting as a Subscription listener
def on_prices_update(item_update):
    # print("price: %s " % item_update)
    print("{stock_name:<19}: Time {UPDATE_TIME:<8} - "
          "Bid {BID:>5} - Ask {OFFER:>5}".format(stock_name=item_update["name"], **item_update["values"]))

def on_account_update(balance_update):
    print("balance: %s " % balance_update)

def main():
    logging.basicConfig(level=logging.INFO)
    # logging.basicConfig(level=logging.DEBUG)

    #ig_service = IGService(config.username, config.password, config.api_key, config.acc_type)
    ig_service = IGService(username, password, api_key, acc_type)

    ig_stream_service = IGStreamService(ig_service)
    ig_session = ig_stream_service.create_session()
    accountId = ig_session[u'accounts'][0][u'accountId']
    ig_stream_service.connect(accountId)

    # Making a new Subscription in MERGE mode
    subcription_prices = Subscription(
        mode="MERGE",
        items=['L1:CS.D.GBPUSD.CFD.IP', 'L1:CS.D.USDJPY.CFD.IP'],
        fields=["UPDATE_TIME", "BID", "OFFER", "CHANGE", "MARKET_STATE"],
        )
        #adapter="QUOTE_ADAPTER")


    # Adding the "on_price_update" function to Subscription
    subcription_prices.addlistener(on_prices_update)

    # Registering the Subscription
    sub_key_prices = ig_stream_service.ls_client.subscribe(subcription_prices)


    # Making an other Subscription in MERGE mode
    subscription_account = Subscription(
        mode="MERGE",
        items='ACCOUNT:'+accountId,
        fields=["AVAILABLE_CASH"],
        )
    #    #adapter="QUOTE_ADAPTER")

    # Adding the "on_balance_update" function to Subscription
    subscription_account.addlistener(on_account_update)

    # Registering the Subscription
    sub_key_account = ig_stream_service.ls_client.subscribe(subscription_account)

    input("{0:-^80}\n".format("HIT CR TO UNSUBSCRIBE AND DISCONNECT FROM \
    LIGHTSTREAMER"))

    # Disconnecting
    ig_stream_service.disconnect()

if __name__ == '__main__':
    main()
@femtotrader
Copy link
Member

it looks like an issue between lower case / upper case.

@alienoia
Copy link
Author

alienoia commented Feb 23, 2017

If I set the DEMO account credentials, all is ok. If I change to LIVE account credentials I get the error.

@femtotrader
Copy link
Member

I didn't test with LIVE... so you should fix it and submit a PR.

I think you should simply change
https://github.com/ig-python/ig-markets-api-python-library/blob/master/trading_ig/rest.py#L129
from:

        self.CLIENT_TOKEN = response_headers['CST']

to

        self.CLIENT_TOKEN = response_headers['cst']

Please test it and say me if it fix this issue.

@alienoia
Copy link
Author

alienoia commented Feb 23, 2017

I changed the code but It doesn't fix the issue.

/Users/gb/anaconda/lib/python3.5/site-packages/trading_ig/rest.py in _set_headers(self, response_headers, update_cst)
    125         if update_cst:
    126             #self.CLIENT_TOKEN = response_headers['CST']
--> 127             self.CLIENT_TOKEN = response_headers['cst']
    128 
    129         if 'X-SECURITY-TOKEN' in response_headers:

/Users/gb/anaconda/lib/python3.5/site-packages/requests/structures.py in __getitem__(self, key)
     52 
     53     def __getitem__(self, key):
---> 54         return self._store[key.lower()][1]
     55 
     56     def __delitem__(self, key):

KeyError: 'cst'

@alienoia
Copy link
Author

alienoia commented Feb 23, 2017

I tried line by line:

ig_session = ig_stream_service.create_session() # This generates the error

...

from trading_ig import IGService, IGStreamService
from trading_ig.lightstreamer import Subscription
import trading_ig.compat as compat

ig_service = IGService(username, password, api_key, acc_type)
ig_stream_service = IGStreamService(ig_service)
ig_session = ig_stream_service.create_session() # This generates the error

@femtotrader
Copy link
Member

femtotrader commented Feb 23, 2017

I can only "blindly" help as I don't use anymore IG live (for now).
But maybe you should print response_headers

    if update_cst:
        print(response_headers)
        self.CLIENT_TOKEN = response_headers['CST']

to see what is going on

@alienoia
Copy link
Author

alienoia commented Feb 23, 2017

In LIVE, I get:

{'Connection': 'close', 'Vary': 'X-IG-API-KEY,Accept-Encoding', 'Content-Encoding': 'gzip', 'Access-Control-Allow-Headers': 'Content-Type, X-IG-API-KEY, CST, X-SECURITY-TOKEN, VERSION, _method, Authorization, IG-ACCOUNT-ID', 'Date': 'Thu, 23 Feb 2017 11:09:52 GMT', 'Access-Control-Expose-Headers': 'CST, X-SECURITY-TOKEN', 'Access-Control-Allow-Methods': 'POST, GET, PUT, DELETE, OPTIONS, GET, POST, PUT, DELETE', 'Server': 'Apache', 'Access-Control-Max-Age': '3600', 'Access-Control-Allow-Origin': '*', 'Content-Length': '62', 'Content-Type': 'application/json', 'X-STATE': 'live', 'P3P': 'CP="ALL DSP LAW OTPa OUR IND UNI CNT"', 'Cache-Control': 'no-cache, no-store'}

If I change from LIVE to DEMO, I get (some data omitted "..." ):

{'X-REQUEST-ID': '8...7', 'Server': 'Apache', 'Content-Length': '330', 'P3P': 'CP="ALL DSP LAW OTPa OUR IND UNI CNT"', 'Connection': 'keep-alive', 'Date': 'Thu, 23 Feb 2017 11:13:53 GMT', 'X-STATE': 'live', 'Cache-Control': 'no-cache, no-store', 'Access-Control-Expose-Headers': 'CST, X-SECURITY-TOKEN', 'Access-Control-Max-Age': '3600', 'Pragma': 'no-cache', 'CST': '8...1', 'Access-Control-Allow-Headers': 'Content-Type, X-IG-API-KEY, CST, X-SECURITY-TOKEN, VERSION, _method, Authorization, IG-ACCOUNT-ID', 'Access-Control-Allow-Origin': '*', 'X-SECURITY-TOKEN': '3...3', 'Access-Control-Allow-Methods': 'POST, GET, PUT, DELETE, OPTIONS, GET, POST, PUT, DELETE', 'Content-Type': 'application/json', 'Content-Encoding': 'gzip', 'Expires': '0', 'Vary': 'X-IG-API-KEY,Accept-Encoding'}

@alienoia
Copy link
Author

alienoia commented Feb 23, 2017

I found the error!
It was an API key problem, not your code.
I am very sorry for wasted your time.

@femtotrader
Copy link
Member

A better error message is probably required

@ahmedhindi
Copy link

@alienoia how did you solve the problem?

femtotrader pushed a commit that referenced this issue Sep 18, 2017
… (#60)

* When a session is created, raise exception if HTTP error response (#41)

* simplify if statement.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants