Limit Orders using ltp

Parva
I am new to using kiteconnect and not very familiar with object oriented programming in python. Can anyone please post an example where one can process LTP received via ticks, calculate an indicator using those ticks and generate limit orders.

For a simple example, I would like to get SMA(CLOSE,5) of 5 min timeframe during the live market hours and place a limit order when it crosses SMA(CLOSE,20)
  • Imran
    hii @parva

    from kiteconnect import KiteConnect


    # backtesting ema

    ak='xxxxxxxxxxxxxxxxxx' # Place your api_key here
    asecret='xxxxxxxxxxxxxxxxxx' # place your api_secret


    # stop-loss and take-profit
    trd_sl = float(input("[*] Enter Stop-Loss (eg. 5%, 10% etc) : "));
    trd_tp = float(input("[*] Enter Take-Profit (eg. 5%, 10% etc) : "));
    capital = float(input("[*] Enter tarding capital : "));

    kite = KiteConnect(api_key=ak)
    print("[*] Generate access Token : ",kite.login_url())
    request_tkn = input("[*] Enter Your Request Token Here : ")[-32:];
    data = kite.request_access_token(request_tkn, secret=asecret)
    kite.set_access_token(data["access_token"])


    #variables required to work with historical data
    from_date = input("[*] enter from date in 2018-02-12 format : ")
    to_date = input("[*] enter to date in 2018-03-12 format :")
    interval = input("[*] enter trading interval minute, 5minute, 15minute, 60minute, day : ")

    first_time_frame = int(input("[*] Enter Moving Average Period(eg. 1, 5, 10 ) : "))
    second_time_frame = int(input("[*] Enter Moving Average Period(eg. 100, 150, 200 ) : "))

    first_EMA = [];
    second_EMA = [];
    second_EMA_l = [];

    for x in range(0,first_time_frame):
    first_EMA.append(0);

    for x in range(0,second_time_frame):
    second_EMA.append(0);
    second_EMA_l.append(0);


    # to get historical data from ZERODHA
    def get_historical_data(instrument_token):
    return kite.historical(instrument_token, from_date, to_date, interval)


    buy_track = True;
    sell_track = True;

    buy_price = 0
    sell_price = 0
    prev_order_type = "";

    profit_loss = 0;

    crossover_buy = False;
    crossover_sell = False;
    is_This_Is_Iniatial_Crossover = True;

    crossover_buy_value = 0;
    crossover_sell_value = 0;

    crossover_buy_type = "";
    crossover_sell_type = "";

    def do_buy_sell(EMA1,EMA2_high,EMA2_low,candle):
    global buy_track,sell_track;
    global buy_price,sell_price;
    global prev_order_type;
    global profit_loss,trd_sl,trd_tp;

    global crossover_buy,crossover_sell;
    global crossover_buy_value,crossover_sell_value,is_This_Is_Iniatial_Crossover;
    global crossover_buy_type,crossover_sell_type;

    if is_This_Is_Iniatial_Crossover:
    crossover_buy_value = EMA1 - EMA2_high;
    crossover_sell_value = EMA1 - EMA2_low;
    crossover_buy_type = "P" if crossover_buy_value > 0 else "N";
    crossover_sell_type = "P" if crossover_sell_value > 0 else "N";
    is_This_Is_Iniatial_Crossover = False;

    if buy_track:
    if crossover_buy_type=="P":
    if (EMA1 - EMA2_high) < crossover_buy_value and (EMA1 - EMA2_high) < 0:
    crossover_buy_type = "N";
    crossover_buy = True;
    if crossover_buy_type=="N":
    if (EMA1 - EMA2_high) > crossover_buy_value and (EMA1 - EMA2_high) > 0:
    crossover_buy_type = "P";
    crossover_buy = True;

    if sell_track:
    if crossover_sell_type=="P":
    if (EMA1 - EMA2_low ) < crossover_sell_value and (EMA1 - EMA2_low ) < 0:
    crossover_sell_type = "N";
    crossover_sell = True;
    if crossover_sell_type=="N":
    if (EMA1 - EMA2_low ) > crossover_sell_value and (EMA1 - EMA2_low ) > 0:
    crossover_sell_type = "P";
    crossover_sell = True;

    crossover_buy_value = EMA1 - EMA2_high;
    crossover_sell_value = EMA1 - EMA2_low;

    if (EMA1+0.00001*candle['open']) > EMA2_high and buy_track and crossover_buy:
    print("[+] BUY : ON",candle['date'],"AT PRICE",candle['open'])
    buy_price = candle['open'];

    sell_track = False;
    buy_track = False;
    crossover_buy = False;
    prev_order_type = "BUY";

    if (EMA1-0.00001*candle['open']) < EMA2_low and sell_track and crossover_sell:
    print("[+] SELL : ON",candle['date'],"AT PRICE",candle['open'])
    sell_price = candle['open'];

    buy_track = False;
    sell_track = False;
    crossover_sell = False;
    prev_order_type = "SELL";

    if prev_order_type=="BUY":
    tp = buy_price + buy_price*(trd_tp/100);
    sl = buy_price - buy_price*(trd_sl/100);

    if tp <= candle['high']:
    profit_loss += (tp - buy_price);
    print(" [-] Hiting Take Profit ON:",candle['date']," :",round(tp - buy_price,2),"\n")
    buy_track = True;
    sell_track = True;
    prev_order_type=""

    if sl >= candle['high']:
    profit_loss -= (buy_price - sl);
    print(" [-] Hiting Stop Loss ON:",candle['date']," :",round(buy_price - sl,2),"\n")
    buy_track = True;
    sell_track = True;
    prev_order_type=""

    if prev_order_type=="SELL":
    tp = sell_price - sell_price*(trd_tp/100);
    sl = sell_price + sell_price*(trd_sl/100);

    if tp >= candle['high']:
    profit_loss += (sell_price - tp);
    print(" [-] Hiting Take Profit ON:",candle['date']," :",round(sell_price - tp,2),"\n")
    buy_track = True;
    sell_track = True;
    prev_order_type=""

    if sl <= candle['high']:
    profit_loss -= (sl - sell_price);
    print(" [-] Hiting Stop Loss ON:",candle['date']," :",round(sl - sell_price,2),"\n")
    buy_track = True;
    sell_track = True;
    prev_order_type=""

    # calculate EMA and do buy sell
    def calculate_EMA(tick,first_time_frame,second_time_frame):
    global first_EMA,second_EMA;
    global buy_track,sell_track;
    global buy_price,sell_price;
    global profit_loss;

    global crossover_buy,crossover_sell;
    global crossover_buy_value,crossover_buy_value,is_This_Is_Iniatial_Crossover;
    global crossover_buy_type,crossover_sell_type;

    crossover_buy = False;
    crossover_sell = False;
    is_This_Is_Iniatial_Crossover = True;

    crossover_buy_value = 0;
    crossover_sell_value = 0;

    crossover_buy_type = "";
    crossover_sell_type = "";

    profit_loss = 0;
    buy_price = 0
    sell_price = 0

    prev_order_type = "";

    buy_track = True;
    sell_track = True;

    count_1 = 1
    count_2 = 0

    # calculating Simple Moving Average as EMA
    first_TF = True
    multiplier1 = 2/(first_time_frame+1)
    multiplier2 = 2/(second_time_frame+1)

    # EMA VARIABLES
    EMA1_curr = 0;
    EMA2_curr = 0;
    EMA1_prev = 0;
    EMA2_prev = 0;

    EMA2_curr_l = 0;
    EMA2_prev_l = 0;

    for candle in tick:
    if count_1 <= second_time_frame:
    if count_1 >= (second_time_frame - first_time_frame):
    first_EMA.pop(0)
    first_EMA.append(int(candle['close']))
    count_2+=1;

    second_EMA.pop(0)
    second_EMA.append(int(candle['high']))

    second_EMA_l.pop(0)
    second_EMA_l.append(int(candle['low']))

    if count_2>first_time_frame:
    if first_TF:
    first_TF = False;
    s = 0
    for x in first_EMA:
    s+=x;
    EMA1_prev = round(s/first_time_frame,2);

    s = 0
    for x in second_EMA:
    s+=x;
    EMA2_prev = round(s/second_time_frame,2);

    s = 0
    for x in second_EMA_l:
    s+=x;
    EMA2_prev_l = round(s/second_time_frame,2);

    else:
    EMA1_curr = (candle['close'] - EMA1_prev) * multiplier1 + EMA1_prev
    EMA2_curr = (candle['high'] - EMA2_prev) * multiplier2 + EMA2_prev
    EMA2_curr_l = (candle['low'] - EMA2_prev_l) * multiplier2 + EMA2_prev_l

    do_buy_sell(EMA1_curr,EMA2_curr,EMA2_curr_l,candle);

    #print(EMA1_curr,"\t:\t",EMA2_curr,"\t:\t",candle['date'])
    EMA1_prev = EMA1_curr
    EMA2_prev = EMA2_curr
    EMA2_prev_l = EMA2_curr_l

    count_1+=1;
    cl = candle['close'];

    print("\n\t[*] Profit Loss :",round((profit_loss*(capital/cl)),2))





    def start():
    global first_time_frame,second_time_frame;

    trading_symbol = {81153:"BAJFINANCE",140033:"BRITANNIA",2029825:"CADILAHC",1215745:"CONCOR",3460353:"EMAMILTD",821761:"GSKCONS",3677697:"IDEA",7458561:"INFRATEL",408065:"INFY",4454401:"NHPC",3924993:"NMDC",2977281:"NTPC",648961:"PGHH",3465729:"TECHM",2889473:"UPL",784129:"VEDL"}
    for token in trading_symbol:
    print("##------------------------# BACKTESTING FOR :",trading_symbol[token],"#------------------------## ")

    calculate_EMA(get_historical_data(token),first_time_frame,second_time_frame);


    start();
  • Parva
    Hello @Imran
    Thanks a lot for such a quick response and an amazing code. Learnt a lot from this code. Why the semi colons(;) though?

    From what I understand is, this code is for backtesting EMA crossovers. (Correct me if I am wrong). Can you please guide me about the changes I need to make to receive ticks during live market hours (using KiteTicker) and actually trade ema crossovers from python (using place_order()) by calculating ema from those ticks.
Sign In or Register to comment.