class OrderCondition(Object):
class ExecutionCondition(OrderCondition):
class OperatorCondition(OrderCondition):
class MarginCondition(OperatorCondition):
class ContractCondition(OperatorCondition):
class TimeCondition(OperatorCondition):
class PriceCondition(ContractCondition):
class PercentChangeCondition(ContractCondition):
class VolumeCondition(ContractCondition):
    def __init__(self, condType):
    def type(self):
    def And(self):
    def Or(self):
    def decode(self, fields):
    def make_fields(self):
    def __str__(self):
    def __init__(self, secType=None, exch=None, symbol=None):
    def decode(self, fields):
    def make_fields(self):
    def __str__(self):
    def __init__(self, condType=None, isMore=None):
    def valueToString(self) -> str:
    def setValueFromString(self, text: str) -> None:
    def decode(self, fields):
    def make_fields(self):
    def __str__(self):
    def __init__(self, isMore=None, percent=None):
    def decode(self, fields):
    def make_fields(self):
    def valueToString(self) -> str:
    def setValueFromString(self, text: str) -> None:
    def __str__(self):
    def __init__(self, condType=None, conId=None, exch=None, isMore=None):
    def decode(self, fields):
    def make_fields(self):
    def __str__(self):
    def __init__(self, isMore=None, time=None):
    def decode(self, fields):
    def make_fields(self):
    def valueToString(self) -> str:
    def setValueFromString(self, text: str) -> None:
    def __str__(self):
    def __init__(self, triggerMethod=None, conId=None, exch=None, isMore=None, 
                 price=None):
    def decode(self, fields):
    def make_fields(self):
    def valueToString(self) -> str:
    def setValueFromString(self, text: str) -> None:
    def __str__(self):
    def __init__(self, conId=None, exch=None, isMore=None,
                 changePercent=UNSET_DOUBLE):
    def decode(self, fields):
    def make_fields(self):
    def valueToString(self) -> str:
    def setValueFromString(self, text: str) -> None:
    def __str__(self):
    def __init__(self, conId=None, exch=None, isMore=None, volume=None):
    def decode(self, fields):
    def make_fields(self):
    def valueToString(self) -> str:
    def setValueFromString(self, text: str) -> None:
    def __str__(self):
