Example #1
0
def main():
    if len(sys.argv) != NO_OF_PARAMS:
        print "Invalid number of parameters"
        print "./calculate_profit.py csv_file"

    PL = int(0)
    lot_size_dict = utils.get_fno_dict()

    fp = open(sys.argv[1])
    count = int(0)
    #TODO: Format output
    print "------------------------------------------"
    for row in fp:
        if (count == int(0)):
            count = count + int(1)
            continue
        li = row.split(",")
        try:
            lot_size = lot_size_dict[li[1]]
        except KeyError:
            count = count + int(1)
            continue

        lot_size = lot_size_dict[li[1]]
        current_pl = float(float(li[5]) * int(lot_size))

        print li[1], " = ", current_pl
        count = count + int(1)
        PL = float(PL) + float(current_pl)

    print "------------------------------------------"
    print "Total P/L = ", PL
    print "------------------------------------------"
Example #2
0
def simulate(filename):
    count = int(0)
    fno_dict = utils.get_fno_dict()
    fp = open(filename)
    for each in fp:
        each = each.split(",")
        if each[1] != "EQ":
            continue
        # only take scrips whose price is greater than 100 and less than 2000
        if float(each[3]) > float(2000):
            continue
        if float(each[3]) < float(200):
            continue
        
        if each[0] in fno_dict:
            count = count + int(1)
            generate_orders(each[0], base_dict[each[0]], each[2])
            
    print "Count = ", count
Example #3
0
def main():
    print "Executing CBO Algo for Equities"
    print "-------------------------------"

    global fno_dict, base_dict, config_dict, orders

    inst_token = []

    #TODO: Add argparser for validating input
    if len(sys.argv) < NO_OF_PARAMS:
        print "Invalid number of params"
        #return

    # read config file
    config_dict = utils.read_config_file()
    
    # get list of fno
    fno_dict = utils.get_fno_dict()

    # get yesterdays high low
    base_dict = get_yesterdays_ohlc(sys.argv[1])
    
    '''
    #simulate(sys.argv[2])
    #return 
    #open kite connection 
    if len(sys.argv) == int(NO_OF_PARAMS) + int(1):
        request_token = sys.argv[2]
    else:
        request_token = None
    
    #kite = kite_utils.kite_login(request_token)
    config = ConfigParser.ConfigParser()
    config.read(config_dict['data_access'])
    access_token = config.get('MAIN','DATA_ACCESS_TOKEN')
   
    #my_api = "yvyxm4vynkq1pj8q"
    #my_api_secret = "53ekyylrx3orbb85l8isj4o291o22g31" 
    
    my_api = str(config_dict['kite_api_key'])
    my_api_secret = str(config_dict['kite_api_secret'])
    
    kite = KiteConnect(api_key=my_api)
    url = kite.login_url()
    # Redirect the user to the login url obtained
    # from kite.login_url(), and receive the request_token
    # from the registered redirect url after the login flow.
    # Once you have the request_token, obtain the access_token
    # as follows.
    # sys.argv[1] is access token that we get from login
    if request_token == None:
        kite.set_access_token(access_token)
    else:
        data = kite.generate_session(request_token, api_secret=my_api_secret)
        kite.set_access_token(data["access_token"])
        access_token = data["access_token"]
        config.set('MAIN','DATA_ACCESS_TOKEN', data["access_token"])

        with open(config_dict['data_access'], 'wb') as configfile:
            config.write(configfile)
    prit kite
    '''

    kite = kite_utils.login_kite(None)

    # get instrument list
    quote_list = []
    data = kite.instruments("NSE")
    for each in fno_dict:
        for instrument in data:
            if each == instrument['tradingsymbol']:
                entry = "NSE:" + str(instrument['tradingsymbol'])
                quote_list.append(entry)
    
    # open file to write buy/sell orders
    fp = open(config_dict['cbo_seed_file'], "w")
   
    # write header
    outstring = "########################################################################################\n"
    fp.write(outstring)
    outstring = "# CBO file generated for " + time.strftime("%c") +"\n"
    fp.write(outstring)
    outstring = "########################################################################################\n"
    fp.write(outstring)

    count = int(0)
    quotes = kite.quote(quote_list)
    for each in quotes:
        scrip = each.split(":")[1].strip("\n")
        if float(quotes[each]["ohlc"]["open"]) < float(config_dict['start_price']):
            continue
        
        if float(quotes[each]["ohlc"]["open"]) > float(config_dict['end_price']):
            continue

        count = int(count) + int(1);
        buy, sell = generate_orders(scrip, base_dict[scrip], quotes[each]['ohlc']['open'])
        if (buy != None):
            fp.write(buy)
        if (sell != None):
            fp.write(sell)
    fp.close()
    
    # push all the orders
    order_list = []
    fp = open(config_dict['cbo_seed_file'])
    for each in fp:
        #ignore line starting with #
        if each.startswith("#"):
            continue
        each = each.rstrip()
        order_list.append(each.split(" "))
    fp.close()
    print "----------------------------------------------------------------"
    print order_list
    print "----------------- End of order list ----------------------------"
    
    for each in order_list:
        try:
            print each
            order_id = kite.place_order(
                    tradingsymbol=str(each[SCRIP_ID]),
                    exchange="NSE", 
                    transaction_type=str(each[ACTION_ID]),
                    quantity=1,
                    order_type="SL",
                    product="BO",
                    price = float(each[PRICE_ID]),
                    trigger_price = float(each[TRIGGER_ID]),
                    squareoff = float(each[TARGET_ID]),
                    stoploss = float(each[STOPLOSS_ID]),
                    variety = "bo",
                    validity = "DAY"
                    )

            logging.info("Order placed. ID is: {}".format(order_id))
        except Exception as e:
            logging.info("Order placement failed: {}".format(e.message))
