Giter Site home page Giter Site logo

Comments (3)

joris22o avatar joris22o commented on June 3, 2024

Please find a minimal sample implementation underneath. I've tried to elaborate on the code as much as possible. Note that you have to send your request to TWS (LYNX Trading) via the Eclient object. Afterwards the Ewrapper handles the information and from there you can print your output.

from ibapi import wrapper
from ibapi.wrapper import EWrapper
from ibapi.client import EClient

# We require common and contract to handle the incoming data
from ibapi.common import *
from ibapi.contract import *

# We require threading to handle the data streams
from threading import Thread

# Client => this is where our requests are. Ie fetchAccountUpdates function
class Client(EClient):
    def __init__(self, wrapper):
        EClient.__init__(self, wrapper)

    def fetchAccountUpdates(self):
        # Call this function to start getting account values, portfolio, and last update time information via EWrapper.updateAccountValue(), EWrapperi.updatePortfolio() and Wrapper.updateAccountTime().
        # When you have a single account structure with LYNX there's no need to fill in an account number
        self.reqAccountUpdates(True, '')


# Wrapper => this is where we place the functions for returning the data
# see: https://api.lynx.academy/Account&PortfolioData?id=receiving
class Wrapper(EWrapper):
    def __init__(self):
        wrapper.EWrapper.__init__(self)

    """ These functions below are called only when ReqAccountUpdates on
        EEClientSocket object has been called. """

    def updateAccountValue(self, key: str, val: str, currency:
                        str,accountName: str):

        super().updateAccountValue(key, val, currency, accountName)
        print("UpdateAccountValue. Key:", key, "Value:", val,
            "Currency:", currency, "AccountName:", accountName)

    def updatePortfolio(self, contract: Contract, position: float,
                    marketPrice: float, marketValue:
                    float,averageCost: float, unrealizedPNL:
                    float,realizedPNL: float, accountName: str):
        super().updatePortfolio(contract, position, marketPrice,
                                marketValue,averageCost, unrealizedPNL,
                                realizedPNL, accountName)

        print("UpdatePortfolio.", "Symbol:", contract.symbol, "SecType:",
            contract.secType, "Exchange:",contract.exchange,
            "Position:", position, "MarketPrice:",
            marketPrice,"MarketValue:", marketValue, "AverageCost:",
            averageCost,"UnrealizedPNL:", unrealizedPNL, "RealizedPNL:",
            realizedPNL,"AccountName:", accountName)

    def updateAccountTime(self, timeStamp: str):
        super().updateAccountTime(timeStamp)
        print("UpdateAccountTime. Time:", timeStamp)

    def accountDownloadEnd(self, accountName: str):
        """This is called after a batch updateAccountValue() and
        updatePortfolio() is sent."""

        super().accountDownloadEnd(accountName)
        print("AccountDownloadEnd. Account:", accountName)


# App
class App(Wrapper, Client):
    def __init__(self, ipaddress, portid, clientid):
        Wrapper.__init__(self)
        Client.__init__(self, wrapper=self)

        self.connect(ipaddress, portid, clientid)

        thread = Thread(target = self.run)
        thread.start()

        setattr(self, "_thread", thread)


def main():
    # Now we can create a new instance of App and start running queries
    app = App('localhost', 7496, 0)
    app.fetchAccountUpdates()


if __name__ == "__main__":
    main()

Let me know if you have any further questions.

from api-examples.

gosuto-inzasheru avatar gosuto-inzasheru commented on June 3, 2024

Thank you for your help. By defining some globals and appending to these I was able to get a dataframe variable out of it with all my account data.

I do have to say that this is not really an API in this sense that I know them though. It feels like this is more just opening up part of your back-end code, and still missing an API layer which is aimed at end users. Needing 87 lines is quite an elaborate way to access say my cash balance. It feels odd to have to (re)define all these classes and functions myself. Or handling threads? Is there truly no quicker way of getting my account values or portfolio in a variable?

from api-examples.

gosuto-inzasheru avatar gosuto-inzasheru commented on June 3, 2024

For anyone else bumping into this, here's a slightly simpler approach resulting in a clean dictionary as output:

from ibapi.wrapper import EWrapper
from ibapi.client import EClient
from threading import Thread

class Wrapper(EWrapper):
    def __init__(self):
        EWrapper.__init__(self)
    account_values = {}
    def updateAccountValue(self, key: str, val: str, currency: str, accountName: str):
        if currency != '':
            try:
                self.account_values[key][currency] = val
            except KeyError:
                self.account_values[key] = {currency: val}
        else:
            self.account_values[key] = val

client = EClient(Wrapper())
client.connect('localhost', 7496, 0)
client._thread = Thread(target=client.run).start()
client.reqAccountUpdates(True, '')

account = Wrapper.account_values

Now I can access all my information simply by calling the (nested) keys:

account['CashBalance']['USD']

A similar thing could be done for the portfolio or any other part of the API.

Defining this updateAccoutValue myself still feels weird though. I mean don't get my wrong I'm sure the API as it is now would be great for building live market tickers or trade bots but I think 9/10 users would already be happy with easy access to their account balance and portfolio positions.

from api-examples.

Related Issues (1)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.