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