Example #4
0
def main():
    print "Executing CBO Algo for Equities"
    print "-------------------------------"
    global kite
    global fno_dict, base_dict, config_dict, orders
    global scrip_map, sub_list
    global order_dict
    inst_token = []

    #TODO: Add argparser for validating input
    if len(sys.argv) < NO_OF_PARAMS:
        print "Invalid number of params"
        #return

    # read config file
    config_dict = utils.read_config_file()
    
    # get list of fno
    fno_dict = utils.get_fno_dict()

    # get yesterdays high low
    base_dict = get_yesterdays_ohlc(sys.argv[1])
   
    #get kite object
    api_key, access_token, kite = kite_utils.login_kite(None)

    # get instrument list, create quote subscription list and 
    # mapping between instrument token and tradingsymbol
    quote_list = []
    data = kite.instruments("NSE")
    for each in fno_dict:
        for instrument in data:
            if each == instrument['tradingsymbol']:
                entry = "NSE:" + str(instrument['tradingsymbol'])
                quote_list.append(entry)
                # sub list for subscribing to the quotes
                sub_list.append(int(instrument['instrument_token']))
                #mapping dictionary for token and trading symbol
                scrip_map[int(instrument['instrument_token'])] = str(instrument['tradingsymbol'])
    
    print scrip_map
    # open file to write buy/sell orders
    fp = open(config_dict['cbo_seed_file'], "w")
  
    # write header
    utils.write_header(fp, "CBO")

    # Generate order file
    count = int(0)
    quotes = kite.quote(quote_list)
    for each in quotes:
        scrip = each.split(":")[1].strip("\n")
        if scrip not in base_dict:
            continue
        if float(quotes[each]["ohlc"]["open"]) < float(config_dict['start_price']):
            continue
        
        if float(quotes[each]["ohlc"]["open"]) > float(config_dict['end_price']):
            continue
        count = int(count) + int(1);
        buy, sell = generate_orders(scrip, base_dict[scrip], quotes[each]['ohlc']['open'])
        if (buy != None):
            fp.write(buy)
        if (sell != None):
            fp.write(sell)
    fp.close()

    # create dictionary for active orders

    curr_order = kite.orders()
    print "------------------------------------------------"
    print curr_order
    print "------------------------------------------------"


    # push all the orders
    order_list = []
    order_dict = {}
    fp = open(config_dict['cbo_seed_file'])
    for each in fp:
        #ignore line starting with #
        if each.startswith("#"):
            continue
        each = each.rstrip()
        line = each.split(" ")
        scrip = line[SCRIP_ID]
        action = line[ACTION_ID]
        price = line[PRICE_ID]
        t_price = line[TRIGGER_ID]
        target = line[TARGET_ID]
        stoploss = line[STOPLOSS_ID]
        live_price = line[LIVE_PRICE_ID]

        if line[SCRIP_ID] not in order_dict:
            order_dict[scrip] = {}
            order_dict[scrip][action] = {}
        else:
            order_dict[scrip][action] = {}

        order_dict[scrip][action]['price'] = price
        order_dict[scrip][action]['trigger_price'] = t_price
        order_dict[scrip][action]['target'] = target
        order_dict[scrip][action]['stoploss'] = stoploss
        order_dict[scrip][action]['flag'] = 0
        order_dict[scrip][action]['live_price'] = live_price
        
    fp.close()
    
    print "----------------------------------------------------------------"
    print order_dict
    print "----------------- End of order list ----------------------------"
  
    kws = KiteTicker(api_key, access_token, debug=False)
    kws.on_ticks = on_ticks
    kws.on_connect = on_connect
    kws.on_close = on_close
    kws.on_error = on_error
    kws.on_noreconnect = on_noreconnect
    kws.on_reconnect = on_reconnect
    kws.on_order_update = on_order_update
    kws.connect()
