Re: How can I pull my account value in as an object to help calculate my contract quantity size?
Maybe you are looking for something like this:?i
There is a code to get positions and NAVs for your account(s)
|
Re: order - close position by time condition
thank you for your precise answer!
?
It took me quite some time to understands what did you mean. Also, GAT order doesn't work with brackets, I have no idea why.?
|
Re: How to get the open orders
Here is the answer.? Email me if you want it in a dataframe and csv or want to create variables for particular items in this output and I can try to get that done for you.
Regards,
Javed
import logging
import time
import pandas as pd
from ibapi.utils import iswrapper
from ContractSamples import ContractSamples
from ibapi.client import EClient from ibapi.wrapper import EWrapper # types from ibapi.common import * # @UnusedWildImport from ibapi.contract import * # @UnusedWildImport from ibapi.order import Order from ibapi.order_state import OrderState
class TestApp(EWrapper, EClient): def __init__(self): EWrapper.__init__(self) EClient.__init__(self, wrapper=self) # ! [socket_init] self.nKeybInt = 0 self.started = False self.nextValidOrderId = None self.permId2ord = {} self.globalCancelOnly = False self.simplePlaceOid = None self._my_errors = {} self.data = [] # Initialize variable to store candle self.df = pd.DataFrame()
@iswrapper # ! [connectack] def connectAck(self): if self.asynchronous: self.startApi()
# ! [connectack]
@iswrapper # ! [nextvalidid] def nextValidId(self, orderId: int): super().nextValidId(orderId)
logging.debug("setting nextValidOrderId: %d", orderId) self.nextValidOrderId = orderId print("NextValidId:", orderId) # ! [nextvalidid]
# we can start now self.start()
def start(self): if self.started: return
self.started = True
if self.globalCancelOnly: print("Executing GlobalCancel only") self.reqGlobalCancel() else: print("Executing requests") self.orderOperations_req()
print("Executing requests ... finished")
def keyboardInterrupt(self): self.nKeybInt += 1 if self.nKeybInt == 1: self.stop() else: print("Finishing test") self.done = True
def stop(self): print("Executing cancels")
print("Executing cancels ... finished")
def nextOrderId(self): oid = self.nextValidOrderId self.nextValidOrderId += 1 return oid
@iswrapper # ! [error] def error(self, reqId: TickerId, errorCode: int, errorString: str): super().error(reqId, errorCode, errorString) print("Error. Id:", reqId, "Code:", errorCode, "Msg:", errorString) errormsg = "IB error id %d errorcode %d string %s" % (reqId, errorCode, errorString) self._my_errors = errormsg
@iswrapper def winError(self, text: str, lastError: int): super().winError(text, lastError)
def orderOperations_req(self): # Requesting all open orders # ! [reqallopenorders] self.reqAllOpenOrders() # ! [reqallopenorders]
def openOrder(self, orderId: OrderId, contract: Contract, order: Order, orderState: OrderState): super().openOrder(orderId, contract, order, orderState) print("OpenOrder. PermId: ", order.permId, "ClientId:", order.clientId, " OrderId:", orderId, "Account:", order.account, "Symbol:", contract.symbol, "SecType:", contract.secType, "Exchange:", contract.exchange, "Action:", order.action, "OrderType:", order.orderType, "TotalQty:", order.totalQuantity, "CashQty:", order.cashQty, "LmtPrice:", order.lmtPrice, "AuxPrice:", order.auxPrice, "Status:", orderState.status)
order.contract = contract self.permId2ord[order.permId] = order # ! [openorder]
# ! [openorderend] def openOrderEnd(self): super().openOrderEnd() print("OpenOrderEnd")
logging.debug("Received %d openOrders", len(self.permId2ord))
# ! [openorderend]
# ! [orderstatus] def orderStatus(self, orderId: OrderId, status: str, filled: float, remaining: float, avgFillPrice: float, permId: int, parentId: int, lastFillPrice: float, clientId: int, whyHeld: str, mktCapPrice: float): super().orderStatus(orderId, status, filled, remaining, avgFillPrice, permId, parentId, lastFillPrice, clientId, whyHeld, mktCapPrice) print("OrderStatus. Id:", orderId, "Status:", status, "Filled:", filled, "Remaining:", remaining, "AvgFillPrice:", avgFillPrice, "PermId:", permId, "ParentId:", parentId, "LastFillPrice:", lastFillPrice, "ClientId:", clientId, "WhyHeld:", whyHeld, "MktCapPrice:", mktCapPrice) self.disconnect() # ! [orderstatus]
def main():
app = TestApp() try:
# ! [connect] app.connect("127.0.0.1", port=7497, clientId=102) # ! [connect] print("serverVersion:%s connectionTime:%s" % (app.serverVersion(), app.twsConnectionTime())) # ! [clientrun] app.run()
# ! [clientrun] except: raise
if __name__ == "__main__": main()
toggle quoted message
Show quoted text
Hello,
Could somebody please help me with what API call I need to make to get the current open orders?
I tried with but it's returning nothing.
Thanks for the help!
|
Re: How can I pull my account value in as an object to help calculate my contract quantity size?
Okay, I threw it into a list, dataframe and csv:
import logging
import time
import pandas as pd
from ibapi.utils import iswrapper
from ContractSamples import ContractSamples
from ibapi.client import EClient from ibapi.wrapper import EWrapper # types from ibapi.common import * # @UnusedWildImport from ibapi.contract import * # @UnusedWildImport
class TestApp(EWrapper, EClient): def __init__(self): EWrapper.__init__(self) EClient.__init__(self, wrapper=self) # ! [socket_init] self.nKeybInt = 0 self.started = False self.nextValidOrderId = None self.permId2ord = {} self.globalCancelOnly = False self.simplePlaceOid = None self._my_errors = {} self.data = [] # Initialize variable to store candle self.df = pd.DataFrame()
@iswrapper # ! [connectack] def connectAck(self): if self.asynchronous: self.startApi()
# ! [connectack]
@iswrapper # ! [nextvalidid] def nextValidId(self, orderId: int): super().nextValidId(orderId)
logging.debug("setting nextValidOrderId: %d", orderId) self.nextValidOrderId = orderId print("NextValidId:", orderId) # ! [nextvalidid]
# we can start now self.start()
def start(self): if self.started: return
self.started = True
if self.globalCancelOnly: print("Executing GlobalCancel only") self.reqGlobalCancel() else: print("Executing requests") self.accountOperations_req() print("Executing requests ... finished")
def keyboardInterrupt(self): self.nKeybInt += 1 if self.nKeybInt == 1: self.stop() else: print("Finishing test") self.done = True
def stop(self): print("Executing cancels")
print("Executing cancels ... finished")
def nextOrderId(self): oid = self.nextValidOrderId self.nextValidOrderId += 1 return oid
@iswrapper # ! [error] def error(self, reqId: TickerId, errorCode: int, errorString: str): super().error(reqId, errorCode, errorString) print("Error. Id:", reqId, "Code:", errorCode, "Msg:", errorString) errormsg = "IB error id %d errorcode %d string %s" % (reqId, errorCode, errorString) self._my_errors = errormsg
@iswrapper def winError(self, text: str, lastError: int): super().winError(text, lastError)
def accountOperations_req(self): # Requesting accounts' summary # ! [reqaaccountsummary] self.reqAccountSummary(9002, "All", "$LEDGER") # ! [reqaaccountsummary]
# ! [accountsummary] def accountSummary(self, reqId: int, account: str, tag: str, value: str, currency: str): super().accountSummary(reqId, account, tag, value, currency) print("AccountSummary. ReqId:", reqId, "Account:", account, "Tag: ", tag, "Value:", value, "Currency:", currency) self.data.append([tag, value])
# print("HistoricalData. ReqId:", reqId, "BarData.", bar) self.df = pd.DataFrame(self.data)
print(self.df) self.df.to_csv('acct_value.csv')
# ! [accountsummary]
# ! [accountsummaryend] def accountSummaryEnd(self, reqId: int): super().accountSummaryEnd(reqId) print("AccountSummaryEnd. ReqId:", reqId)
self.disconnect() # ! [accountsummaryend]
def main():
app = TestApp() try:
# ! [connect] app.connect("127.0.0.1", port=7497, clientId=102) # ! [connect] print("serverVersion:%s connectionTime:%s" % (app.serverVersion(), app.twsConnectionTime())) # ! [clientrun] app.run()
# ! [clientrun] except: raise
if __name__ == "__main__": main()
toggle quoted message
Show quoted text
Here is how you pull the account value (code below).
Throw it into a list or pandas dataframe, and then pull out the value you want to focus on and apply your 5% to it.
import logging
import time
import pandas as pd
from ibapi.utils import iswrapper
from ContractSamples import ContractSamples
from ibapi.client import EClient from ibapi.wrapper import EWrapper # types from ibapi.common import * # @UnusedWildImport from ibapi.contract import * # @UnusedWildImport
class TestApp(EWrapper, EClient): def __init__(self): EWrapper.__init__(self) EClient.__init__(self, wrapper=self) # ! [socket_init] self.nKeybInt = 0 self.started = False self.nextValidOrderId = None self.permId2ord = {} self.globalCancelOnly = False self.simplePlaceOid = None self._my_errors = {} self.data = [] # Initialize variable to store candle self.contract = Contract() self.i = 0 self.df = pd.DataFrame() self.strike_list = []
@iswrapper # ! [connectack] def connectAck(self): if self.asynchronous: self.startApi()
# ! [connectack]
@iswrapper # ! [nextvalidid] def nextValidId(self, orderId: int): super().nextValidId(orderId)
logging.debug("setting nextValidOrderId: %d", orderId) self.nextValidOrderId = orderId print("NextValidId:", orderId) # ! [nextvalidid]
# we can start now self.start()
def start(self): if self.started: return
self.started = True
if self.globalCancelOnly: print("Executing GlobalCancel only") self.reqGlobalCancel() else: print("Executing requests") self.accountOperations_req() print("Executing requests ... finished")
def keyboardInterrupt(self): self.nKeybInt += 1 if self.nKeybInt == 1: self.stop() else: print("Finishing test") self.done = True
def stop(self): print("Executing cancels")
print("Executing cancels ... finished")
def nextOrderId(self): oid = self.nextValidOrderId self.nextValidOrderId += 1 return oid
@iswrapper # ! [error] def error(self, reqId: TickerId, errorCode: int, errorString: str): super().error(reqId, errorCode, errorString) print("Error. Id:", reqId, "Code:", errorCode, "Msg:", errorString) errormsg = "IB error id %d errorcode %d string %s" % (reqId, errorCode, errorString) self._my_errors = errormsg
@iswrapper def winError(self, text: str, lastError: int): super().winError(text, lastError)
def accountOperations_req(self): # Requesting accounts' summary # ! [reqaaccountsummary] self.reqAccountSummary(9002, "All", "$LEDGER") # ! [reqaaccountsummary]
# ! [accountsummary] def accountSummary(self, reqId: int, account: str, tag: str, value: str, currency: str): super().accountSummary(reqId, account, tag, value, currency) print("AccountSummary. ReqId:", reqId, "Account:", account, "Tag: ", tag, "Value:", value, "Currency:", currency) # ! [accountsummary]
# ! [accountsummaryend] def accountSummaryEnd(self, reqId: int): super().accountSummaryEnd(reqId) print("AccountSummaryEnd. ReqId:", reqId) self.disconnect() # ! [accountsummaryend]
def main():
app = TestApp() try:
# ! [connect] app.connect("127.0.0.1", port=7497, clientId=102) # ! [connect] print("serverVersion:%s connectionTime:%s" % (app.serverVersion(), app.twsConnectionTime())) # ! [clientrun] app.run()
# ! [clientrun] except: raise
if __name__ == "__main__": main()
Use the value variable here:
Email me direct and I can take a crack at it for you.
Regards,
Javed Using python, how can I pull in my account size as a value to help calc the quantity of my contract size?? ?For instance, if I have a $50K account and I want to only risk 5% on any trade, I would like to do something like:?
quantity = np.floor(account value/contract price)??
Currently in my api class, I have:
class IBApi(EWrapper,EClient):
? ? def __init__(self):
? ? ? ? EClient.__init__(self, self)
? ? ? ? self.funds = 0.0
?
? ? # Historical Backtest Data
? ? def historicalData(self, reqId, bar):
? ? ? ? try:
? ? ? ? ? ? bot.on_bar_update(reqId,bar,False)
? ? ? ? except Exception as e:
? ? ? ? ? ? print(e)
? ? # On Realtime Bar after historical data finishes
? ? def historicalDataUpdate(self, reqId, bar):
? ? ? ? try:
? ? ? ? ? ? bot.on_bar_update(reqId,bar,True)
? ? ? ? except Exception as e:
? ? ? ? ? ? print(e)
? ? # On Historical Data End
? ? def historicalDataEnd(self, reqId, start, end):
? ? ? ? print(reqId)
?
? ? def nextValidId(self, nextorderId):
? ? ? ? global orderId
? ? ? ? orderId = nextorderId
? ? ??
? ? def error(self, id, errorCode, errorMsg):
? ? ? ? print(errorCode)
? ? ? ? print(errorMsg)
? ? ? ??
? ? @iswrapper
? ? def accountSummary(self, req_id, acct, tag, val, currency):
? ? ? ? ''' Called in response to reqAccountSummary '''
?
? ? ? ? if tag == 'AvailableFunds':
? ? ? ? ? ? print('Account {}: available funds = {}'.format(acct, val))
? ? ? ? ? ? self.funds = float(val)
But I'm having trouble bringing that into my bot class which is below:
class Bot:
? ? ib = None
? ? reqId = 1
? ? SLOW_PERIOD = 30
? ? FAST_PERIOD = 6
? ? global orderId
? ? initialbartime = datetime.datetime.now().astimezone(pytz.timezone("America/New_York"))
? ? def __init__(self):
? ? ? ? #Connect to IB on init
? ? ? ? self.ib = IBApi()
? ? ? ? self.ib.connect("127.0.0.1", 7497,1)
? ? ? ? ib_thread = threading.Thread(target=self.run_loop, daemon=True)
? ? ? ? ib_thread.start()
? ? ? ? self.funds = self.funds
?
? ? ? ? self.low = collections.deque(maxlen=SLOW_PERIOD)
? ? ? ? self.high = collections.deque(maxlen=SLOW_PERIOD)
? ? ? ? self.close = collections.deque(maxlen=SLOW_PERIOD)
? ? ? ? self.long_ema = collections.deque(maxlen=SLOW_PERIOD)
? ? ? ? self.short_ema = collections.deque(maxlen=FAST_PERIOD)
? ? ? ? self.nmc = 0
? ? ? ??
? ? ? ? #Create our IB Contract Object
? ? ? ? contract = Contract()
? ? ? ? contract.symbol = "ES"
? ? ? ? contract.secType = "FUT"
? ? ? ? contract.exchange = "GLOBEX"
? ? ? ? contract.currency = "USD"
? ? ? ? contract.lastTradeDateOrContractMonth = "202109"
? ? ? ? self.ib.reqIds(-1)
?
? ? ? ? self.ib.reqHistoricalData(self.reqId,contract,"","5 D","5 mins","TRADES",0,1,True,[])
? ? ? ? # self.ib.reqPositions(self.reqId)
? ? ? ? # print(self.pos)
? ? #Listen to socket in seperate thread
? ? def run_loop(self):
? ? ? ? self.ib.run()
?
? ? #Bracet Order Setup
? ? def bracketOrder(self, parentOrderId, action, quantity, profitTarget, stopLoss):
? ? ? ? #Initial Entry? ? ? ??
? ? ? ? # Create Parent Order / Initial Entry
? ? ? ? parent = Order()
? ? ? ? parent.orderId = parentOrderId
? ? ? ? parent.orderType = "MKT"
? ? ? ? parent.action = action
? ? ? ? parent.totalQuantity = quantity
? ? ? ? parent.transmit = False
? ? ? ? # Profit Target
? ? ? ? profitTargetOrder = Order()
? ? ? ? profitTargetOrder.orderId = parent.orderId+1
? ? ? ? profitTargetOrder.orderType = "LMT"
? ? ? ? profitTargetOrder.action = "SELL" if action == "BUY" else "BUY"
? ? ? ? profitTargetOrder.totalQuantity = quantity
? ? ? ? profitTargetOrder.lmtPrice = profitTarget
? ? ? ? profitTargetOrder.parentId = parentOrderId
? ? ? ? profitTargetOrder.transmit = False
? ? ? ? # Stop Loss
? ? ? ? stopLossOrder = Order()
? ? ? ? stopLossOrder.orderId = parent.orderId+2
? ? ? ? stopLossOrder.orderType = "STP"
? ? ? ? stopLossOrder.action = "SELL" if action == "BUY" else "BUY"
? ? ? ? stopLossOrder.totalQuantity = quantity
? ? ? ? stopLossOrder.parentId = parentOrderId
? ? ? ? stopLossOrder.auxPrice = stopLoss
? ? ? ? stopLossOrder.transmit = True
?
? ? ? ? bracketOrders = [parent, profitTargetOrder, stopLossOrder]
? ? ? ??
? ? ? ? return bracketOrders
? ??
? ? #Pass realtime bar data back to our bot object
? ? def on_bar_update(self, reqId, bar,realtime):
? ? ? ? global orderId
? ? ? ? global position_
? ? ? ? # if self.pos > 0:
? ? ? ? #? ? ?print("{} Position/s on in {}.".format(self.pos, contract.symbol))
? ? ? ? # else:
? ? ? ? #append values
? ? ? ? self.low.append(bar.close)
? ? ? ? self.high.append(bar.high)
? ? ? ? self.close.append(bar.close)
? ? ? ? self.long_ema.append(bar.close)
? ? ? ? self.short_ema.append(bar.close)
? ? ? ??
? ? ? ? #check time for market hours (regular)
? ? ? ? now = datetime.datetime.now()
? ? ? ? if (now.time() < datetime.time(9,30) or now.time() > datetime.time(16,00)):
? ? ? ? ? ? print("Regular Market Hours Not Open")
? ? ? ? else:
? ? ? ? ? ? ? ? ? ? ? ??
? ? ? ? ? ? ? ? self.preds = (self.diff_rsi*4.977e-05)+(self.nmc*3.785e-05)
? ? ? ? ? ? ? ??
? ? ? ? ? ? ? ? print("Prediction : {}. Position is {}".format(self.preds, position_))
? ??
? ? ? ? ? ? ? ? ? ? # Check Criteria
? ? ? ? ? ? ? ? if (self.preds >= -0.000411116078039124
? ? ) and (position_ == 'out'):
? ? ? ? ? ? ? ? ? ? #Bracket Order 4% Profit Target 1% Stop Loss
? ? ? ? ? ? ? ? ? ? profitTarget_ = round(((bar.close*1.04)*4)/4)
? ? ? ? ? ? ? ? ? ? stopLoss_ = round(((bar.close*.99)*4)/4)
? ? ? ? ? ? ? ? ? ? quantity_ = 1
? ? ? ? ? ? ? ? ? ? bracket = self.bracketOrder(orderId,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? action ="BUY",quantity=quantity_,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? profitTarget=profitTarget_,?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? stopLoss = stopLoss_)
? ? ? ? ? ? ? ? ? ? contract = Contract()
? ? ? ? ? ? ? ? ? ? contract.symbol = "ES"
? ? ? ? ? ? ? ? ? ? contract.secType = "FUT"
? ? ? ? ? ? ? ? ? ? contract.exchange = "GLOBEX"
? ? ? ? ? ? ? ? ? ? contract.currency = "USD"
? ? ? ? ? ? ? ? ? ? contract.lastTradeDateOrContractMonth = "202109"
?
? ? ? ? ? ? ? ? ? ? # Place Bracket Order
? ? ? ? ? ? ? ? ? ? for o in bracket:
? ? ? ? ? ? ? ? ? ? ? ? # o.ocaGroup = "OCA_"+str(orderId)
? ? ? ? ? ? ? ? ? ? ? ? self.ib.placeOrder(o.orderId,contract,o)
? ? ? ? ? ? ? ? ? ? ? ? print(o.orderId)
? ? ? ? ? ? ? ? ? ? ? ? # self.nextorderId()
? ? ? ? ? ? ? ? ? ? orderId += 3
? ? ? ? ? ? ? ? ? ? position_ = "long"
? ? ? ? ? ? ? ? ? ? print(position_, "Order placed on IDs", orderId)
?
? ? ? ? ? ? ? ? ? ??
? ? ? ? ? ? ? ? elif (self.preds <= -0.000889676
? ? ) and position_ == 'out':
? ? ? ? ? ? ? ? ? ? # Bracket Order 4% Profit Target 1% Stop Loss
? ? ? ? ? ? ? ? ? ? profitTarget_ = round(((price*.96)*4)/4)
? ? ? ? ? ? ? ? ? ? stopLoss_ = round((bar.close*1.02)*4)/4
? ? ? ? ? ? ? ? ? ? quantity_ = 1
? ? ? ? ? ? ? ? ? ? bracket_s = self.bracketOrder(orderId,action = "SELL",?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? quantity=quantity_,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? profitTarget=profitTarget_,?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? stopLoss = stopLoss_ )
? ? ? ? ? ? ? ? ? ? contract = Contract()
? ? ? ? ? ? ? ? ? ? contract.symbol = "ES"
? ? ? ? ? ? ? ? ? ? contract.secType = "FUT"
? ? ? ? ? ? ? ? ? ? contract.exchange = "GLOBEX"
? ? ? ? ? ? ? ? ? ? contract.currency = "USD"
? ? ? ? ? ? ? ? ? ? contract.lastTradeDateOrContractMonth = "202109"
? ? ??
? ? ? ? ? ? ? ? ? ? for o in bracket_s:
? ? ? ? ? ? ? ? ? ? ? ? print(o.orderId)
? ? ? ? ? ? ? ? ? ? ? ? self.ib.placeOrder(o.orderId,contract,o)
? ? ? ? ? ? ? ? ? ? ? ? print(o.orderId)
? ? ? ? ? ? ? ? ? ? orderId += 3
? ? ? ? ? ? ? ? ? ? position_ = "Short"
? ? ? ? ? ? ? ? ? ? print(position_, "Order placed on IDs", orderId)
?
#Start Bot
bot = Bot()
?
|
Re: How can I pull my account value in as an object to help calculate my contract quantity size?
Here is how you pull the account value (code below).
Throw it into a list or pandas dataframe, and then pull out the value you want to focus on and apply your 5% to it.
import logging
import time
import pandas as pd
from ibapi.utils import iswrapper
from ContractSamples import ContractSamples
from ibapi.client import EClient from ibapi.wrapper import EWrapper # types from ibapi.common import * # @UnusedWildImport from ibapi.contract import * # @UnusedWildImport
class TestApp(EWrapper, EClient): def __init__(self): EWrapper.__init__(self) EClient.__init__(self, wrapper=self) # ! [socket_init] self.nKeybInt = 0 self.started = False self.nextValidOrderId = None self.permId2ord = {} self.globalCancelOnly = False self.simplePlaceOid = None self._my_errors = {} self.data = [] # Initialize variable to store candle self.contract = Contract() self.i = 0 self.df = pd.DataFrame() self.strike_list = []
@iswrapper # ! [connectack] def connectAck(self): if self.asynchronous: self.startApi()
# ! [connectack]
@iswrapper # ! [nextvalidid] def nextValidId(self, orderId: int): super().nextValidId(orderId)
logging.debug("setting nextValidOrderId: %d", orderId) self.nextValidOrderId = orderId print("NextValidId:", orderId) # ! [nextvalidid]
# we can start now self.start()
def start(self): if self.started: return
self.started = True
if self.globalCancelOnly: print("Executing GlobalCancel only") self.reqGlobalCancel() else: print("Executing requests") self.accountOperations_req() print("Executing requests ... finished")
def keyboardInterrupt(self): self.nKeybInt += 1 if self.nKeybInt == 1: self.stop() else: print("Finishing test") self.done = True
def stop(self): print("Executing cancels")
print("Executing cancels ... finished")
def nextOrderId(self): oid = self.nextValidOrderId self.nextValidOrderId += 1 return oid
@iswrapper # ! [error] def error(self, reqId: TickerId, errorCode: int, errorString: str): super().error(reqId, errorCode, errorString) print("Error. Id:", reqId, "Code:", errorCode, "Msg:", errorString) errormsg = "IB error id %d errorcode %d string %s" % (reqId, errorCode, errorString) self._my_errors = errormsg
@iswrapper def winError(self, text: str, lastError: int): super().winError(text, lastError)
def accountOperations_req(self): # Requesting accounts' summary # ! [reqaaccountsummary] self.reqAccountSummary(9002, "All", "$LEDGER") # ! [reqaaccountsummary]
# ! [accountsummary] def accountSummary(self, reqId: int, account: str, tag: str, value: str, currency: str): super().accountSummary(reqId, account, tag, value, currency) print("AccountSummary. ReqId:", reqId, "Account:", account, "Tag: ", tag, "Value:", value, "Currency:", currency) # ! [accountsummary]
# ! [accountsummaryend] def accountSummaryEnd(self, reqId: int): super().accountSummaryEnd(reqId) print("AccountSummaryEnd. ReqId:", reqId) self.disconnect() # ! [accountsummaryend]
def main():
app = TestApp() try:
# ! [connect] app.connect("127.0.0.1", port=7497, clientId=102) # ! [connect] print("serverVersion:%s connectionTime:%s" % (app.serverVersion(), app.twsConnectionTime())) # ! [clientrun] app.run()
# ! [clientrun] except: raise
if __name__ == "__main__": main()
toggle quoted message
Show quoted text
Use the value variable here:
Email me direct and I can take a crack at it for you.
Regards,
Javed Using python, how can I pull in my account size as a value to help calc the quantity of my contract size?? ?For instance, if I have a $50K account and I want to only risk 5% on any trade, I would like to do something like:?
quantity = np.floor(account value/contract price)??
Currently in my api class, I have:
class IBApi(EWrapper,EClient):
? ? def __init__(self):
? ? ? ? EClient.__init__(self, self)
? ? ? ? self.funds = 0.0
?
? ? # Historical Backtest Data
? ? def historicalData(self, reqId, bar):
? ? ? ? try:
? ? ? ? ? ? bot.on_bar_update(reqId,bar,False)
? ? ? ? except Exception as e:
? ? ? ? ? ? print(e)
? ? # On Realtime Bar after historical data finishes
? ? def historicalDataUpdate(self, reqId, bar):
? ? ? ? try:
? ? ? ? ? ? bot.on_bar_update(reqId,bar,True)
? ? ? ? except Exception as e:
? ? ? ? ? ? print(e)
? ? # On Historical Data End
? ? def historicalDataEnd(self, reqId, start, end):
? ? ? ? print(reqId)
?
? ? def nextValidId(self, nextorderId):
? ? ? ? global orderId
? ? ? ? orderId = nextorderId
? ? ??
? ? def error(self, id, errorCode, errorMsg):
? ? ? ? print(errorCode)
? ? ? ? print(errorMsg)
? ? ? ??
? ? @iswrapper
? ? def accountSummary(self, req_id, acct, tag, val, currency):
? ? ? ? ''' Called in response to reqAccountSummary '''
?
? ? ? ? if tag == 'AvailableFunds':
? ? ? ? ? ? print('Account {}: available funds = {}'.format(acct, val))
? ? ? ? ? ? self.funds = float(val)
But I'm having trouble bringing that into my bot class which is below:
class Bot:
? ? ib = None
? ? reqId = 1
? ? SLOW_PERIOD = 30
? ? FAST_PERIOD = 6
? ? global orderId
? ? initialbartime = datetime.datetime.now().astimezone(pytz.timezone("America/New_York"))
? ? def __init__(self):
? ? ? ? #Connect to IB on init
? ? ? ? self.ib = IBApi()
? ? ? ? self.ib.connect("127.0.0.1", 7497,1)
? ? ? ? ib_thread = threading.Thread(target=self.run_loop, daemon=True)
? ? ? ? ib_thread.start()
? ? ? ? self.funds = self.funds
?
? ? ? ? self.low = collections.deque(maxlen=SLOW_PERIOD)
? ? ? ? self.high = collections.deque(maxlen=SLOW_PERIOD)
? ? ? ? self.close = collections.deque(maxlen=SLOW_PERIOD)
? ? ? ? self.long_ema = collections.deque(maxlen=SLOW_PERIOD)
? ? ? ? self.short_ema = collections.deque(maxlen=FAST_PERIOD)
? ? ? ? self.nmc = 0
? ? ? ??
? ? ? ? #Create our IB Contract Object
? ? ? ? contract = Contract()
? ? ? ? contract.symbol = "ES"
? ? ? ? contract.secType = "FUT"
? ? ? ? contract.exchange = "GLOBEX"
? ? ? ? contract.currency = "USD"
? ? ? ? contract.lastTradeDateOrContractMonth = "202109"
? ? ? ? self.ib.reqIds(-1)
?
? ? ? ? self.ib.reqHistoricalData(self.reqId,contract,"","5 D","5 mins","TRADES",0,1,True,[])
? ? ? ? # self.ib.reqPositions(self.reqId)
? ? ? ? # print(self.pos)
? ? #Listen to socket in seperate thread
? ? def run_loop(self):
? ? ? ? self.ib.run()
?
? ? #Bracet Order Setup
? ? def bracketOrder(self, parentOrderId, action, quantity, profitTarget, stopLoss):
? ? ? ? #Initial Entry? ? ? ??
? ? ? ? # Create Parent Order / Initial Entry
? ? ? ? parent = Order()
? ? ? ? parent.orderId = parentOrderId
? ? ? ? parent.orderType = "MKT"
? ? ? ? parent.action = action
? ? ? ? parent.totalQuantity = quantity
? ? ? ? parent.transmit = False
? ? ? ? # Profit Target
? ? ? ? profitTargetOrder = Order()
? ? ? ? profitTargetOrder.orderId = parent.orderId+1
? ? ? ? profitTargetOrder.orderType = "LMT"
? ? ? ? profitTargetOrder.action = "SELL" if action == "BUY" else "BUY"
? ? ? ? profitTargetOrder.totalQuantity = quantity
? ? ? ? profitTargetOrder.lmtPrice = profitTarget
? ? ? ? profitTargetOrder.parentId = parentOrderId
? ? ? ? profitTargetOrder.transmit = False
? ? ? ? # Stop Loss
? ? ? ? stopLossOrder = Order()
? ? ? ? stopLossOrder.orderId = parent.orderId+2
? ? ? ? stopLossOrder.orderType = "STP"
? ? ? ? stopLossOrder.action = "SELL" if action == "BUY" else "BUY"
? ? ? ? stopLossOrder.totalQuantity = quantity
? ? ? ? stopLossOrder.parentId = parentOrderId
? ? ? ? stopLossOrder.auxPrice = stopLoss
? ? ? ? stopLossOrder.transmit = True
?
? ? ? ? bracketOrders = [parent, profitTargetOrder, stopLossOrder]
? ? ? ??
? ? ? ? return bracketOrders
? ??
? ? #Pass realtime bar data back to our bot object
? ? def on_bar_update(self, reqId, bar,realtime):
? ? ? ? global orderId
? ? ? ? global position_
? ? ? ? # if self.pos > 0:
? ? ? ? #? ? ?print("{} Position/s on in {}.".format(self.pos, contract.symbol))
? ? ? ? # else:
? ? ? ? #append values
? ? ? ? self.low.append(bar.close)
? ? ? ? self.high.append(bar.high)
? ? ? ? self.close.append(bar.close)
? ? ? ? self.long_ema.append(bar.close)
? ? ? ? self.short_ema.append(bar.close)
? ? ? ??
? ? ? ? #check time for market hours (regular)
? ? ? ? now = datetime.datetime.now()
? ? ? ? if (now.time() < datetime.time(9,30) or now.time() > datetime.time(16,00)):
? ? ? ? ? ? print("Regular Market Hours Not Open")
? ? ? ? else:
? ? ? ? ? ? ? ? ? ? ? ??
? ? ? ? ? ? ? ? self.preds = (self.diff_rsi*4.977e-05)+(self.nmc*3.785e-05)
? ? ? ? ? ? ? ??
? ? ? ? ? ? ? ? print("Prediction : {}. Position is {}".format(self.preds, position_))
? ??
? ? ? ? ? ? ? ? ? ? # Check Criteria
? ? ? ? ? ? ? ? if (self.preds >= -0.000411116078039124
? ? ) and (position_ == 'out'):
? ? ? ? ? ? ? ? ? ? #Bracket Order 4% Profit Target 1% Stop Loss
? ? ? ? ? ? ? ? ? ? profitTarget_ = round(((bar.close*1.04)*4)/4)
? ? ? ? ? ? ? ? ? ? stopLoss_ = round(((bar.close*.99)*4)/4)
? ? ? ? ? ? ? ? ? ? quantity_ = 1
? ? ? ? ? ? ? ? ? ? bracket = self.bracketOrder(orderId,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? action ="BUY",quantity=quantity_,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? profitTarget=profitTarget_,?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? stopLoss = stopLoss_)
? ? ? ? ? ? ? ? ? ? contract = Contract()
? ? ? ? ? ? ? ? ? ? contract.symbol = "ES"
? ? ? ? ? ? ? ? ? ? contract.secType = "FUT"
? ? ? ? ? ? ? ? ? ? contract.exchange = "GLOBEX"
? ? ? ? ? ? ? ? ? ? contract.currency = "USD"
? ? ? ? ? ? ? ? ? ? contract.lastTradeDateOrContractMonth = "202109"
?
? ? ? ? ? ? ? ? ? ? # Place Bracket Order
? ? ? ? ? ? ? ? ? ? for o in bracket:
? ? ? ? ? ? ? ? ? ? ? ? # o.ocaGroup = "OCA_"+str(orderId)
? ? ? ? ? ? ? ? ? ? ? ? self.ib.placeOrder(o.orderId,contract,o)
? ? ? ? ? ? ? ? ? ? ? ? print(o.orderId)
? ? ? ? ? ? ? ? ? ? ? ? # self.nextorderId()
? ? ? ? ? ? ? ? ? ? orderId += 3
? ? ? ? ? ? ? ? ? ? position_ = "long"
? ? ? ? ? ? ? ? ? ? print(position_, "Order placed on IDs", orderId)
?
? ? ? ? ? ? ? ? ? ??
? ? ? ? ? ? ? ? elif (self.preds <= -0.000889676
? ? ) and position_ == 'out':
? ? ? ? ? ? ? ? ? ? # Bracket Order 4% Profit Target 1% Stop Loss
? ? ? ? ? ? ? ? ? ? profitTarget_ = round(((price*.96)*4)/4)
? ? ? ? ? ? ? ? ? ? stopLoss_ = round((bar.close*1.02)*4)/4
? ? ? ? ? ? ? ? ? ? quantity_ = 1
? ? ? ? ? ? ? ? ? ? bracket_s = self.bracketOrder(orderId,action = "SELL",?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? quantity=quantity_,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? profitTarget=profitTarget_,?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? stopLoss = stopLoss_ )
? ? ? ? ? ? ? ? ? ? contract = Contract()
? ? ? ? ? ? ? ? ? ? contract.symbol = "ES"
? ? ? ? ? ? ? ? ? ? contract.secType = "FUT"
? ? ? ? ? ? ? ? ? ? contract.exchange = "GLOBEX"
? ? ? ? ? ? ? ? ? ? contract.currency = "USD"
? ? ? ? ? ? ? ? ? ? contract.lastTradeDateOrContractMonth = "202109"
? ? ??
? ? ? ? ? ? ? ? ? ? for o in bracket_s:
? ? ? ? ? ? ? ? ? ? ? ? print(o.orderId)
? ? ? ? ? ? ? ? ? ? ? ? self.ib.placeOrder(o.orderId,contract,o)
? ? ? ? ? ? ? ? ? ? ? ? print(o.orderId)
? ? ? ? ? ? ? ? ? ? orderId += 3
? ? ? ? ? ? ? ? ? ? position_ = "Short"
? ? ? ? ? ? ? ? ? ? print(position_, "Order placed on IDs", orderId)
?
#Start Bot
bot = Bot()
?
|
Re: How can I pull my account value in as an object to help calculate my contract quantity size?
Use the value variable here:
Email me direct and I can take a crack at it for you.
Regards,
Javed
toggle quoted message
Show quoted text
Using python, how can I pull in my account size as a value to help calc the quantity of my contract size?? ?For instance, if I have a $50K account and I want to only risk 5% on any trade, I would like to do something like:?
quantity = np.floor(account value/contract price)??
Currently in my api class, I have:
class IBApi(EWrapper,EClient):
? ? def __init__(self):
? ? ? ? EClient.__init__(self, self)
? ? ? ? self.funds = 0.0
?
? ? # Historical Backtest Data
? ? def historicalData(self, reqId, bar):
? ? ? ? try:
? ? ? ? ? ? bot.on_bar_update(reqId,bar,False)
? ? ? ? except Exception as e:
? ? ? ? ? ? print(e)
? ? # On Realtime Bar after historical data finishes
? ? def historicalDataUpdate(self, reqId, bar):
? ? ? ? try:
? ? ? ? ? ? bot.on_bar_update(reqId,bar,True)
? ? ? ? except Exception as e:
? ? ? ? ? ? print(e)
? ? # On Historical Data End
? ? def historicalDataEnd(self, reqId, start, end):
? ? ? ? print(reqId)
?
? ? def nextValidId(self, nextorderId):
? ? ? ? global orderId
? ? ? ? orderId = nextorderId
? ? ??
? ? def error(self, id, errorCode, errorMsg):
? ? ? ? print(errorCode)
? ? ? ? print(errorMsg)
? ? ? ??
? ? @iswrapper
? ? def accountSummary(self, req_id, acct, tag, val, currency):
? ? ? ? ''' Called in response to reqAccountSummary '''
?
? ? ? ? if tag == 'AvailableFunds':
? ? ? ? ? ? print('Account {}: available funds = {}'.format(acct, val))
? ? ? ? ? ? self.funds = float(val)
But I'm having trouble bringing that into my bot class which is below:
class Bot:
? ? ib = None
? ? reqId = 1
? ? SLOW_PERIOD = 30
? ? FAST_PERIOD = 6
? ? global orderId
? ? initialbartime = datetime.datetime.now().astimezone(pytz.timezone("America/New_York"))
? ? def __init__(self):
? ? ? ? #Connect to IB on init
? ? ? ? self.ib = IBApi()
? ? ? ? self.ib.connect("127.0.0.1", 7497,1)
? ? ? ? ib_thread = threading.Thread(target=self.run_loop, daemon=True)
? ? ? ? ib_thread.start()
? ? ? ? self.funds = self.funds
?
? ? ? ? self.low = collections.deque(maxlen=SLOW_PERIOD)
? ? ? ? self.high = collections.deque(maxlen=SLOW_PERIOD)
? ? ? ? self.close = collections.deque(maxlen=SLOW_PERIOD)
? ? ? ? self.long_ema = collections.deque(maxlen=SLOW_PERIOD)
? ? ? ? self.short_ema = collections.deque(maxlen=FAST_PERIOD)
? ? ? ? self.nmc = 0
? ? ? ??
? ? ? ? #Create our IB Contract Object
? ? ? ? contract = Contract()
? ? ? ? contract.symbol = "ES"
? ? ? ? contract.secType = "FUT"
? ? ? ? contract.exchange = "GLOBEX"
? ? ? ? contract.currency = "USD"
? ? ? ? contract.lastTradeDateOrContractMonth = "202109"
? ? ? ? self.ib.reqIds(-1)
?
? ? ? ? self.ib.reqHistoricalData(self.reqId,contract,"","5 D","5 mins","TRADES",0,1,True,[])
? ? ? ? # self.ib.reqPositions(self.reqId)
? ? ? ? # print(self.pos)
? ? #Listen to socket in seperate thread
? ? def run_loop(self):
? ? ? ? self.ib.run()
?
? ? #Bracet Order Setup
? ? def bracketOrder(self, parentOrderId, action, quantity, profitTarget, stopLoss):
? ? ? ? #Initial Entry? ? ? ??
? ? ? ? # Create Parent Order / Initial Entry
? ? ? ? parent = Order()
? ? ? ? parent.orderId = parentOrderId
? ? ? ? parent.orderType = "MKT"
? ? ? ? parent.action = action
? ? ? ? parent.totalQuantity = quantity
? ? ? ? parent.transmit = False
? ? ? ? # Profit Target
? ? ? ? profitTargetOrder = Order()
? ? ? ? profitTargetOrder.orderId = parent.orderId+1
? ? ? ? profitTargetOrder.orderType = "LMT"
? ? ? ? profitTargetOrder.action = "SELL" if action == "BUY" else "BUY"
? ? ? ? profitTargetOrder.totalQuantity = quantity
? ? ? ? profitTargetOrder.lmtPrice = profitTarget
? ? ? ? profitTargetOrder.parentId = parentOrderId
? ? ? ? profitTargetOrder.transmit = False
? ? ? ? # Stop Loss
? ? ? ? stopLossOrder = Order()
? ? ? ? stopLossOrder.orderId = parent.orderId+2
? ? ? ? stopLossOrder.orderType = "STP"
? ? ? ? stopLossOrder.action = "SELL" if action == "BUY" else "BUY"
? ? ? ? stopLossOrder.totalQuantity = quantity
? ? ? ? stopLossOrder.parentId = parentOrderId
? ? ? ? stopLossOrder.auxPrice = stopLoss
? ? ? ? stopLossOrder.transmit = True
?
? ? ? ? bracketOrders = [parent, profitTargetOrder, stopLossOrder]
? ? ? ??
? ? ? ? return bracketOrders
? ??
? ? #Pass realtime bar data back to our bot object
? ? def on_bar_update(self, reqId, bar,realtime):
? ? ? ? global orderId
? ? ? ? global position_
? ? ? ? # if self.pos > 0:
? ? ? ? #? ? ?print("{} Position/s on in {}.".format(self.pos, contract.symbol))
? ? ? ? # else:
? ? ? ? #append values
? ? ? ? self.low.append(bar.close)
? ? ? ? self.high.append(bar.high)
? ? ? ? self.close.append(bar.close)
? ? ? ? self.long_ema.append(bar.close)
? ? ? ? self.short_ema.append(bar.close)
? ? ? ??
? ? ? ? #check time for market hours (regular)
? ? ? ? now = datetime.datetime.now()
? ? ? ? if (now.time() < datetime.time(9,30) or now.time() > datetime.time(16,00)):
? ? ? ? ? ? print("Regular Market Hours Not Open")
? ? ? ? else:
? ? ? ? ? ? ? ? ? ? ? ??
? ? ? ? ? ? ? ? self.preds = (self.diff_rsi*4.977e-05)+(self.nmc*3.785e-05)
? ? ? ? ? ? ? ??
? ? ? ? ? ? ? ? print("Prediction : {}. Position is {}".format(self.preds, position_))
? ??
? ? ? ? ? ? ? ? ? ? # Check Criteria
? ? ? ? ? ? ? ? if (self.preds >= -0.000411116078039124
? ? ) and (position_ == 'out'):
? ? ? ? ? ? ? ? ? ? #Bracket Order 4% Profit Target 1% Stop Loss
? ? ? ? ? ? ? ? ? ? profitTarget_ = round(((bar.close*1.04)*4)/4)
? ? ? ? ? ? ? ? ? ? stopLoss_ = round(((bar.close*.99)*4)/4)
? ? ? ? ? ? ? ? ? ? quantity_ = 1
? ? ? ? ? ? ? ? ? ? bracket = self.bracketOrder(orderId,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? action ="BUY",quantity=quantity_,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? profitTarget=profitTarget_,?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? stopLoss = stopLoss_)
? ? ? ? ? ? ? ? ? ? contract = Contract()
? ? ? ? ? ? ? ? ? ? contract.symbol = "ES"
? ? ? ? ? ? ? ? ? ? contract.secType = "FUT"
? ? ? ? ? ? ? ? ? ? contract.exchange = "GLOBEX"
? ? ? ? ? ? ? ? ? ? contract.currency = "USD"
? ? ? ? ? ? ? ? ? ? contract.lastTradeDateOrContractMonth = "202109"
?
? ? ? ? ? ? ? ? ? ? # Place Bracket Order
? ? ? ? ? ? ? ? ? ? for o in bracket:
? ? ? ? ? ? ? ? ? ? ? ? # o.ocaGroup = "OCA_"+str(orderId)
? ? ? ? ? ? ? ? ? ? ? ? self.ib.placeOrder(o.orderId,contract,o)
? ? ? ? ? ? ? ? ? ? ? ? print(o.orderId)
? ? ? ? ? ? ? ? ? ? ? ? # self.nextorderId()
? ? ? ? ? ? ? ? ? ? orderId += 3
? ? ? ? ? ? ? ? ? ? position_ = "long"
? ? ? ? ? ? ? ? ? ? print(position_, "Order placed on IDs", orderId)
?
? ? ? ? ? ? ? ? ? ??
? ? ? ? ? ? ? ? elif (self.preds <= -0.000889676
? ? ) and position_ == 'out':
? ? ? ? ? ? ? ? ? ? # Bracket Order 4% Profit Target 1% Stop Loss
? ? ? ? ? ? ? ? ? ? profitTarget_ = round(((price*.96)*4)/4)
? ? ? ? ? ? ? ? ? ? stopLoss_ = round((bar.close*1.02)*4)/4
? ? ? ? ? ? ? ? ? ? quantity_ = 1
? ? ? ? ? ? ? ? ? ? bracket_s = self.bracketOrder(orderId,action = "SELL",?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? quantity=quantity_,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? profitTarget=profitTarget_,?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? stopLoss = stopLoss_ )
? ? ? ? ? ? ? ? ? ? contract = Contract()
? ? ? ? ? ? ? ? ? ? contract.symbol = "ES"
? ? ? ? ? ? ? ? ? ? contract.secType = "FUT"
? ? ? ? ? ? ? ? ? ? contract.exchange = "GLOBEX"
? ? ? ? ? ? ? ? ? ? contract.currency = "USD"
? ? ? ? ? ? ? ? ? ? contract.lastTradeDateOrContractMonth = "202109"
? ? ??
? ? ? ? ? ? ? ? ? ? for o in bracket_s:
? ? ? ? ? ? ? ? ? ? ? ? print(o.orderId)
? ? ? ? ? ? ? ? ? ? ? ? self.ib.placeOrder(o.orderId,contract,o)
? ? ? ? ? ? ? ? ? ? ? ? print(o.orderId)
? ? ? ? ? ? ? ? ? ? orderId += 3
? ? ? ? ? ? ? ? ? ? position_ = "Short"
? ? ? ? ? ? ? ? ? ? print(position_, "Order placed on IDs", orderId)
?
#Start Bot
bot = Bot()
?
|
Re: How can I pull my account value in as an object to help calculate my contract quantity size?
Understood. There¡¯s not much out there on the stack-threads. I¡¯ll keep looking. ?Thanks JR.?
|
Re: Get Parent Order ID of Child Order AFTER parent order is filled
Exactly, once the parent order is filled, you can no longer add
extra child orders to that parent id, even if other child orders
with that same parent id still exist. So in that case, you need to
know the original oca group id and create orders in that group.
On 13-07-2021 15:43, rajeshh_98 via
groups.io wrote:
toggle quoted message
Show quoted text
or after the parent order is triggered.?
I was trying to do something like this - I wanted to read back
open bracket orders ( parent and child), or the child orders if
parent had filled. I dont remember the specific details, but I
recall that once a parent order is filled, I could not find the
parent order at least across restarts. I think I was starting with
ib.trades() [ am using the in_sync library].?
|
Re: Get Parent Order ID of Child Order AFTER parent order is filled
Hi Everyone. Thanks for the help.
Just wanted to update. I am just using the order IDs of all the indivual trade in the bracket order and managing the life of the trade.
|
Re: historical data doesn't include 16:00
Options usually stop trading at 4Pm so there is no 16:00 bar. The 15:30 bar goes from 15:30 to 15:59:59.
toggle quoted message
Show quoted text
On 7/23/2021 6:40 PM, ebtrader wrote: when i run historical data on options using the script below, it does not include pricing for 16:00 (close).? anyone figure out a way to include that?
|
historical data doesn't include 16:00
when i run historical data on options using the script below, it does not include pricing for 16:00 (close).? anyone figure out a way to include that?
import logging
import time
import pandas as pd
from ibapi.utils import iswrapper
from ContractSamples import ContractSamples
from ibapi.client import EClient from ibapi.wrapper import EWrapper # types from ibapi.common import * # @UnusedWildImport from ibapi.contract import * # @UnusedWildImport
class TestApp(EWrapper, EClient): def __init__(self): EWrapper.__init__(self) EClient.__init__(self, wrapper=self) # ! [socket_init] self.nKeybInt = 0 self.started = False self.nextValidOrderId = None self.permId2ord = {} self.globalCancelOnly = False self.simplePlaceOid = None self._my_errors = {} self.data = [] # Initialize variable to store candle self.contract = Contract() self.i = 0 self.df = pd.DataFrame()
@iswrapper # ! [connectack] def connectAck(self): if self.asynchronous: self.startApi()
# ! [connectack]
@iswrapper # ! [nextvalidid] def nextValidId(self, orderId: int): super().nextValidId(orderId)
logging.debug("setting nextValidOrderId: %d", orderId) self.nextValidOrderId = orderId print("NextValidId:", orderId) # ! [nextvalidid]
# we can start now self.start()
def start(self): if self.started: return
self.started = True
if self.globalCancelOnly: print("Executing GlobalCancel only") self.reqGlobalCancel() else: print("Executing requests") # self.tickDataOperations_req() self.historicalDataOperations_req() print("Executing requests ... finished")
def keyboardInterrupt(self): self.nKeybInt += 1 if self.nKeybInt == 1: self.stop() else: print("Finishing test") self.done = True
def stop(self): print("Executing cancels") self.tickByTickOperations_cancel()
print("Executing cancels ... finished")
def nextOrderId(self): oid = self.nextValidOrderId self.nextValidOrderId += 1 return oid
@iswrapper # ! [error] def error(self, reqId: TickerId, errorCode: int, errorString: str): super().error(reqId, errorCode, errorString) print("Error. Id:", reqId, "Code:", errorCode, "Msg:", errorString) errormsg = "IB error id %d errorcode %d string %s" % (reqId, errorCode, errorString) self._my_errors = errormsg
@iswrapper def winError(self, text: str, lastError: int): super().winError(text, lastError)
# @printWhenExecuting # def historicalTicksOperations(self): # # ! [reqhistoricalticks] # # self.reqHistoricalTicks(18001, ContractSamples.USOptionContract(), # '20210722 09:39:33', "", 50, "TRADES", 1, True, []) #
def historicalDataOperations_req(self):
chain = [128, 129, 130] for self.i in chain: self.contract.symbol = "TQQQ" self.contract.secType = "OPT" self.contract.exchange = "SMART" self.contract.currency = "USD" self.contract.lastTradeDateOrContractMonth = "20210723" self.contract.strike = self.i self.contract.right = "C" self.contract.multiplier = "100" self.reqHistoricalData(4103, self.contract, '', "2 D", "30 mins", "MIDPOINT", 1, 1, False, [])
# https://interactivebrokers.github.io/tws-api/historical_bars.html
def historicalData(self, reqId: int, bar: BarData): self.data.append([bar]) # print("HistoricalData. ReqId:", reqId, "BarData.", bar) self.df = pd.DataFrame(self.data) print(self.df) self.df.to_csv('history.csv')
def main():
app = TestApp() try:
# ! [connect] app.connect("127.0.0.1", port=7497, clientId=102) # ! [connect] print("serverVersion:%s connectionTime:%s" % (app.serverVersion(), app.twsConnectionTime())) # ! [clientrun] app.run() # ! [clientrun] except: raise
if __name__ == "__main__": main()
|
Re: How can I pull my account value in as an object to help calculate my contract quantity size?
Well, that's probably a question for a Python support forum since it is not related to the TWS API.
Alternatively, you could check the sample Python code that comes with the IB API. Maybe there is something of use tehre.
|
Re: How can I pull my account value in as an object to help calculate my contract quantity size?
Thanks.? I did read the account summary portion.? I only see where it shows to print the summary returned messages.? I am confused on how to store it as an object.
|
Re: How can I pull my account value in as an object to help calculate my contract quantity size?
Why don't you re-read the section of the API documentation? That tells you about the account related functions the API provides.
JR
|
Re: Limitations on data requests. Requesting 120 options in option chain.
There is a hotkeys Ctrl Alt = to see market data lines, as noted here
It works both in TWS and in IB Gateway.
|
How can I pull my account value in as an object to help calculate my contract quantity size?
Using python, how can I pull in my account size as a value to help calc the quantity of my contract size?? ?For instance, if I have a $50K account and I want to only risk 5% on any trade, I would like to do something like:?
quantity = np.floor(account value/contract price)??
Currently in my api class, I have:
class IBApi(EWrapper,EClient):
? ? def __init__(self):
? ? ? ? EClient.__init__(self, self)
? ? ? ? self.funds = 0.0
?
? ? # Historical Backtest Data
? ? def historicalData(self, reqId, bar):
? ? ? ? try:
? ? ? ? ? ? bot.on_bar_update(reqId,bar,False)
? ? ? ? except Exception as e:
? ? ? ? ? ? print(e)
? ? # On Realtime Bar after historical data finishes
? ? def historicalDataUpdate(self, reqId, bar):
? ? ? ? try:
? ? ? ? ? ? bot.on_bar_update(reqId,bar,True)
? ? ? ? except Exception as e:
? ? ? ? ? ? print(e)
? ? # On Historical Data End
? ? def historicalDataEnd(self, reqId, start, end):
? ? ? ? print(reqId)
?
? ? def nextValidId(self, nextorderId):
? ? ? ? global orderId
? ? ? ? orderId = nextorderId
? ? ??
? ? def error(self, id, errorCode, errorMsg):
? ? ? ? print(errorCode)
? ? ? ? print(errorMsg)
? ? ? ??
? ? @iswrapper
? ? def accountSummary(self, req_id, acct, tag, val, currency):
? ? ? ? ''' Called in response to reqAccountSummary '''
?
? ? ? ? if tag == 'AvailableFunds':
? ? ? ? ? ? print('Account {}: available funds = {}'.format(acct, val))
? ? ? ? ? ? self.funds = float(val)
But I'm having trouble bringing that into my bot class which is below:
class Bot:
? ? ib = None
? ? reqId = 1
? ? SLOW_PERIOD = 30
? ? FAST_PERIOD = 6
? ? global orderId
? ? initialbartime = datetime.datetime.now().astimezone(pytz.timezone("America/New_York"))
? ? def __init__(self):
? ? ? ? #Connect to IB on init
? ? ? ? self.ib = IBApi()
? ? ? ? self.ib.connect("127.0.0.1", 7497,1)
? ? ? ? ib_thread = threading.Thread(target=self.run_loop, daemon=True)
? ? ? ? ib_thread.start()
? ? ? ? self.funds = self.funds
?
? ? ? ? self.low = collections.deque(maxlen=SLOW_PERIOD)
? ? ? ? self.high = collections.deque(maxlen=SLOW_PERIOD)
? ? ? ? self.close = collections.deque(maxlen=SLOW_PERIOD)
? ? ? ? self.long_ema = collections.deque(maxlen=SLOW_PERIOD)
? ? ? ? self.short_ema = collections.deque(maxlen=FAST_PERIOD)
? ? ? ? self.nmc = 0
? ? ? ??
? ? ? ? #Create our IB Contract Object
? ? ? ? contract = Contract()
? ? ? ? contract.symbol = "ES"
? ? ? ? contract.secType = "FUT"
? ? ? ? contract.exchange = "GLOBEX"
? ? ? ? contract.currency = "USD"
? ? ? ? contract.lastTradeDateOrContractMonth = "202109"
? ? ? ? self.ib.reqIds(-1)
?
? ? ? ? self.ib.reqHistoricalData(self.reqId,contract,"","5 D","5 mins","TRADES",0,1,True,[])
? ? ? ? # self.ib.reqPositions(self.reqId)
? ? ? ? # print(self.pos)
? ? #Listen to socket in seperate thread
? ? def run_loop(self):
? ? ? ? self.ib.run()
?
? ? #Bracet Order Setup
? ? def bracketOrder(self, parentOrderId, action, quantity, profitTarget, stopLoss):
? ? ? ? #Initial Entry? ? ? ??
? ? ? ? # Create Parent Order / Initial Entry
? ? ? ? parent = Order()
? ? ? ? parent.orderId = parentOrderId
? ? ? ? parent.orderType = "MKT"
? ? ? ? parent.action = action
? ? ? ? parent.totalQuantity = quantity
? ? ? ? parent.transmit = False
? ? ? ? # Profit Target
? ? ? ? profitTargetOrder = Order()
? ? ? ? profitTargetOrder.orderId = parent.orderId+1
? ? ? ? profitTargetOrder.orderType = "LMT"
? ? ? ? profitTargetOrder.action = "SELL" if action == "BUY" else "BUY"
? ? ? ? profitTargetOrder.totalQuantity = quantity
? ? ? ? profitTargetOrder.lmtPrice = profitTarget
? ? ? ? profitTargetOrder.parentId = parentOrderId
? ? ? ? profitTargetOrder.transmit = False
? ? ? ? # Stop Loss
? ? ? ? stopLossOrder = Order()
? ? ? ? stopLossOrder.orderId = parent.orderId+2
? ? ? ? stopLossOrder.orderType = "STP"
? ? ? ? stopLossOrder.action = "SELL" if action == "BUY" else "BUY"
? ? ? ? stopLossOrder.totalQuantity = quantity
? ? ? ? stopLossOrder.parentId = parentOrderId
? ? ? ? stopLossOrder.auxPrice = stopLoss
? ? ? ? stopLossOrder.transmit = True
?
? ? ? ? bracketOrders = [parent, profitTargetOrder, stopLossOrder]
? ? ? ??
? ? ? ? return bracketOrders
? ??
? ? #Pass realtime bar data back to our bot object
? ? def on_bar_update(self, reqId, bar,realtime):
? ? ? ? global orderId
? ? ? ? global position_
? ? ? ? # if self.pos > 0:
? ? ? ? #? ? ?print("{} Position/s on in {}.".format(self.pos, contract.symbol))
? ? ? ? # else:
? ? ? ? #append values
? ? ? ? self.low.append(bar.close)
? ? ? ? self.high.append(bar.high)
? ? ? ? self.close.append(bar.close)
? ? ? ? self.long_ema.append(bar.close)
? ? ? ? self.short_ema.append(bar.close)
? ? ? ??
? ? ? ? #check time for market hours (regular)
? ? ? ? now = datetime.datetime.now()
? ? ? ? if (now.time() < datetime.time(9,30) or now.time() > datetime.time(16,00)):
? ? ? ? ? ? print("Regular Market Hours Not Open")
? ? ? ? else:
? ? ? ? ? ? ? ? ? ? ? ??
? ? ? ? ? ? ? ? self.preds = (self.diff_rsi*4.977e-05)+(self.nmc*3.785e-05)
? ? ? ? ? ? ? ??
? ? ? ? ? ? ? ? print("Prediction : {}. Position is {}".format(self.preds, position_))
? ??
? ? ? ? ? ? ? ? ? ? # Check Criteria
? ? ? ? ? ? ? ? if (self.preds >= -0.000411116078039124
? ? ) and (position_ == 'out'):
? ? ? ? ? ? ? ? ? ? #Bracket Order 4% Profit Target 1% Stop Loss
? ? ? ? ? ? ? ? ? ? profitTarget_ = round(((bar.close*1.04)*4)/4)
? ? ? ? ? ? ? ? ? ? stopLoss_ = round(((bar.close*.99)*4)/4)
? ? ? ? ? ? ? ? ? ? quantity_ = 1
? ? ? ? ? ? ? ? ? ? bracket = self.bracketOrder(orderId,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? action ="BUY",quantity=quantity_,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? profitTarget=profitTarget_,?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? stopLoss = stopLoss_)
? ? ? ? ? ? ? ? ? ? contract = Contract()
? ? ? ? ? ? ? ? ? ? contract.symbol = "ES"
? ? ? ? ? ? ? ? ? ? contract.secType = "FUT"
? ? ? ? ? ? ? ? ? ? contract.exchange = "GLOBEX"
? ? ? ? ? ? ? ? ? ? contract.currency = "USD"
? ? ? ? ? ? ? ? ? ? contract.lastTradeDateOrContractMonth = "202109"
?
? ? ? ? ? ? ? ? ? ? # Place Bracket Order
? ? ? ? ? ? ? ? ? ? for o in bracket:
? ? ? ? ? ? ? ? ? ? ? ? # o.ocaGroup = "OCA_"+str(orderId)
? ? ? ? ? ? ? ? ? ? ? ? self.ib.placeOrder(o.orderId,contract,o)
? ? ? ? ? ? ? ? ? ? ? ? print(o.orderId)
? ? ? ? ? ? ? ? ? ? ? ? # self.nextorderId()
? ? ? ? ? ? ? ? ? ? orderId += 3
? ? ? ? ? ? ? ? ? ? position_ = "long"
? ? ? ? ? ? ? ? ? ? print(position_, "Order placed on IDs", orderId)
?
? ? ? ? ? ? ? ? ? ??
? ? ? ? ? ? ? ? elif (self.preds <= -0.000889676
? ? ) and position_ == 'out':
? ? ? ? ? ? ? ? ? ? # Bracket Order 4% Profit Target 1% Stop Loss
? ? ? ? ? ? ? ? ? ? profitTarget_ = round(((price*.96)*4)/4)
? ? ? ? ? ? ? ? ? ? stopLoss_ = round((bar.close*1.02)*4)/4
? ? ? ? ? ? ? ? ? ? quantity_ = 1
? ? ? ? ? ? ? ? ? ? bracket_s = self.bracketOrder(orderId,action = "SELL",?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? quantity=quantity_,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? profitTarget=profitTarget_,?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? stopLoss = stopLoss_ )
? ? ? ? ? ? ? ? ? ? contract = Contract()
? ? ? ? ? ? ? ? ? ? contract.symbol = "ES"
? ? ? ? ? ? ? ? ? ? contract.secType = "FUT"
? ? ? ? ? ? ? ? ? ? contract.exchange = "GLOBEX"
? ? ? ? ? ? ? ? ? ? contract.currency = "USD"
? ? ? ? ? ? ? ? ? ? contract.lastTradeDateOrContractMonth = "202109"
? ? ??
? ? ? ? ? ? ? ? ? ? for o in bracket_s:
? ? ? ? ? ? ? ? ? ? ? ? print(o.orderId)
? ? ? ? ? ? ? ? ? ? ? ? self.ib.placeOrder(o.orderId,contract,o)
? ? ? ? ? ? ? ? ? ? ? ? print(o.orderId)
? ? ? ? ? ? ? ? ? ? orderId += 3
? ? ? ? ? ? ? ? ? ? position_ = "Short"
? ? ? ? ? ? ? ? ? ? print(position_, "Order placed on IDs", orderId)
?
#Start Bot
bot = Bot()
?
|
Re: Limitations on data requests. Requesting 120 options in option chain.
Did you find this page, which explains the limitations at the bottom of the page:? https://interactivebrokers.github.io/tws-api/market_data.html Read the section titled "Market Data Lines"
|
Re: Historical options pricing
Last time I checked, expired options were not available for historical data requests and only intraday historical data was available (daily data was not available). Hope that helps.
--
|
Re: Historical options pricing
The Contract class has the IncludeExpired field. However, the explaining text mentions: "If set to true, contract details requests and historical data queries can be performed pertaining to expired futures contracts. Expired options or other instrument types are not available. " So, in your case, the answer is unfortunately no: historical data for expired option contracts is not available. Historical data is available for currently traded option contracts.
|
Re: How to save Stop loss order fills
Oh yeah, that's what I meant, thanks Sandro!
Please I wrote another thread regarding execution Filter, could you check that message please? I want to know how to use well the ExecutionFilter,
Thanks!
|