Beispiel #1
0
def closePositions():
    wb = xw.Book.caller()
    callingWorksheet = wb.sheets.active.name

    # Get the Excel cell address where "Positions to Close" table begins
    cellAddress = wb.sheets(callingWorksheet).tables[
        callingWorksheet + 'PositionsToCloseTable'].data_body_range(1,
                                                                    1).address

    # Pick up the "Positions to Close" table
    positionsToClose = wb.sheets(callingWorksheet).tables[
        callingWorksheet +
        'PositionsToCloseTable'].data_body_range.options(ndim=2).value

    # If the first cell of the "Positions to Close" is empty, raise error
    if positionsToClose[0][0] == None or positionsToClose[0][0].strip() == "":
        raise ValueError("No Positions to Close")

    # Start a new IB connection
    ib.connect('127.0.0.1', getIbConnectionPort(callingWorksheet), clientId=2)

    # Match each position to be closed with currently held positions, per IB's records
    # # If a match is found, place closing order
    for acccountPosition in ib.positions():
        for position in positionsToClose:
            if acccountPosition.contract.localSymbol.lower().replace(
                    " ", "") == position[0].lower().replace(" ", ""):
                # if current position for a contract is LONG, then set closing action to "SELL"
                # otherwise set closing action to "BUY"
                closingAction = "SELL" if acccountPosition.position > 0 else "BUY"

                # Prepare closing order
                if position[1].upper() == "LMT":
                    # If limit price is not set, then raise error
                    if ibi.util.isNan(position[2]) or position[2] < 0:
                        ib.disconnect()
                        raise ValueError("Incorrect Limit Price for " +
                                         position[0])
                    else:
                        closingOrder = ibi.LimitOrder(
                            closingAction,
                            abs(acccountPosition.position),
                            position[2],
                            account=getSheetNameDict().get(callingWorksheet))
                elif position[1].upper() == "MKT":
                    closingOrder = ibi.MarketOrder(
                        closingAction,
                        abs(acccountPosition.position),
                        account=getSheetNameDict().get(callingWorksheet))
                else:
                    raise ValueError("Incorrect Order Type for " + position[0])

                ib.qualifyContracts(acccountPosition.contract)
                trade = ib.placeOrder(acccountPosition.contract, closingOrder)
                assert trade in ib.trades()

    # Disconnect from IB after placing the orders
    ib.disconnect()
def tradelimitorder(ib, contract, quantity, price):
    try:
        print("tradelimitorder")
        ultimaordre =[]
        ordertype  = "BUY"
        if quantity < 0: ordertype = "SELL"
        order = ibsync.LimitOrder(ordertype, abs(quantity), price, tif="GTC", transmit=False)
        ib.qualifyContracts(contract)
        trade = ib.placeOrder(contract, order)
        ib.sleep(1)
        return trade
    except Exception as err:
        error_handling(err)
        raise
def tradelimitorder(ib, db, contract, quantity, price, scode=None, ttype=None):
    try:
        ordertype = "BUY" if quantity >= 0 else "SELL"
        order = ibsync.LimitOrder(ordertype,
                                  abs(quantity),
                                  price,
                                  tif="GTC",
                                  transmit=False)
        ib.qualifyContracts(contract)
        trade = ib.placeOrder(contract, order)
        assert trade in ib.trades()
        assert order in ib.orders()
        # Insertem el contracte a la taule Contract (si no hi és)
        ibdb.dbfill_contracts(db, [contract])
        ibdb.dbfill_orders(db, order, trade, scode, ttype)
        return trade
    except Exception as err:
        #error_handling(err)
        raise
 def place_limit_order(self, contract, type_, price, quantity, sleep=True):
     """
     Places a limit order.
     
     :param contract: ib_insync.Contract instance.
     :param type_: str. 'BUY'/'Sell'
     :param price: float. Price at which the order will be triggered.
     :param quantity: int. Size of the position in dollars.
     
     :return: int. The order id used by the Trader class to indentify 
                   trades. See _get_order_id()
     """
     # Generating order.
     order = ib.LimitOrder(type_, int(quantity), price, account=self.account)
     
     # Placing order.
     order_trade_id = self._place_order(contract=contract, order=order, 
                                        sleep=sleep)
     
     return order_trade_id