def Create(condType): class IN:
    TICK_PRICE                = 1
    TICK_SIZE                 = 2
    ORDER_STATUS              = 3
    ERR_MSG                   = 4
    OPEN_ORDER                = 5
    ACCT_VALUE                = 6
    PORTFOLIO_VALUE           = 7
    ACCT_UPDATE_TIME          = 8
    NEXT_VALID_ID             = 9
    CONTRACT_DATA             = 10
    EXECUTION_DATA            = 11
    MARKET_DEPTH              = 12
    MARKET_DEPTH_L2           = 13
    NEWS_BULLETINS            = 14
    MANAGED_ACCTS             = 15
    RECEIVE_FA                = 16
    HISTORICAL_DATA           = 17
    BOND_CONTRACT_DATA        = 18
    SCANNER_PARAMETERS        = 19
    SCANNER_DATA              = 20
    TICK_OPTION_COMPUTATION   = 21
    TICK_GENERIC              = 45
    TICK_STRING               = 46
    TICK_EFP                  = 47
    CURRENT_TIME              = 49
    REAL_TIME_BARS            = 50
    FUNDAMENTAL_DATA          = 51
    CONTRACT_DATA_END         = 52
    OPEN_ORDER_END            = 53
    ACCT_DOWNLOAD_END         = 54
    EXECUTION_DATA_END        = 55
    DELTA_NEUTRAL_VALIDATION  = 56
    TICK_SNAPSHOT_END         = 57
    MARKET_DATA_TYPE          = 58
    COMMISSION_REPORT         = 59
    POSITION_DATA             = 61
    POSITION_END              = 62
    ACCOUNT_SUMMARY           = 63
    ACCOUNT_SUMMARY_END       = 64
    VERIFY_MESSAGE_API        = 65
    VERIFY_COMPLETED          = 66
    DISPLAY_GROUP_LIST        = 67
    DISPLAY_GROUP_UPDATED     = 68
    VERIFY_AND_AUTH_MESSAGE_API = 69
    VERIFY_AND_AUTH_COMPLETED   = 70
    POSITION_MULTI            = 71
    POSITION_MULTI_END        = 72
    ACCOUNT_UPDATE_MULTI      = 73
    ACCOUNT_UPDATE_MULTI_END  = 74
    SECURITY_DEFINITION_OPTION_PARAMETER = 75
    SECURITY_DEFINITION_OPTION_PARAMETER_END = 76
    SOFT_DOLLAR_TIERS         = 77
    FAMILY_CODES              = 78
    SYMBOL_SAMPLES            = 79
    MKT_DEPTH_EXCHANGES       = 80
    TICK_REQ_PARAMS           = 81
    SMART_COMPONENTS          = 82
    NEWS_ARTICLE              = 83
    TICK_NEWS                 = 84
    NEWS_PROVIDERS            = 85
    HISTORICAL_NEWS           = 86
    HISTORICAL_NEWS_END       = 87
    HEAD_TIMESTAMP            = 88
    HISTOGRAM_DATA            = 89
    HISTORICAL_DATA_UPDATE    = 90
    REROUTE_MKT_DATA_REQ      = 91
    REROUTE_MKT_DEPTH_REQ     = 92
    MARKET_RULE               = 93
    PNL                       = 94
    PNL_SINGLE                = 95
    HISTORICAL_TICKS          = 96
    HISTORICAL_TICKS_BID_ASK  = 97
    HISTORICAL_TICKS_LAST     = 98
    TICK_BY_TICK              = 99 class Order(Object):
    def __init__(self):
        self.softDollarTier = SoftDollarTier("", "", "")
        # order identifier
        self.orderId  = 0
        self.clientId = 0
        self.permId   = 0

        # main order fields
        self.action = ""
        self.totalQuantity = 0
        self.orderType = ""
        self.lmtPrice      = UNSET_DOUBLE
        self.auxPrice      = UNSET_DOUBLE

        # extended order fields
        self.tif = ""                # "Time in Force" - DAY, GTC, etc.
        self.activeStartTime = ""   # for GTC orders
        self.activeStopTime = ""    # for GTC orders
        self.ocaGroup = ""          # one cancels all group name
        self.ocaType        = 0     # 1 = CANCEL_WITH_BLOCK, 2 = REDUCE_WITH_BLOCK, 3 = REDUCE_NON_BLOCK
        self.orderRef       = ""
        self.transmit       = True  # if false, order will be created but not transmited
        self.parentId       = 0     # Parent order Id, to associate Auto STP or TRAIL orders with the original order.
        self.blockOrder     = False
        self.sweepToFill    = False
        self.displaySize    = 0
        self.triggerMethod  = 0     # 0=Default, 1=Double_Bid_Ask, 2=Last, 3=Double_Last, 4=Bid_Ask, 7=Last_or_Bid_Ask, 8=Mid-point
        self.outsideRth     = False
        self.hidden         = False
        self.goodAfterTime       = ""   # Format: 20060505 08:00:00 {time zone}
        self.goodTillDate        = ""   # Format: 20060505 08:00:00 {time zone}
        self.rule80A             = ""   # Individual = 'I', Agency = 'A', AgentOtherMember = 'W', IndividualPTIA = 'J', AgencyPTIA = 'U', AgentOtherMemberPTIA = 'M', IndividualPT = 'K', AgencyPT = 'Y', AgentOtherMemberPT = 'N'
        self.allOrNone      = False
        self.minQty         = UNSET_INTEGER  #type: int
        self.percentOffset  = UNSET_DOUBLE  # type: float; REL orders only
        self.overridePercentageConstraints = False
        self.trailStopPrice = UNSET_DOUBLE  # type: float
        self.trailingPercent = UNSET_DOUBLE # type: float; TRAILLIMIT orders only

        # financial advisors only
        self.faGroup              = ""
        self.faProfile            = ""
        self.faMethod             = ""
        self.faPercentage         = ""

        # institutional (ie non-cleared) only
        self.designatedLocation = "" #used only when shortSaleSlot=2
        self.openClose     = "O"    # O=Open, C=Close
        self.origin        = CUSTOMER  # 0=Customer, 1=Firm
        self.shortSaleSlot = 0    # type: int; 1 if you hold the shares, 2 if they will be delivered from elsewhere.  Only for Action=SSHORT
        self.exemptCode    = -1

        # SMART routing only
        self.discretionaryAmt = 0
        self.eTradeOnly       = True
        self.firmQuoteOnly    = True
        self.nbboPriceCap     = UNSET_DOUBLE  # type: float
        self.optOutSmartRouting = False

        # BOX exchange orders only
        self.auctionStrategy = AUCTION_UNSET # type: int; AUCTION_MATCH, AUCTION_IMPROVEMENT, AUCTION_TRANSPARENT
        self.startingPrice   = UNSET_DOUBLE   # type: float
        self.stockRefPrice   = UNSET_DOUBLE   # type: float
        self.delta           = UNSET_DOUBLE   # type: float

        # pegged to stock and VOL orders only
        self.stockRangeLower = UNSET_DOUBLE   # type: float
        self.stockRangeUpper = UNSET_DOUBLE   # type: float

        self.randomizePrice = False
        self.randomizeSize = False

        # VOLATILITY ORDERS ONLY
        self.volatility            = UNSET_DOUBLE  # type: float
        self.volatilityType        = UNSET_INTEGER  # type: int   # 1=daily, 2=annual
        self.deltaNeutralOrderType = ""
        self.deltaNeutralAuxPrice  = UNSET_DOUBLE  # type: float
        self.deltaNeutralConId     = 0
        self.deltaNeutralSettlingFirm = ""
        self.deltaNeutralClearingAccount = ""
        self.deltaNeutralClearingIntent = ""
        self.deltaNeutralOpenClose = ""
        self.deltaNeutralShortSale = False
        self.deltaNeutralShortSaleSlot = 0
        self.deltaNeutralDesignatedLocation = ""
        self.continuousUpdate      = False
        self.referencePriceType    = UNSET_INTEGER  # type: int; 1=Average, 2 = BidOrAsk

        # COMBO ORDERS ONLY
        self.basisPoints     = UNSET_DOUBLE  # type: float; EFP orders only
        self.basisPointsType = UNSET_INTEGER  # type: int;  EFP orders only

        # SCALE ORDERS ONLY
        self.scaleInitLevelSize  = UNSET_INTEGER  # type: int
        self.scaleSubsLevelSize  = UNSET_INTEGER  # type: int
        self.scalePriceIncrement = UNSET_DOUBLE  # type: float
        self.scalePriceAdjustValue = UNSET_DOUBLE  # type: float
        self.scalePriceAdjustInterval = UNSET_INTEGER  # type: int
        self.scaleProfitOffset = UNSET_DOUBLE  # type: float
        self.scaleAutoReset = False
        self.scaleInitPosition = UNSET_INTEGER   # type: int
        self.scaleInitFillQty = UNSET_INTEGER    # type: int
        self.scaleRandomPercent = False
        self.scaleTable = ""

        # HEDGE ORDERS
        self.hedgeType             = "" # 'D' - delta, 'B' - beta, 'F' - FX, 'P' - pair
        self.hedgeParam            = "" # 'beta=X' value for beta hedge, 'ratio=Y' for pair hedge

        # Clearing info
        self.account               = "" # IB account
        self.settlingFirm          = ""
        self.clearingAccount       = ""   #True beneficiary of the order
        self.clearingIntent        = "" # "" (Default), "IB", "Away", "PTA" (PostTrade)

        # ALGO ORDERS ONLY
        self.algoStrategy          = ""

        self.algoParams            = None    #TagValueList
        self.smartComboRoutingParams = None  #TagValueList

        self.algoId = ""

        # What-if
        self.whatIf = False

        # Not Held
        self.notHeld = False
        self.solicited = False

        # models
        self.modelCode = ""

        # order combo legs

        self.orderComboLegs = None  # OrderComboLegListSPtr

        self.orderMiscOptions = None  # TagValueList

        # VER PEG2BENCH fields:
        self.referenceContractId = 0
        self.peggedChangeAmount = 0.
        self.isPeggedChangeAmountDecrease = False
        self.referenceChangeAmount = 0.
        self.referenceExchangeId = ""
        self.adjustedOrderType = ""

        self.triggerPrice = UNSET_DOUBLE
        self.adjustedStopPrice = UNSET_DOUBLE
        self.adjustedStopLimitPrice = UNSET_DOUBLE
        self.adjustedTrailingAmount = UNSET_DOUBLE
        self.adjustableTrailingUnit = 0
        self.lmtPriceOffset = UNSET_DOUBLE

        self.conditions = []  # std::vector<ibapi::shared_ptr<OrderCondition>>
        self.conditionsCancelOrder = False
        self.conditionsIgnoreRth = False

        # ext operator
        self.extOperator = ""

        # native cash quantity
        self.cashQty = UNSET_DOUBLE

        self.mifid2DecisionMaker = ""
        self.mifid2DecisionAlgo = ""
        self.mifid2ExecutionTrader = ""
        self.mifid2ExecutionAlgo = ""


    def __str__(self):
        s = "%s,%d,%s:" % (self.orderId, self.clientId, self.permId)

        s += " %s %s %d@%f" % (
            self.orderType,
            self.action,
            self.totalQuantity,
            self.lmtPrice)

        s += " %s" % self.tif

        if self.orderComboLegs:
            s += " CMB("
            for leg in self.orderComboLegs:
                s += str(leg) + ","
            s += ")"

        if self.conditions:
            s += " COND("
            for cond in self.conditions:
                s += str(cond) + ","
            s += ")"

        return s class OrderComboLeg(Object):
    def __init__(self):
        self.price = UNSET_DOUBLE  # type: float

    def __str__(self):
        return "%f" % self.price class Contract(Object):
    def __init__(self):
        self.conId = 0
        self.symbol = ""
        self.secType = ""
        self.lastTradeDateOrContractMonth = ""
        self.strike = 0.  # float !!
        self.right = ""
        self.multiplier = ""
        self.exchange = ""
        self.primaryExchange = "" # pick an actual (ie non-aggregate) exchange that the contract trades on.  DO NOT SET TO SMART.
        self.currency = ""
        self.localSymbol = ""
        self.tradingClass = ""
        self.includeExpired = False
        self.secIdType = ""	  # CUSIP;SEDOL;ISIN;RIC
        self.secId = ""

        #combos
        self.comboLegsDescrip = ""  # type: str; received in open order 14 and up for all combos
        self.comboLegs = None     # type: list<ComboLeg>
        self.underComp = None


    def __str__(self):
        s = ",".join((
            str(self.conId),
            str(self.symbol),
            str(self.secType),
            str(self.lastTradeDateOrContractMonth),
            str(self.strike),
            str(self.right),
            str(self.multiplier),
            str(self.exchange),
            str(self.primaryExchange),
            str(self.currency),
            str(self.localSymbol),
            str(self.tradingClass),
            str(self.includeExpired),
            str(self.secIdType),
            str(self.secId)))
        s += "combo:" + self.comboLegsDescrip

        if self.comboLegs:
            for leg in self.comboLegs:
                s += ";" + str(leg)

        if self.underComp:
            s += ";" + str(self.underComp)

        return s class ContractDescription(Object):
    def __init__(self):
        self.contract = Contract()
        self.derivativeSecTypes = None   # type: list of strings class UnderComp(Object):
    def __init__(self):
        self.conId = 0   # type: int
        self.delta = 0.  # type: float
        self.price = 0.  # type: float

    def __str__(self):
        return ",".join((
            str(self.conId),
            str(self.delta),
            str(self.price))) class ComboLeg(Object):
    def __init__(self):
        self.conId = 0  # type: int
        self.ratio = 0  # type: int
        self.action = ""      # BUY/SELL/SSHORT
        self.exchange = ""
        self.openClose = 0   # type: int; LegOpenClose enum values
         # for stock legs when doing short sale
        self.shortSaleSlot = 0
        self.designatedLocation = ""
        self.exemptCode = -1


    def __str__(self):
        return ",".join((
            str(self.conId),
            str(self.ratio),
            str(self.action),
            str(self.exchange),
            str(self.openClose),
            str(self.shortSaleSlot),
            str(self.designatedLocation),
            str(self.exemptCode))) class Execution(Object):

    def __init__(self):
        self.execId = ""
        self.time =  ""
        self.acctNumber =  ""
        self.exchange =  ""
        self.side = ""
        self.shares = 0.
        self.price = 0. 
        self.permId = 0
        self.clientId = 0
        self.orderId = 0
        self.liquidation = 0
        self.cumQty = 0.
        self.avgPrice = 0.
        self.orderRef =  ""
        self.evRule =  ""
        self.evMultiplier = 0.
        self.modelCode =  ""
        self.lastLiquidity = 0

    def __str__(self):
        return ",".join((
            str(self.execId),
            str(self.time),
            str(self.acctNumber),
            str(self.exchange),
            str(self.side),
            str(self.shares),
            str(self.price),
            str(self.permId),
            str(self.clientId),
            str(self.orderId),
            str(self.liquidation),
            str(self.cumQty),
            str(self.avgPrice),
            str(self.orderRef),
            str(self.evRule),
            str(self.evMultiplier),
            str(self.modelCode),
            str(self.lastLiquidity))) class OrderState:

    def __init__(self):
      self.status= ""
      self.initMargin= ""
      self.maintMargin= ""
      self.equityWithLoan= ""

      self.commission = UNSET_DOUBLE      # type: float
      self.minCommission = UNSET_DOUBLE   # type: float
      self.maxCommission = UNSET_DOUBLE   # type: float
      self.commissionCurrency = ""
      self.warningText = "" class SoftDollarTier(Object):
    def __init__(self, name = "", val = "", displayName = ""):
        self.name = name
        self.val = val
        self.displayName = displayName

    def __str__(self):
        return "%s=%s,%s" % (self.name, self.val, self.displayName) class TagValue(Object):
    def __init__(self, tag:str=None, value:str=None):
        self.tag = str(tag)
        self.value = str(value)

    def __str__(self):
        # this is not only used for Python dump but when encoding to send
        # so don't change it lightly !
        return "%s=%s;" % (self.tag, self.value) class ScanData(Object):
    def __init__(self):
        self.contract = None
        self.rank = 0
        self.distance = ""
        self.benchmark = ""
        self.projection = ""
        self.legsStr = ""

    def __str__(self):
        return "%s,%d,%s,%s,%s,%s" % (self.contract, self.rank, self.distance,
            self.benchmark, self.projection, self.legsStr) class CommissionReport(Object):

    def __init__(self):
        self.execId = ""
        self.commission = 0. 
        self.currency = ""
        self.realizedPNL =  0.
        self.yield_ = 0.
        self.yieldRedemptionDate = 0  # YYYYMMDD format

    def __str__(self):
        s = "%s: %f %s %f %f %d" % (self.execId, self.commission, 
            self.currency, self.realizedPNL, self.yield_, 
            self.yieldRedemptionDate)
        return s BAD_MESSAGE = CodeMsgPair(508, "Bad message")
