¿ªÔÆÌåÓý

ctrl + shift + ? for shortcuts
© 2025 Groups.io

How can I pull my account value in as an object to help calculate my contract quantity size?


Jordan
 

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()

?


 

Why don't you re-read the section of the API documentation? That tells you about the account related functions the API provides.

JR


Jordan
 

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.


 

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.


Jordan
 

Understood. There¡¯s not much out there on the stack-threads. I¡¯ll keep looking. ?Thanks JR.?


 

Use the value variable here:


Email me direct and I can take a crack at it for you.

Regards,

Javed

On Fri, Jul 23, 2021 at 12:32 PM Jordan <jordan.howell2@...> wrote:
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()

?


 

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()

On Sat, Jul 24, 2021 at 7:41 AM ebtrader via <jsiddique=[email protected]> wrote:
Use the value variable here:


Email me direct and I can take a crack at it for you.

Regards,

Javed

On Fri, Jul 23, 2021 at 12:32 PM Jordan <jordan.howell2@...> wrote:
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()

?


 

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()

On Sat, Jul 24, 2021 at 8:25 AM ebtrader via <jsiddique=[email protected]> wrote:
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()

On Sat, Jul 24, 2021 at 7:41 AM ebtrader via <jsiddique=[email protected]> wrote:
Use the value variable here:


Email me direct and I can take a crack at it for you.

Regards,

Javed

On Fri, Jul 23, 2021 at 12:32 PM Jordan <jordan.howell2@...> wrote:
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()

?


 

Maybe you are looking for something like this:?i

There is a code to get positions and NAVs for your account(s)


 


?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)?

simply by avoiding using python-

Using ib-ruby? you would end with this (using the gateway framework)
()
u= G.clients.first
five_percent = u.account_data_scan( /NetLiquidation$/).value.first.to_f / 5
stock =? IB::Stock.new symbol: 'TSLA'
market_price = stock.market_price
u.place contract: stock, order: Limit.order( size: (five_percent / market_price).to_i , price: (market_price - 10).round(2), action: :buy)

simple, but effective.
No spaghetti code anymore, it simply works.

hartmut


 

Hi,

Thanks for the nice solution that you have provided. Yes, whenever I executed NAVs - it provided me a result like this:

Testing IB's API as an imported library:
Waiting for IB's API response for accounts positions requests...

Empty DataFrame
Columns: [Symbol, Quantity, Average Cost, Sec Type]
Index: []

Waiting for IB's API response for NAVs requests...

? ? ? ? ? ?reqId? ? Account? ? ? ? ? ? ?Tag? ? ?Value Currency
DUXX70XXX? ? ? 0? DUXX70XXX? TotalCashValue? 5000.04? ? ? USD

But what if I request more than one Value with the reqAccountSummary() - is there any way that I can capture all of the values? Such as (NetLiquidation, TotalCashValue, etc., etc.)

app.reqAccountSummary(
? ? ? ? 0, "All", "NetLiquidation, TotalCashValue"
? ? )

Regards,
Julius



On Sun, Jul 25, 2021 at 5:08 AM Rational-IM <ds@...> wrote:
Maybe you are looking for something like this:?i

There is a code to get positions and NAVs for your account(s)