def branco_strategy1(ib, db, accid):
    try:
        cnt = ibsync.Stock('VXX', 'SMART', 'USD')
        ib.qualifyContracts(cnt)
        pricevxx = ib.reqTickers(cnt)[0].marketPrice()

        chains = ib.reqSecDefOptParams(cnt.symbol, '', cnt.secType, cnt.conId)
        chain = next(c for c in chains if c.tradingClass == cnt.symbol
                     and c.exchange == cf.myprefexchange)

        lexps = []
        for e in chain.expirations:
            lexps.append(int(e))
        desiredexpiration = (date.today() +
                             timedelta(days=15)).strftime('%Y%m%d')
        expiration = min(lexps,
                         key=lambda x: abs(int(x) - int(desiredexpiration)))
        strikes = [
            strike for strike in chain.strikes
            if (pricevxx * 0.9 < strike < pricevxx * 1.1)
        ]

        contracts = [
            ibsync.Option('VXX',
                          expiration,
                          strike,
                          "C",
                          'SMART',
                          tradingClass='VXX') for strike in strikes
        ]
        ib.qualifyContracts(*contracts)
        greeks = [
            ibutil.get_greeks(ib, contract).modelGreeks
            for contract in contracts
        ]
        deltas = [greek.delta for greek in list(filter(None, greeks))]

        ishort = int(
            min(range(len(deltas)), key=lambda i: abs(deltas[i] - 0.7)))
        ilong = int(min(range(len(deltas)),
                        key=lambda i: abs(deltas[i] - 0.3)))

        #combo = ibsync.Contract()
        #combo.symbol = "VXX"
        #combo.secType = "BAG"
        #combo.exchange = "SMART"
        #combo.currency = "USD"

        #leg1 = ibsync.ComboLeg ()
        #leg1.conId = contracts[ishort]
        #leg1.ratio = 1
        #leg1.action = "SELL"
        #leg1.exchange = "SMART"

        #leg2 = ibsync.ComboLeg()
        #leg2.conId = contracts[ilong]
        #leg2.ratio = 1
        #leg2.action = "BUY"
        #leg2.exchange = "SMART"

        #combo.comboLegs = []
        #combo.comboLegs.append(leg1)
        #combo.comboLegs.append(leg2)

        #order = ibsync.order.LimitOrder("BUY", 1, 1, tif="GTC", transmit=False)
        #trade = ib.placeOrder(combo, order)

        combo = ibsync.Contract(symbol='VXX',
                                secType='BAG',
                                exchange='SMART',
                                currency='USD',
                                comboLegs=[
                                    ibsync.ComboLeg(conId=contracts[ishort],
                                                    ratio=1,
                                                    action='SELL',
                                                    exchange='SMART'),
                                    ibsync.ComboLeg(conId=contracts[ilong],
                                                    ratio=1,
                                                    action='BUY',
                                                    exchange='SMART')
                                ])
        trade = tradelimitorder(ib, db, combo, 1, 1, "BRANCO_1")
        order = ibsync.LimitOrder(action='SELL',
                                  totalQuantity=1,
                                  lmtPrice=1,
                                  transmit=False,
                                  account=accid)
        trade = ib.placeOrder(combo, order)
        print(trade)
    except Exception as err:
        # error_handling(err)
        raise
Beispiel #6
0
def placeOrders():
    wb = xw.Book.caller()
    callingWorksheet = wb.sheets.active.name

    # Get the Excel cell address where "Positions to Close" table begins
    cellAddress = wb.sheets(callingWorksheet).tables[
        callingWorksheet + 'OrderListTable'].data_body_range(1, 1).address

    # Pick up the "Positions to Close"
    ordersFromXL = wb.sheets(callingWorksheet).tables[
        callingWorksheet +
        'OrderListTable'].data_body_range.options(ndim=2).value

    # If the first cell of the "Positions to Close" is empty, raise error
    if ordersFromXL[0][0] == None or ordersFromXL[0][0].strip() == "":
        raise ValueError("No Orders to Submit")

    # Start a new IB connection
    ib = ibi.IB()
    ib.connect('127.0.0.1', getIbConnectionPort(callingWorksheet), clientId=4)

    # Place orders one at a time
    for order in ordersFromXL:
        # Create the entryOrder object
        if order[2].upper() == "LMT":
            entryOrder = ibi.LimitOrder(
                order[1],
                abs(int(order[6])),
                order[5],
                account=getSheetNameDict().get(callingWorksheet))
        elif order[2].upper() == "MKT":
            entryOrder = ibi.MarketOrder(
                order[1],
                abs(int(order[6])),
                account=getSheetNameDict().get(callingWorksheet))
        else:
            raise ValueError("Incorrect Order Type in " + order[0])

        # Create the contract object
        if order[7].upper() == "STK":
            contract = ibi.Stock(order[8],
                                 'SMART',
                                 'USD',
                                 primaryExchange='NYSE')
        elif order[7].upper() == "OPT":
            contract = ibi.Option(order[8],
                                  "20" + order[9].strftime("%y%m%d"),
                                  order[10],
                                  order[11],
                                  'SMART',
                                  multiplier=100,
                                  currency='USD')
            ib.qualifyContracts(contract)
        else:
            raise ValueError("Incorrect instrument type")

        ib.qualifyContracts(contract)
        trade = ib.placeOrder(contract, entryOrder)
        assert trade in ib.trades()

    # Disconnect from IB after placing the orders
    ib.disconnect()