from ibapi import order_condition
from ibapi.message import IN
from ibapi.wrapper import *
from ibapi.order import Order
from ibapi.order import OrderComboLeg
from ibapi.contract import Contract
from ibapi.contract import ContractDescription
from ibapi.contract import UnderComp
from ibapi.contract import ComboLeg
from ibapi.execution import Execution
from ibapi.order_state import OrderState
from ibapi.server_versions import *
from ibapi.utils import *
from ibapi.softdollartier import SoftDollarTier
from ibapi.ticktype import *
from ibapi.tag_value import TagValue
from ibapi.scanner import ScanData
from ibapi.commission_report import CommissionReport
from ibapi.errors import BAD_MESSAGE
from ibapi.common import *
        version = UNSET_INTEGER

        if self.serverVersion < MIN_SERVER_VER_SYNT_REALTIME_BARS:
            version = decode(int, fields)

        reqId = decode(int, fields)
        startDateStr = decode(str, fields) # ver 2 field
        endDateStr = decode(str, fields) # ver 2 field

        itemCount = decode(int, fields)

        for idxBar in range(itemCount):
            bar = BarData()
            bar.date = decode(str, fields)
            bar.open = decode(float, fields)
            bar.high = decode(float, fields)
            bar.low = decode(float, fields)
            bar.close = decode(float, fields)
            bar.volume = decode(int, fields)
            bar.average = decode(float, fields)

            if self.serverVersion < MIN_SERVER_VER_SYNT_REALTIME_BARS:
                hasGaps = decode(str, fields)

            bar.barCount = decode(int, fields) # ver 3 field

            self.wrapper.historicalData(reqId, bar)

        # send end of dataset marker
        self.wrapper.historicalDataEnd(reqId, startDateStr, endDateStr)

    def processHistoricalDataUpdateMsg(self, fields):
        sMsgId = next(fields)
        reqId = decode(int, fields)
        bar = BarData()
        bar.barCount = decode(int, fields)
        bar.date = decode(str, fields)
        bar.open = decode(float, fields)
        bar.close = decode(float, fields)
        bar.high = decode(float, fields)
        bar.low = decode(float, fields)
        bar.average = decode(float, fields)
        bar.volume = decode(int, fields)
        self.wrapper.historicalDataUpdate(reqId, bar)

    def processRealTimeBarMsg(self, fields):
        sMsgId = next(fields)
        version = decode(int, fields)
        reqId = decode(int, fields)

        bar = BarData()
        bar.date = decode(int, fields)
        bar.open = decode(float, fields)
        bar.high = decode(float, fields)
        bar.low = decode(float, fields)
        bar.close = decode(float, fields)
        bar.volume = decode(int, fields)
        bar.wap = decode(float, fields)
        bar.count = decode(int, fields)

        self.wrapper.realtimeBar(reqId, bar.date, bar.open, bar.high, bar.low, bar.close, bar.volume, bar.wap, bar.count)

    def processTickOptionComputationMsg(self, fields):
        optPrice = None
        pvDividend = None
        gamma = None
        vega = None
        theta = None
        undPrice = None

        sMsgId = next(fields)
        version = decode(int, fields)
        reqId = decode(int, fields)
        tickTypeInt = decode(int, fields)

        impliedVol = decode(float, fields)
        delta = decode(float, fields)

        if impliedVol < 0:    # -1 is the "not computed" indicator
            impliedVol = None
        if delta > 1. or delta < -1.: # -2 is the "not computed" indicator
            delta = None

        if version >= 6 or \
            tickTypeInt == TickTypeEnum.MODEL_OPTION or \
                        tickTypeInt == TickTypeEnum.DELAYED_MODEL_OPTION:

            optPrice = decode(float, fields)
            pvDividend = decode(float, fields)

            if optPrice < 0:    # -1 is the "not computed" indicator
                optPrice = None
            if pvDividend < 0:  # -1 is the "not computed" indicator
                pvDividend = None

        if version >= 6:
            gamma = decode(float, fields)
            vega = decode(float, fields)
            theta = decode(float, fields)
            undPrice = decode(float, fields)

            if gamma > 1 or gamma < -1:  # -2 is the "not yet computed" indicator
                gamma = None
            if vega > 1 or vega < -1:    # -2 is the "not yet computed" indicator
                vega = None
            if theta > 1 or theta < -1:  # -2 is the "not yet computed" indicator
                theta = None
            if undPrice < 0:             # -1 is the "not computed" indicator
                undPrice = None

        self.wrapper.tickOptionComputation(reqId, tickTypeInt, impliedVol,
            delta, optPrice, pvDividend, gamma, vega, theta, undPrice)



    def processDeltaNeutralValidationMsg(self, fields):
        sMsgId = next(fields)
        version = decode(int, fields)
        reqId = decode(int, fields)


        underComp = UnderComp()