How to set and apply offset to parent order setting in bracket order for Interactive brokers python api? - interactive-brokers

From TWS, I can place a bracket order where I can place the takeprofit and stoploss order with a setting "apply offset to parent order". How do one apply same setting "apply offset to parent order" from python API while placing bracket order? My code
parent.orderId = parentOrderId
parent.action = action
parent.orderType = "STP LMT"
parent.totalQuantity = quantity
parent.auxPrice=auxPrice
parent.lmtPrice = limitPrice #upper price when stop trigerred
#The parent and children orders will need this attribute set to False to prevent accidental executions.
#The LAST CHILD will have it set to True,
parent.transmit = False
takeProfit = Order()
takeProfit.orderId = getNextOrderID()
takeProfit.action = "SELL" if action == "BUY" else "BUY"
takeProfit.orderType = "LMT"
takeProfit.totalQuantity = quantity
takeProfit.lmtPrice = takeProfitLimitPrice
takeProfit.parentId = parentOrderId
takeProfit.transmit = False
stopLoss = Order()
stopLoss.orderId = getNextOrderID()
stopLoss.action = "SELL" if action == "BUY" else "BUY"
stopLoss.orderType = "STP"
#Stop trigger price
stopLoss.auxPrice = stopLossPrice
stopLoss.totalQuantity = quantity
stopLoss.parentId = parentOrderId
#In this case, the low side order will be the last child being sent. Therefore, it needs to set this attribute to True
#to activate all its predecessors
stopLoss.transmit = True

I wrote to IB team. Got this reply
Thank you for reaching out to Interactive Brokers.The said settings are related to presets and currently, there are no APIs which can configure the said settings.

Related

In Networkx is there a way to select when to save to a file, when show on screen and when both?

At the moment, I am doing both:
pos = nx.spring_layout(G)
f1 = plt.figure(figsize=(18,10))
default_axes = plt.axes(frameon=True)
nx.draw_networkx(G, node_size=600, alpha=0.8, ax=default_axes, pos=pos)
edge_labels = nx.get_edge_attributes(G, "weight")
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels)
plt.savefig('graph.jpg')
I would like to be able to select if to display, save or both (what I am doing now)
There is no built-in option for that in networkx. One option is to wrap the code in a function along these lines:
def custom(G, plot=True, save_file=False):
'''plots G by default. save_file should be a string'''
pos = nx.spring_layout(G)
f1 = plt.figure(figsize=(18,10))
default_axes = plt.axes(frameon=True)
nx.draw_networkx(G, node_size=600, alpha=0.8, ax=default_axes, pos=pos)
edge_labels = nx.get_edge_attributes(G, "weight")
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels)
if save: plt.savefig(save) # can allow custom save name
if plot: plt.show()
return
Note that if the figure displays regardless of the option passed to the command, then the inline option might need to be disabled.

Select particular listbox value on start of Dynpro?

I have a custom dialog dynpro including an input field named DYN_MATNR as listbox for which I have included a list of particular materials as selection.
How can I set a specific material (of that list) as selected when the dialog dynpro is opened?
PBO of dialog dynpro:
data lt_values type vrm_values.
select matnr,
maktx
into table #data(lt_materials)
from makt
where matnr in #so_matnr
and spras = 'D'
order by matnr.
loop at lt_materials assigning field-symbol(<material>).
append initial line to lt_values assigning field-symbol(<value>).
<value>-key = <material>-matnr.
<value>-text = <material>-maktx.
endloop.
call function 'VRM_SET_VALUES'
exporting
id = 'DYN_MATNR'
values = lt_values
exceptions
id_illegal_name = 1
others = 2.
if sy-subrc <> 0.
" ...
endif.
This works and it shows the list of materials as listbox values. To select a particular material I have included the FM DYNP_VALUES_UPDATE afterwards and also in PBO but this did not work:
data lv_stepl type syst-stepl.
call function 'DYNP_GET_STEPL'
importing
povstepl = lv_stepl
exceptions
stepl_not_found = 1
others = 2.
if sy-subrc <> 0.
" ...
endif.
data(lt_dynpfields) = value dynpread_tabtype(
( fieldname = 'DYN_MATNR'
stepl = lv_stepl
fieldvalue = gcl_helper->get_matnr( ) " matnr which should be selected is stored here
fieldinp = space )
).
call function 'DYNP_VALUES_UPDATE'
exporting
dyname = sy-repid
dynumb = sy-dynnr
tables
dynpfields = lt_dynpfields
exceptions
invalid_abapworkarea = 1
invalid_dynprofield = 2
invalid_dynproname = 3
invalid_dynpronummer = 4
invalid_request = 5
no_fielddescription = 6
undefind_error = 7
others = 8.
if sy-subrc <> 0.
" ...
endif.
I am also not able to directly set DYN_MATNR as it is not available in PBO.
Any hints?
Got it:
You need to additionally define a global(!) variable with the name and (wished) type of the input field (e.g. in the top include of the report or in a separate include of the dynpro logic):
data dyn_matnr type matnr.
Then you can set the initial value of the dynpro field in PBO directly:
dyn_matnr = gcl_helper->get_matnr( ).
As this becomes rather irritating when using various dialog dynpros I recommend including the dynpro number in those variables and input fields.

attempt to index a boolean value (local 'target')

