I am using a paper trading IB-account where trades are processed just fine. I have a number of unfilled orders. The "updateAccountValue" performs as expected, while "con.register(acct_update, message.reqAllOpenOrders())" does nothing, neither does "con.reqOpenOrders()'. Neither raises an error either. The IB documentation tells me that all three methods are 'void' which I understand to mean that no value is supposed to be returned. Yet, as stated, the "updateAccountValue" method works perfectly fine, supplying the proper output.
Question 1: how do I retrieve data regarding (unfilled) open orders?
I have also noticed that the code does not always run, but it always runs properly right after (re-)starting the TWS workstation application.
Question 2: why does this code not run every time it is launched?
from ib.opt import ibConnection, message
import sys
def acct_update(msg):
print msg
con = ibConnection(clientId=100)
con.register(acct_update,
message.updateAccountValue)
con.register(acct_update,
message.reqAllOpenOrders())
con.connect()
con.reqAccountUpdates(True,'DU000000')
con.reqAllOpenOrders()
con.reqOpenOrders()
sys.exit()
I was trying to figure out how to print out all open orders. Here is what I found that may help you with your first question.
Add a print function to the original IBpy documents of Order.py and Contract.py.
In the Order.py add:
def __str__(self):
return "Action: " + self.m_action + ", Quantity: " + str(self.m_totalQuantity) + ", at price: " + str(self.m_lmtPrice)
In the Contract.py add:
def __str__(self):
return "secType: " + self.m_secType + ", symbol: " + self.m_symbol + "; expiry: " + self.m_expiry
You can modify the fields to show what you would like to view.
In your own python file:
``
from ib.opt import Connection, message
from ib.ext.Contract import Contract
from ib.ext.Order import Order
def print_open_order_messege(msg):
print ("open_order: " + str(msg.orderId) + "::" + str(msg.contract) + "::" + str(msg.order) + "::"+str(msg.orderState))
def print_order_status_messege(msg):
print ("order_status: " + str(msg.orderId) + "::" + "Status: " + msg.status + ", Filled: " + str(msg.filled) + ", Remaining: " + str(msg.remaining) + ", avgFillPrice: " + str(msg.avgFillPrice))
con.register(print_open_order_messege, message.openOrder)
con.register(print_order_status_messege, message.orderStatus)
con.reqAllOpenOrders()
It prints out my test order as below:
...
open_order: 2::secType: FUT, symbol: NQ; expiry: 20161216::action: BUY, quantity: 1, at price: 4500.0::Status: PendingCancel
order_status: 2::Status: PendingCancel Filled: 0 Remaining: 1 avgFillPrice: 0.0
Notice the difference ?
con.register(acct_update,
message.updateAccountValue)
con.register(acct_update,
message.reqAllOpenOrders())
You should use message.openOrder
Also, you're sending it to the acct_update callback but since it just prints, it's no big deal. However if you want information from the callback, here is the format it arrives in.
<openOrder orderId=123469, contract=<ib.ext.Contract.Contract object at 0x7f68daeff6a0>, order=<ib.ext.Order.Order object at 0x7f68e80d2668>, orderState=<ib.ext.OrderState.OrderState object at 0x7f68daf39240>>
You also call exit() before the program probably has a chance to finish. It's asynchronous, that means you have to wait for a reply.
Related
Pretty straight forward. I just want to print in thinkscript. If this question indicates that I'm missing a crucial element of thinkscript by asking this, please let me know that as well.
Use something like this: AddLabel(yes, if close > 0 then "whatyouwanttoprint"
If you're asking how to actually print out the code for a script: the best I can find is to copy the code into another editor and print from there.
If you're looking for ways to output for debugging purposes, say, then #Mteam888's answer, AddLabel is one way. Another is AddChartBubble:
#hint: Demonstrates adding a chart bubble at a given bar number and a label showing the last (most recent) bar number.\nNote: bar[0] is the rightmost, or most recent, bar. It is actually n bars from the leftmost side of the chart;\nbar[1] is one bar left of bar[0], and bar[2] is 2 bars left of bar 0.\nThis example also shows no plot is required in this case.
def isLastBar = !IsNaN(close) and IsNaN(close[-1]);
def lastBarNum = if isLastBar then BarNumber() else 0;
AddChartBubble( "time condition"=(BarNumber() == 15), "price location"=high, text="BarNumber" + BarNumber(), color=Color.YELLOW);
AddChartBubble( "time condition"=(BarNumber() == 30), "price location"=high, text="BarNumber" + BarNumber(), color=Color.YELLOW);
AddChartBubble( "time condition"=(BarNumber() == 45), "price location"=high, text="BarNumber" + BarNumber(), color=Color.YELLOW);
AddLabel(visible=isLastBar, text="bar[0] (rightmost): " + lastBarNum, color=Color.GREEN);
AddLabel(visible=isLastBar, text="bar[1]: " + (lastBarNum - 1), color=Color.YELLOW);
AddLabel(visible=isLastBar, text="bar[2]: " + (lastBarNum - 2), color=Color.ORANGE);
#plot Data = close; #plot is not required if only adding labels/chart bubbles
I have the following code:
for i in range(len(str(hoursList))):
try:
g(hoursList[i])
except Exception as ex:
print(str(nameList[i]) + " " + "has more than 80 hours worked!")
When I run the code, I get an error saying "IndexError: list index out of range". I'm wondering if its because I have hoursList[i], but when I take out the [i], the loop runs too many times.
My nameList and hoursList has the following in it, respectively.
['Michael Johnson', 'Sue Jones', 'Tom Spencer', 'Mary Harris', 'Alice Tolbert', 'Joe Sweeney', 'Linda Smith', 'Ted Farmer', 'Ruth Thompson', 'Bob Bensen']
[8.75, 8.75, 8.75, 8.75, 8.75, 8.75, 11.0, 11.0, 5.25, 5.0]
What is happening when you are doing len(str(hoursList)) is you are turning the entire list into a string then going through and returning an i for each number, space, and , of the new string. For example:
len(str(["hello", "world"])) == 18
But if you do this:
len(["hello", "world"]) == 2
So when you are in the for i loop you end up going over how many entries are actually in the hoursList.
Change your loop to be:
for i in range(len(hoursList)):
try:
g(hoursList[i])
except Exception as ex:
print(str(nameList[i]) + " " + "has more than 80 hours worked!")
I have a dynamic action on a button that runs a small bit of javascript. Basically, it acts as a mailto link and adds some of the page items to the body of the email. it works for the most part but I have noticed that if the value of the page item contains an & the email cuts off at that point in the text. This is what I currently have:
var policy_num = $v('P9_POLICY');
var tclose = $v('P9_TDATE');
var taskt = $v('P9_TYPE');
var taskd = $v('P9_DESC');
var audito = $v('P9_TASK_AUDIT_OUTCOME');
var auditc = $v('P9_NOTE');
location.href= "mailto:" +
"?subject=" + "Please take immediate action" +
"&body="+
"%0APolicy: " + policy_num +
"%0ATask Closed: " + tclose +
"%0ATask Type: " + taskt +
"%0ATask Description: " + taskd +
"%0AAudit Outcome: " + audito +
"%0AAudit Comment: " + auditc ;
If there is a better way to accomplish this kind of mailto function that I would definitely be open to that. This is just the first way I found that actually worked. Thanks!
If your Items contain an &-Character it will act as a control-character. You need to escape it so it won't be interpreted as a control-character anymore.
It should look something like this:
var policy_num = escape($v('P9_POLICY'));
var tclose = escape($v('P9_TDATE'));
var taskt = escape($v('P9_TYPE'));
var taskd = escape($v('P9_DESC'));
var audito = escape($v('P9_TASK_AUDIT_OUTCOME'));
var auditc = escape($v('P9_NOTE'));
location.href= "mailto:" +
"?subject=" + "Please take immediate action" +
"&body="+
"%0APolicy: " + policy_num +
"%0ATask Closed: " + tclose +
"%0ATask Type: " + taskt +
"%0ATask Description: " + taskd +
"%0AAudit Outcome: " + audito +
"%0AAudit Comment: " + auditc ;
I am new to Esper and i am working on Storm-Esper collaboration.Through my main class,i send queries to a bolt which contains esper while the esper-bolt sends the tuple which contain the results to a printer bolt.My problem is that,although the result of a query is correct as for the values,the attribute values are not in the correct order.For example,i have a query which selects attributes from a pilot's table: name,surname,airline and i should have the result in the same order.However i get:name,airline,surname.I have tried everything concerning group by and order by.I suppose it must be an Esper's fault when creating the event's map which contains the attributes-values.I paste the main class code and the esper bolt code where the map is processed.Any idea why is that happening is most welcome!
**mainclass**
.addStatements(("insert into pilotStream " +
"select * " +
"from Log.win:time(120 second) A "))
.addStatements(("insert into employeeStream " +
"select * " +
"from Emp.win:time(120 second) A "))
.addStatements(("insert into CombinedEvent "+
"select tick.pilotName as p_name , " +
"tick.pilotSurname as p_surname , " +
"tick.airline as p_airline " +
"from pilotStream.win:time(120 second) as tick, " +
"employeeStream.win:time(120 second) as rom "+
"where tick.airline = rom.employeeAirline "+
))
**espebolt**
Map<String, Object> emap = (Map<String, Object>) newEvent.getUnderlying();
String Event_name = newEvent.getEventType().getName();
//System.out.println(Event_name);
for (Map.Entry<String, Object> entry : emap.entrySet()) {
// String key = entry.getKey();
String val = String.valueOf(entry.getValue()) ;
//System.out.println(key+" :"+val);
//System.out.println(val);
values.add(val);
}
collector.emit(Event_name, toTuple(newEvent, values, false));
values.removeAll(values);
The result should be : source: Esper-Print:2, stream: CombinedEvent, id: {}, [John, Snow, Lufthansa]
Instead,i get:source: Esper-Print:2, stream: CombinedEvent, id: {}, [John, Lufthansa, Snow]
P.S.The toTuple functions simply gets the values of the attributes through the values list of strings and puts them into a tuple which is emitted to printerbolt.In the espebolt code there is some printing in comments which helped me see that the problem is in the map which esper creates internally.
By default Esper generates Map events. This can be changed into object-array events when setting a configuration or with annotations. Map events use "HashMap" and not "LinkedHashMap". The "HashMap" is not ordered when iterating the key-value pairs but takes much less memory. Object-array is ordered. For ordered access to Map events there is the "EventType" that you can get from a statement which returns you the property names in order.
I keep getting the
"too many variables to unpack"
error. Can anybody help me get this working, and possibly give me an explanation?
wings_quantity = {
'small' : 8,
'medium' : 14,
'large' : 20,
'half bucket' : 30,
'bucket' : 65,
}
wings_price = {
'small' : 5.99,
'medium' :8.50,
'large' : 14.00,
'half bucket' :20.00,
'bucket' : 55.00
}
for number, key in wings_quantity:
print " "
print "There are "+(str(wings_quantity[number]))+ " wings in a "+(wings_quantity[key])+" size."
print " "
for number, key in wings_quantity:
ppw = wings_quantity[number] / wings_price[number]
print ('The cost per wing in a %s size is $') + ppw %wing_quantity[key]
You are close, but you forgot to put the iteritems() on the end of your for statements.
Change
for number, key in wings_quantity:
to
for number, key in wings_quantity.iteritems():
After that problem you need to rewrite your print statements as they are trying to access the dictionary twice. Since you already have the values you can just print them like so:
print "There are "+ key + " wings in a "+ str(value) +" size."
I tested this in 3.4 and it worked, but in 3.x you need to change it to
for number, key in wings_quantity.items():
This produced this output for the first loop
There are bucket wings in a 65 size.
There are small wings in a 8 size.
There are medium wings in a 14 size.
There are half bucket wings in a 30 size.
There are large wings in a 20 size.