GithubHelp home page GithubHelp logo

Comments (3)

Komnomnomnom avatar Komnomnomnom commented on June 9, 2024

thanks for the detailed report. I can reproduce using the code you provided and will investigate.

from swigibpy.

Komnomnomnom avatar Komnomnomnom commented on June 9, 2024

Looks like a problem accessing the contract object from separate threads.

The updatePortfolio method is called in the callback thread and it appends to the global currentPositions list. You then try to read from that in the main thread and kaboom. There is no problem accessing contract.symbol from within the callback thread in updatePortfolio.

from swigibpy.

troyshu avatar troyshu commented on June 9, 2024

Awesome, you're absolutely right! Thank you again for your help.

Below is the code that successfully grabs each position symbol and quantity, in case any one is interested

import datetime as dt

import sys
from time import sleep

from swigibpy import EWrapper, EPosixClientSocket, Contract, Order, TagValue,\
        TagValueList

try:
    input = raw_input
except:
    pass

###

orderId = None

availableFunds = 0
netLiquidationValue = 0

currentPositions = {}

class PlaceOrderExample(EWrapper):
    '''Callback object passed to TWS, these functions will be called directly
    by TWS.

    '''

    def openOrderEnd(self):
        '''Not relevant for our example'''
        pass

    def execDetails(self, id, contract, execution):
        '''Not relevant for our example'''
        pass

    def managedAccounts(self, openOrderEnd):
        '''Not relevant for our example'''
        pass

    ###############

    def nextValidId(self, validOrderId):
        '''Capture the next order id'''
        global orderId
        orderId = validOrderId

    def orderStatus(self, id, status, filled, remaining, avgFillPrice, permId,
            parentId, lastFilledPrice, clientId, whyHeld):

        print(("Order #%s - %s (filled %d, remaining %d, avgFillPrice %f,"
               "last fill price %f)") % (
                id, status, filled, remaining, avgFillPrice, lastFilledPrice))

    def openOrder(self, orderID, contract, order, orderState):

        print("Order opened for %s" % contract.symbol)

    ####account value
    def updateAccountValue(self, key, value, currency, accountName):
        global availableFunds
        global netLiquidationValue

        #get how much current available funds we have, also our net liquidation value
        if currency == 'USD':

            if key == 'AvailableFunds':
                availableFunds = float(value)
            elif key=='NetLiquidation':
                netLiquidationValue = float(value)

    def accountDownloadEnd(self,accountName):
        print 'account download ended for %s' % (accountName)
    def updateAccountTime(self,timestamp):
        print 'account information pulled at %s' % (timestamp)
    def updatePortfolio(self, contract, position, marketPrice, marketValue, averageCost, unrealizedPNL, realizedPNL, accoutName):
        #this only called when there are actually positions

        global currentPositions
        symbol = contract.symbol
        currentPositions[symbol] = position


# Instantiate our callback object
callback = PlaceOrderExample()

# Instantiate a socket object, allowing us to call TWS directly. Pass our
# callback object so TWS can respond.
tws = EPosixClientSocket(callback)

# Connect to tws running on localhost
tws.eConnect("", 7496, 42)

#account updates
tws.reqAccountUpdates(True,'DU15068')

sleep(3)
print 'available funds: %s' % (availableFunds)
print 'net liquidation value: %s' % (netLiquidationValue)

print 'positions:'
for symbol in currentPositions:
    print "%s: %s" % (symbol,currentPositions[symbol])



print("******************* Press ENTER to quit when done *******************\n")
input()

print("\nDisconnecting...")
tws.eDisconnect()

from swigibpy.

Related Issues (20)

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.