Exemple #1
0
def place_mis_bracket_order(kite,
                            instrument,
                            type,
                            price,
                            quantity,
                            target_points,
                            stoploss_points,
                            trailing_stoploss,
                            exchange="NSE"):
    """Places an intraday bracket order.

  Args:
    kite(obj): KiteConnect object.
    instrument(str): Symbol of stock.
    type(str): Either "buy" or "sell"
    price(float): Price at which to buy shares.
    quantity(int): Number of shares to buy.
    target_points(float):
    stoploss_points(float):
    trailing_stoploss(int): Trailing stoploss value.
                            Default: 0
    exchange(str): Market exchange("NSE", "BSE").
                   Defaults: "NSE"

  Returns:
    (int): order_id if successful else -1.

  """
    # Get constants.
    type = TRANSACTION_TYPE_MAP[type]
    exchange = EXCHANGE_MAP[exchange]

    # Place bracket order.
    try:
        resp = kite.place_order(tradingsymbol=instrument,
                                exchange=exchange,
                                transaction_type=type,
                                quantity=quantity,
                                order_type=KiteConnect.ORDER_TYPE_LIMIT,
                                price=price,
                                product=KiteConnect.PRODUCT_MIS,
                                variety=KiteConnect.VARIETY_BO,
                                squareoff=target_points,
                                stoploss=stoploss_points,
                                trailing_stoploss=trailing_stoploss)

        if resp["status"] == "success":
            INFO(
                f"Order placed successfully: Instrument:{exchange}:{instrument}, "
                f"Type:{type}, Quantity:{quantity}")
            return resp["data"]["order_id"]
        else:
            ERROR(f"Error while placing order for {instrument}")
            return -1

    except Exception as ex:
        # If any exception occurred, catch it and return an error response.
        ERROR(f"Error while placing order for {instrument}: {ex}")
        return -1
Exemple #2
0
def get_holdings(kite):
  """get current holdings for given kite object.

  Args:
    kite(obj):KiteConnect object.

  Returns:
    (list): list of dicts with holdings info.

  """
  # Get holdings.
  try:
    resp = kite.holdings()

    # Return if success else raise exception.
    if resp["status"] == "success":
      INFO(f"Current holdings are: {resp['data']}")
    else:
      raise Exception(f"Status:{resp['status']}, Error:{resp['error_type']}, "
                      f"Error Message:{resp['message']}")

  except Exception as ex:
    ERROR(f"Error occurred while getting holdings:{ex}")
    raise
  return resp["data"]
Exemple #3
0
def get_instrument_tokens(kite, instruments, exchange="NSE"):
    """Get instrument tokens for given instrument symbols of exchange.

  Args:
    kite(obj): KiteConnect object.
    instruments(list): list of symbols.
    exchange(str): Market Exchange.(BFO, BSE, NSE, NFO, MCX, CDS)
                   Default: "NSE"

  Returns:
    (dict): instrument_tokens corresponding to given instrument symbols.
            (symbol:token)

  """
    instruments_dump = kite.instruments(exchange)
    instruments_df = pd.DataFrame(instruments_dump)
    instrument_tokens = {}

    INFO(f"Instruments list:{instruments}")
    for symbol in instruments:
        try:
            token = instruments_df[instruments_df.tradingsymbol ==
                                   symbol].instrument_token.values[0]
            instrument_tokens[symbol] = int(token)
        except:
            ERROR(f"Error occurred during lookup token for symbol:{symbol}")
            raise

    INFO(f"Instrument-token dict:{instrument_tokens}")
    return instrument_tokens
Exemple #4
0
def place_mis_market_order(kite, instrument, type, quantity, exchange="NSE"):
    """Places an intraday market order.

  Args:
    kite(obj): KiteConnect object.
    instrument(str): Symbol of stock.
    type(str): Either "buy" or "sell"
    quantity(int): Number of shares to buy.
    exchange(str): Market exchange("NSE", "BSE").
                   Default: "NSE"

  Returns:
      (int): order_id if successful else -1.

  """
    # Get constants.
    type = TRANSACTION_TYPE_MAP[type]
    exchange = EXCHANGE_MAP[exchange]

    # Place market order.
    try:
        resp = kite.place_order(tradingsymbol=instrument,
                                exchange=exchange,
                                transaction_type=type,
                                quantity=quantity,
                                order_type=KiteConnect.ORDER_TYPE_MARKET,
                                product=KiteConnect.PRODUCT_MIS,
                                variety=KiteConnect.VARIETY_REGULAR)
        if resp["status"] == "success":
            INFO(
                f"Order placed successfully: Instrument:{exchange}:{instrument}, "
                f"Type:{type}, Quantity:{quantity}")
            return resp["data"]["order_id"]
        else:
            ERROR(f"Error while placing response")
            return -1

    except Exception as ex:
        # If any exception occurred, catch it and return an error response.
        ERROR(f"Error while placing order for {instrument}: {ex}")
        return -1
Exemple #5
0
def get_ltp(kite, instrument):
    """Get last traded price for an instrument.

  Args:
    kite(obj): KiteConnect object.
    instrument(str): Instrument in format "Exchange:Symbol"("NSE:INFY").

  Returns:
    (float): Last traded price.

  """
    resp = kite.ltp(instrument)
    if resp['status'] == "success":
        INFO(f"LTP for {instrument}:{resp['data'][instrument]['last_price']}")
    else:
        # Log error details and retry.
        ERROR("Error occurred while getting ltp-")
        ERROR(f"Status:{resp['status']}, Error:{resp['error_type']}, "
              f"Error Message:{resp['message']}")
        raise
    return resp['data'][instrument]['last_price']
Exemple #6
0
def get_quote(kite, instrument):
    """Get quote for an instrument.
  Warning: It may return a bulk object consuming lot of memory, hence avoid
  it's usage unless required.

  Args:
    kite(obj): KiteConnect object.
    instrument(str): Instrument in format "Exchange:Symbol"("NSE:INFY").

  Returns:
    (dict): the quote.

  """
    resp = kite.quote(instrument)
    if resp['status'] == "success":
        INFO(f"Quote for {instrument}: {resp['data']}")
    else:
        # Log error details and retry.
        ERROR("Error occurred while getting quote-")
        ERROR(f"Status:{resp['status']}, Error:{resp['error_type']}, "
              f"Error Message:{resp['message']}")
        raise
    return resp['data']