ribrokersinteractive-brokers

How can I close an opened order on Interactive brokers after 5 seconds


I use a code (link is below) to open an order in Interactive Brokers ( I use a paper account) but when I tried to close the opened order after 5 seconds I was not able to do so.What am I doing wrong?

library(IBrokers)
myconid = 3
twsobj  = twsConnect(myconid)
myaud = twsCurrency("AUD",currency="USD",exch="IDEALPRO",primary="",strike="0.0",right="",local="",multiplier="",include_expired="0",conId=myconid)
Sys.sleep(2)
myorderid = as.integer(reqIds(twsobj))
print(myorderid)
Sys.sleep(2)
# my workaround:
options("scipen"=4)
placeOrder(twsobj, myaud, twsOrder(myorderid,"SELL", 1, "MKT"))
Sys.sleep(5)
placeOrder(twsobj, myaud, twsOrder(myorderid,"BUY", 1, "MKT"))

Link that I used:[IBrokers - How I send 100000 to IBrokers:::.placeOrder?

UPDATE( Following brian's answer ): I use a code (link is below) to open an order in Interactive Brokers ( I use a paper account) but when I tried to close the opened order after 5 seconds I was not able to do so.What am I doing wrong?

 library(IBrokers)
    myconid = 3
    twsobj  = twsConnect(myconid)
    myaud = twsCurrency("AUD",currency="USD",exch="IDEALPRO",primary="",strike="0.0",right="",local="",multiplier="",include_expired="0",conId=myconid)
    Sys.sleep(2)
    print(myorderid)
    Sys.sleep(2)
    # my workaround:
    options("scipen"=4)
    placeOrder(twsobj, myaud, twsOrder(122,"SELL", 1, "MKT"))
    Sys.sleep(5)
    placeOrder(twsobj, myaud, twsOrder(123,"BUY", 1, "MKT"))

Solution

  • You need to use a different order id. They are not re-useable. You should increment by at least 1 for ever, even the next day, month etc.. When you connect, TWS returns the next valid ID. I don't know where it is in R or what reqIds returns (in java it gets a range of ids), but you need to use a unique number. Some people just use seconds from the epoch or you can look for a nextValidId() method.

    Also, look for error messages, if you get "duplicate order id", you should realize your mistake.