-1

Here is a sample of how I check for open positions. If no positions exist it creates a txt file and if open positions exist it del the .txt file. My problem is I don't know how to disconnect it . It is also outputting Error -1 see below script

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.common import *
from ibapi.contract import *
from ib.opt import ibConnection
import os.path
from os import path


class CheckPos(EClient, EWrapper):
            def __init__(self):
                EClient.__init__(self, self)
            def nextValidId(self, orderId:int):
                self.reqPositions()
            def position(self, account: str, contract: Contract, position: float,
                avgCost: float):
                super().position(account, contract, position, avgCost)

                if position >0:
                    try:
                        os.remove("noposition.txt")

                    except:
                       print("Open Positons")



                else:
                    try:
                        open("noposition.txt","w+")
                        print("File Created Sucessfully")

                    except:
                        print("No Open Positions")







def main():
    app = CheckPos()
    app.connect("127.0.0.1", 7497,421 )
    app.run()


if __name__ == "__main__":
    main()    

output is ERROR -1 2104 Market data farm connection is OK:usfuture ERROR -1 2104 Market data farm connection is OK:usfarm ERROR -1 2106 HMDS data farm connection is OK:ushmds File Created Sucessfully

  • Buddy, first of all, commas. They help express better. Secondly, do you have any reproducible code, inputs, expected outputs etc? – LazyCoder Jul 26 '19 at 21:19
  • Ok, what we mean by reproducible code is that can we have a look at your code to debug what went wrong? – LazyCoder Jul 26 '19 at 23:13
  • Do you really want to use IbPy instead of the newer api from IB https://www.interactivebrokers.ca/en/index.php?f=5041 ? – brian Jul 27 '19 at 13:58
  • I am willing to use the newer API and have installed it but having trouble with understanding Ewapper and Eclient. – Nikolaos Trader Jul 27 '19 at 16:36
  • https://stackoverflow.com/a/56917618/2855515 is my latest answer using the ib api, but with contractDetails instead of positions. Here you can see it's almost identical to positions. http://interactivebrokers.github.io/tws-api/positions.html#position_request . Try making some code using my code as a template and replacing the contract methods with position methods. Edit your question and post your code if it doesn't work. If it does work you can post it as an answer. – brian Jul 27 '19 at 17:00

1 Answers1

2

You removed your positionEnd() method. That is when you should disconnect.

This line from ib.opt import ibConnection is from IbPy, remove it.

I'm not sure what you're trying to do with files but you may get many positions returned in the callback. It's better to add them to a list and do something with them when the program has finished getting all the positions. I wrote something in the positionEnd() method that disconnects and then saves the data.

Lines like ERROR -1 2104 Market data farm connection is OK:usfuture are just information. You can ignore them unless they say it's broken, but that's another error code.

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.common import *
from ibapi.contract import *

import os

class TestApp(EClient, EWrapper):
    posns = []
    fname = 'fname.txt'

    def __init__(self):
        EClient.__init__(self, self)

    def nextValidId(self, orderId:int):
        print("id", orderId)
        print("starting program")
        self.reqPositions()

    def error(self, reqId:TickerId, errorCode:int, errorString:str):
        print("Error: ", reqId, "", errorCode, "", errorString)

    def position(self, account: str, contract: Contract, position: float, avgCost: float):
        self.posns.append((account, contract.symbol, position, avgCost))
        print(contract.symbol, position)

    def positionEnd(self):
        print("end, disconnecting")
        self.disconnect()

        #write posns to file or delete file if no positions
        if self.posns: #means not empty
            with open(self.fname, "w") as outfile:
                outfile.write('\n'.join(str(posn) for posn in self.posns))
        else: # no posns so delete file
            os.remove(self.fname)

def main():
    app = TestApp()
    app.connect("127.0.0.1", 7497, 421)
    app.run()

if __name__ == "__main__":
    main()
brian
  • 10,619
  • 4
  • 21
  • 79
  • Thank you so much for your time. The reason for using files is I am not very good at this but I am trying very hard to at least have it functioning. I have a python file that gets alerts from tradingview (much better at coding indicators for alerts in pine) , then places trades, and sends me a text message. I wanted to just def a function to store the var for open positions at the top of my non looping script so that could use it in my logic if then else statements later in the code. – Nikolaos Trader Jul 29 '19 at 17:22
  • This works. Its easy and I can see my portfolio. Thanks for your hard work! – JoyLahi Feb 08 '20 at 02:09