Trouble with pickling the class object with Fyers API v3

Hi @Z4PBvkQGyF

While transforming my codes from v2 to v3, I faced an issue with pickling the class with the following error

PicklingError: logger cannot be pickled

I have noticed that in v3, the logger has been used, which was not earlier. Is there any way to bypass this issue?

PS. Pickling is required for me to avoid login sequences multiple times.

Hi @subhajit_bhar
You can use one time generate access token for the whole day.

That is true and probably the only way-out

To give you the problem overview, I have multiple files where I use fyersModel . In past I used to initiate fyersModel once and use it for other files. But with the given problem, I have to reinitiate the fyersModel for every file.

I got you but as I already provide you solution.
To generate the fyers model for every file is not a good way but however I will say do all the things which you want to do using api in one file and make and use another file for another functions which are not related to apis means your function.

@subhajit_bhar can you explain in more detail?

You can use refresh token+pin which doesn’t even need daily intervention for 15 days

There is fully automated totp as well on GitHub, and in both cases once auth code is generated once daily, you can use the same across all apps/scripts

@Z4PBvkQGyF, as you said correctly, generating the fyers model for every file is not a good way, I used to generate it once and then dump it to pickle file.

Unfortunately, v3 use logger and pickle is not compatible with logger.

@chirag, my login process is fully automated. No issue in that part. The problem is right after the login. I don’t want to generate the fyersModel for each and every file. To do so, I have to save the object to a pickle file. I am facing issue there only.

did you search on the net?

basically it is also an issue with python, some old versions had it working while others suggested using “Dlll” instead of pickle.

ofc this issue is bit complex bcos of logger(singleton) + python + pickle and Fyers devs with their choice of logger, so they can guide.

hard for me or you to resolve it without them.

I use dill only.

This is common problem with logger. You can’t serialize it (or may be I don’t know) and if I can’t serialize, I can’t dump it to pickle or Json file. End of story :unamused_face:.

I have to redesign my code base !

Adding with it, don’t even try to delete the logger attribute and then pickle as suggest in few places. The logger is coupled with service (as I checked thoroughly the source code).

Hi @subhajit_bhar
Please try to solve via internet and information which you want will be in Package.

One thing I can also suggest Please find how you can dump without logger.
Attaching one code it is not exact same but may be it will give you a idea.

import pickle

class YourObject:
    def __init__(self, data):
        self.data = data
        self.logger = your_logger_instance  # Replace this with your actual logger instance

    def remove_logger(self):
        # Remove the logger attribute
        del self.logger

# Create an instance of YourObject
obj = YourObject(data="some data")

# Remove the logger before pickling
obj.remove_logger()

# Now you can pickle the object
serialized_obj = pickle.dumps(obj)

# Do something with the serialized data, e.g., save to a file or send over the network

# To deserialize, you can unpickle and then add the logger back if needed
deserialized_obj = pickle.loads(serialized_obj)

# If necessary, reattach the logger
deserialized_obj.logger = your_logger_instance  # Replace this with your actual logger instance

Hi @Z4PBvkQGyF , Thanks. Please check my previous comment

Hi @subhajit_bhar
Sorry , You already tried it seems.
Now you should go with approach 1 where you will make different models.
or you can hit APIs directly with access token means overall you have to re-design your code.

Hi @Z4PBvkQGyF

Thanks you understood the pain finally! I would request the Fyers team, to provide logger as an option.

@subhajit_bhar As an alternative, you could save the day’s access token on a file like csv.

Pseudocode would be something like this

#This code will read and write access token from/to a csv with two columns (date and access_token)
def make_fyers_obj():
    df = pd.read_csv(credential/access_token.csv)
    df = df.loc[df['date'].dt.date == dt.today()]
    if len(df) == 0:
        access_token = generate_access_token()
    else:
         access_token = df['access_token'].iat[-1]

    fyers = fyersModel.FyersModel(client_id=client_id, token=access_token,log_path=log_path)
    return fyers

def generate_access_token():
    #code to generate here
    #add your generated access token to the credentials/access_token.csv
    return access_token

I’ve used pandas library here but you can use other library (or just plain old with open) as well

I’ve worked only on fyers v2 but I’m sure it will work on v3 as well

Hi @subhajit_bhar

We are using singleton class , do search around it if you can do anything. Otherwise go with creating different models in files.
Or you can directly hit api with proper parameters (Curl Request).

In second case you don’t have to create Models.

Hi @Z4PBvkQGyF ,

There is only two options currently I can see.

  • Use the FyersModel and initiate it whenever required as I can not save it.
  • Create own FyersModel ( as you said by hitting the API with correct parameter) without logger.

Although option 2 can be saved in file and can be reuse later on. But original FyersModel has better error control and also properly tested. Mainly because of that, I stick with original FyersModel.

To do so, I have already made the required changes. Now my class is callable which was not before.

Here is what I am doing now;

  def __call__(self):
        return fyersModel.FyersModel(
                    client_id=self.client_id,
                    token=self.access_token,
                    log_path=f'{self.log_path}/log'
                )

File 1

import dill
from src import FyersLogin 

# # Set paths accordingly
root = 

# Create an instance of FyersLogin
broker = FyersLogin()
dill.dump(broker, file = open(f"{root}/fyers.pickle", "wb"), byref=False, recurse=True)

File N

import dill

root = 
broker = dill.load(open(f"{root}/fyers.pickle", "rb"))

print(broker().funds())

Hi @subhajit_bhar
Nice !!