I have looked at different ways to fix this but have no understanding at all. I've tried fixing the code in every was possible and still have no success.
RegisterServerEvent('housing:attemptsale')
AddEventHandler('housing:attemptsale',
function(args,price,hid,model)
local src = source
local user = exports["np-base"]:getModule("Player"):GetUser(src)
local char = user:getCurrentCharacter()
local target = exports["np-base"]:getModule("Player"):GetUser(args)
local targetchar = user:getCurrentCharacter()
if target:getCash() >= price then
target:removeMoney(price)
exports.ghmattimysql:execute("UPDATE houses SET `cid` = #cid, `price` = #price, `model` = #model WHERE `id` = #id", {
['#cid'] = targetchar.id,
['#price'] = price,
['#id'] = hid,
['#model'] = model
})
else
TriggerClientEvent('DoShortHudText', args, 'You dont got money', 2)
end
end)
As you did not provide any resources on those functiosn you're using there is not much we can do for you.
Actually this is pretty simple.
You're indexing a boolean value local target.
That means your doing something like target:something(), target.something, target[something].
Here you create target:
local target = exports["np-base"]:getModule("Player"):GetUser(args)
Then you do this target:getCash(). At this point target is a boolean, that means it is either true or false.
So you know exports["np-base"]:getModule("Player"):GetUser(args) returned true or false.
Now you have two options.
find out why the function returns a boolean and not what you expect and fix that
don't index target if target is not indexable.

How to setup the correct logic for picking a random item from a list based on item's rarity i.e "rare" "normal"

I'm writing a game using Corona SDK in lua language. I'm having a hard time coming up with a logic for a system like this;
I have different items. I want some items to have 1/1000 chance of being chosen (a unique item), I want some to have 1/10, some 2/10 etc.
I was thinking of populating a table and picking a random item. For example I'd add 100 of "X" item to the table and than 1 "Y" item. So by choosing randomly from [0,101] I kind of achieve what I want but I was wondering if there were any other ways of doing it.
items = {
Cat = { probability = 100/1000 }, -- i.e. 1/10
Dog = { probability = 200/1000 }, -- i.e. 2/10
Ant = { probability = 699/1000 },
Unicorn = { probability = 1/1000 },
}
function getRandomItem()
local p = math.random()
local cumulativeProbability = 0
for name, item in pairs(items) do
cumulativeProbability = cumulativeProbability + item.probability
if p <= cumulativeProbability then
return name, item
end
end
end
You want the probabilities to add up to 1. So if you increase the probability of an item (or add an item), you'll want to subtract from other items. That's why I wrote 1/10 as 100/1000: it's easier to see how things are distributed and to update them when you have a common denominator.
You can confirm you're getting the distribution you expect like this:
local count = { }
local iterations = 1000000
for i=1,iterations do
local name = getRandomItem()
count[name] = (count[name] or 0) + 1
end
for name, count in pairs(count) do
print(name, count/iterations)
end
I believe this answer is a lot easier to work with - albeit slightly slower in execution.
local chancesTbl = {
-- You can fill these with any non-negative integer you want
-- No need to make sure they sum up to anything specific
["a"] = 2,
["b"] = 1,
["c"] = 3
}
local function GetWeightedRandomKey()
local sum = 0
for _, chance in pairs(chancesTbl) do
sum = sum + chance
end
local rand = math.random(sum)
local winningKey
for key, chance in pairs(chancesTbl) do
winningKey = key
rand = rand - chance
if rand <= 0 then break end
end
return winningKey
end

Lua Insert table to table

Basic table, how they should be. But me need do it by function, how i can do that?
local mainMenu = {
caption = "Main Window",
description = "test window",
buttons = {
{ id = 1, value = "Info" },
{ id = 2, value = "Return" },
{ id = 3, value = "Ok" },
{ id = 4, value = "Cancel" }
},
popup = true
}
Table should be based on outside params, and code one table for each variable of options - not better way. I make a function for that, they should create basic options like caption or description and pop up, and insert values to buttons table (if option enabled - add button). But here the problem, they wont insert to tmp table, buttons table and their values for next options.
function createMenu()
tmp = {}
--buttons insert
if(config.info) then
table.insert(tmp, {buttons = {id = 1, value = "Info"}});
elseif(config.return) then
table.insert(tmp, {buttons = {id = 2, value = "Return"}});
end
--table main
table.insert(tmp, {
caption = "Main Window",
description = "test window",
popup = true
})
return tmp
end
How i can fixing them?
From looking at your createMenu function, two obvious problems stick out:
assigning to global tmp a new table every time createMenu is
called.
using the return keyword as a key in config.
One can be a problem if you use tmp somewhere else in your code outside the createMenu function. The obvious fix is to change it to:
local tmp = {}
For the second problem, you can use a lua keyword as a table key if you really want but you won't be able to use the . dot syntax to access this since Lua will parse this the wrong way. Instead, you need to change:
config.return
to
config["return"].
Edit: After reading your comment and checking the example table, it looks like only the button table is accessed by numerical index. In that case, you'll want to use table.insert only on button. If you want to create the table to have associative keys then you'll have to do something like this:
function createMenu()
local tmp =
{
--table main
caption = "Main Window",
description = "test window",
popup = true,
--button table
buttons = {}
}
--buttons insert
if config.info then
table.insert(tmp.buttons, {id = 1, value = "Info"});
elseif config['return'] then
table.insert(tmp.buttons, {id = 2, value = "Return"});
end
return tmp
end
This will produce the mainMenu table you're describing in your question.

Resources