def main():
    print "Main"
    global kite
    global fno_dict, base_dict, config_dict, orders
    global scrip_map, sub_list
    global order_dict
    global fno_mapping
    global order_dict
    #TODO: Add argparser for validating input

    # read config file
    config_dict = utils.read_config_file()

    # get list of fno
    fno_dict = utils.get_fno_dict()

    #get kite object
    api_key, access_token, kite = kite_utils.login_kite(None)

    # get instrument list, create quote subscription list and
    # mapping between instrument token and tradingsymbol
    quote_list = []
    data = kite.instruments("NSE")
    for each in fno_dict:
        for instrument in data:
            if each == instrument['tradingsymbol']:
                entry = "NSE:" + str(instrument['tradingsymbol'])
                quote_list.append(entry)
                # sub list for subscribing to the quotes
                sub_list.append(int(instrument['instrument_token']))
                #mapping dictionary for token and trading symbol
                scrip_map[int(instrument['instrument_token'])] = str(
                    instrument['tradingsymbol'])

    # Generate order file
    count = int(0)
    quotes = kite.quote(quote_list)
    for each in quotes:
        scrip = each.split(":")[1].strip("\n")
        if scrip not in fno_dict:
            continue
        if float(quotes[each]["ohlc"]["open"]) < float(
                config_dict['start_price']):
            continue

        if float(quotes[each]["ohlc"]["open"]) > float(
                config_dict['end_price']):
            continue
        count = int(count) + int(1)

        if quotes[each]['ohlc']['open'] == quotes[each]['ohlc']['low']:
            diff = float(quotes[each]['ohlc']['high']) - float(
                quotes[each]['ohlc']['low'])
            percentage = float(quotes[each]['ohlc']['open']) * float(0.007)
            if float(percentage) < float(diff):
                print each

        if quotes[each]['ohlc']['open'] == quotes[each]['ohlc']['high']:
            diff = float(quotes[each]['ohlc']['high']) - float(
                quotes[each]['ohlc']['low'])
            percentage = float(quotes[each]['ohlc']['open']) * float(0.007)
            if float(percentage) < float(diff):
                print each
Example #6
0
def main():
    print "Executing CBO Algo for Equities"
    print "-------------------------------"

    global fno_dict
    global base_dict
    global config_dict
    global orders
    global sub_list
    global fno_mapping
    global order_dict
    #TODO: Add argparser for validating input
    if len(sys.argv) < NO_OF_PARAMS:
        print "Invalid number of params"
        return

    # read config file
    config_dict = utils.read_config_file()

    # get list of fno
    fno_dict = utils.get_fno_dict()

    # get yesterdays high low
    base_dict = get_yesterdays_fno_ohlc(sys.argv[1])
    #simulate(sys.argv[2])

    #open kite connection
    if len(sys.argv) == int(NO_OF_PARAMS) + int(1):
        request_token = sys.argv[2]
    else:
        request_token = None

    #api_key, access_token, kite = kite_utils.kite_login(request_token)

    # get instrument list
    quote_list = []
    data = kite.instruments("NFO")
    for each in data:
        if each['instrument_type'] != 'FUT':
            continue

        if config_dict['contract_str'] not in each['tradingsymbol']:
            continue

        entry = "NFO:" + str(each['tradingsymbol'])
        quote_list.append(entry)
        sub_list.append(int(each['instrument_token']))
        fno_mapping[int(each['instrument_token'])] = str(each['tradingsymbol'])

    print "=============================="
    print fno_mapping
    print "=============================="

    # open file to write buy/sell orders
    fp = open(config_dict['cbo_fno_seed_file'], "w")
    count = int(0)
    quotes = kite.quote(quote_list)
    for each in quotes:

        scrip = each.split(":")[1].strip("\n")
        m = re.search("\d", scrip)
        if m:
            scrip = scrip[:m.start()]

        if float(quotes[each]["ohlc"]["open"]) < float(
                config_dict['start_price']):
            continue

        if float(quotes[each]["ohlc"]["open"]) > float(
                config_dict['end_price']):
            continue

        count = int(count) + int(1)
        if scrip in base_dict:
            scrip_fno = scrip + "18MARFUT"
            print scrip_fno
            buy, sell = generate_orders(scrip, base_dict[scrip],
                                        quotes[each]['ohlc']['open'])
            if (buy != None):
                buy_dict = {}
                each = buy.split(" ")
                buy_dict['price'] = each[2]
                buy_dict['target'] = float(
                    utils.get_floating_value(float(each[2]) + float(each[4])))
                buy_dict['stoploss'] = float(
                    utils.get_floating_value(float(each[2]) - float(each[5])))
                buy_dict['trade_active'] = False
                order_dict[scrip_fno] = {}
                order_dict[scrip_fno]['buy'] = buy_dict
                fp.write(buy)
            if (sell != None):
                sell_dict = {}
                each = sell.split(" ")
                sell_dict['price'] = each[2]
                sell_dict['target'] = float(
                    utils.get_floating_value(float(each[2]) - float(each[4])))
                sell_dict['stoploss'] = float(
                    utils.get_floating_value(float(each[2]) + float(each[5])))
                sell_dict['trade_active'] = False
                order_dict[scrip_fno]['sell'] = sell_dict
                fp.write(sell)
    fp.close()
    print "-------------------------------------------------------"
    print order_dict
    print "-------------------------------------------------------"

    kws = KiteTicker(api_key, access_token, debug=False)
    kws.on_ticks = on_ticks
    kws.on_connect = on_connect
    kws.on_close = on_close
    kws.on_error = on_error
    kws.on_noreconnect = on_noreconnect
    kws.on_reconnect = on_reconnect
    kws.on_order_update = on_order_update
    kws.connect()