def get_live_table(df, tab='monitor'): if df.shape[0] > 0: if tab == 'monitor': df = df[[ 'stock', 'qty', 'TP %', 'SL %', 'algo', 'freq', 'mode', 'state', 'ltp', 'last_processed', 'amount', 'price', 'P&L', 'P&L %', 'Total P&L', 'Total P&L %', 'low', 'sl', 'ltp %', 'tp', 'high' ]] columns = [{"name": i, "id": i} for i in df.columns] return df.to_dict('records'), columns else: df = df[[ 'stock', 'qty', 'TP %', 'SL %', 'algo', 'freq', 'mode', 'state' ]] columns = [{ "name": 'stock', "id": 'stock' }, { "name": 'qty', "id": 'qty' }, { "name": 'TP %', "id": 'TP %' }, { "name": 'SL %', "id": 'SL %' }, { "name": 'algo', "id": 'algo' }, { "name": 'freq', "id": 'freq' }, { "name": 'mode', "id": 'mode' }, { "name": 'state', "id": 'state' }] live_dropdown = { 'freq': { 'options': [{ 'label': '1D', 'value': '1D' }, { 'label': '1T', 'value': '1T' }] } } pinfo(live_dropdown) return df.to_dict('records'), columns else: return [], [{}]
def toggle_trade(n1, v): pinfo(v) if n1 == 0: return 'Order Pause', "danger" if v == 'Order Pause': live_cache.publish('order_handlerlive', 'pause') return 'Order Resume', "success" live_cache.publish('order_handlerlive', 'resume') return 'Order Pause', "danger"
def buy_bo(symbol, price, trigger, stoploss, squareoff, quantity=1, tag="bot"): pinfo('%12s'%"BUY BO: "+symbol+", price: "+str('%0.2f'%price)+", squareoff: "+str('%0.2f'%squareoff)+", stoploss: "+str('%0.2f'%stoploss)+", quantity: "+str(quantity)) try: order_id = kite.place_order(tradingsymbol=symbol, exchange=kite.EXCHANGE_NSE, transaction_type=kite.TRANSACTION_TYPE_BUY, order_type=kite.ORDER_TYPE_LIMIT, product=kite.PRODUCT_MIS, variety=kite.VARIETY_BO, quantity=quantity, trigger_price=trigger, price=price, squareoff=squareoff, stoploss=stoploss, tag=tag ) logger.info("Order placed. ID is: {}".format(order_id)) except Exception as e: logger.info("Order placement failed: {}".format(e.message))
def squareoff(symbol=None, tag="bot"): pinfo('%12s'%"Squareoff: "+symbol) orders_df = pd.DataFrame(kite.orders()) if symbol != None: open_orders = orders_df[(orders_df['tradingsymbol']==symbol) & (orders_df['status'] == 'TRIGGER PENDING') & (orders_df['tag'] == tag)] else: open_orders = orders_df[(orders_df['status'] == 'TRIGGER PENDING') & (orders_df['tag'] == tag)] for index, row in open_orders.iterrows(): pinfo(row.order_id, row.parent_order_id) kite.exit_order(variety=kite.VARIETY_BO, order_id=order_id, parent_order_id=parent_order_id)
def add(self, key, reset=False): hash_key = key + self.hash_postfix if self.hlen(hash_key) == 0 or reset == True: pinfo('Reset Cache for: {}'.format(hash_key)) self.hmset( hash_key, { 'stock': '', 'qty': 0, 'SL %': 0.0, 'TP %': 0.0, 'amount': 0, 'price': 0.0, 'P&L': 0.0, 'P&L %': 0.0, 'Total P&L': 0.0, 'Total P&L %': 0.0, 'low': 0.0, 'sl': 0.0, 'ltp': 0.0, 'ltp %': 0.0, 'tp': 0.0, 'high': 0.0, 'last_processed': 0, 'state': 'INIT', 'mode': 'PAUSE', 'algo': '', 'freq': '1T', 'hdf_freq': 'minute', 'order_id': 0 }) # Trade Log: [{timestamp, buy, sale, amount, profit, cum_profit, W_L, Mode}] # Amount: -ve for Buy, +ve for sale; W_L: +1 for Win, -1 for Loss; Mode: EN|EX|SL|TP|F self.set(hash_key + 'Trade', pd.DataFrame().to_json(orient='columns')) self.set(hash_key + 'OHLC', pd.DataFrame().to_json(orient='columns')) self.set(hash_key + 'TICK', pd.DataFrame().to_json(orient='columns')) with pd.HDFStore('data/' + hash_key + 'TICK', mode="w") as f: pd.DataFrame().to_hdf(f, format='t', key=hash_key + 'TICK') with pd.HDFStore('data/' + hash_key + 'Trade', mode="w") as f: pd.DataFrame().to_hdf(f, format='t', key=hash_key + 'Trade') self.sadd(self.hash_postfix, key) pinfo('{}=>{}'.format(hash_key, self.hgetall(hash_key)))
def start_backtest(n_clicks, stocks, qty, sl, target, start_date, end_date, algo, freq, algo_name, mode ): toDate = end_date fromDate = start_date try: pinfo("==========: {} :========".format(session["access_token"])) except: perror("Access Token Not found") #return 0 if n_clicks == 0: return 0 if len(mode) > 0: backtest = 'quick' else: backtest = 'full' if not isinstance(stocks,list): stocks = [stocks] pdebug1(stocks) # Step 1: Create the msg for initiating backtest #pinfo(freq) backtest_msg={'stock':stocks,'sl':sl,'target':target,'qty':qty,'algo':algo_name,'fromDate':fromDate,'toDate':toDate,'freq':freq, 'mode':backtest} try: store_algo(algo, algo_name) except: perror('Something went wrong while saving algo') pdebug1(backtest_msg) # Step 2: Store the stock name under backtest in the redis cache for stock in stocks: backtest_cache.set('stock',stock) #TODO: replace # Step 4: Done is set to 0: Backtest is in progress, will be resetted by backtest job backtest_cache.set('done'+cache_type,0) # Step 5: Send the msg to backtest thread to initiate the back test pdebug(json.dumps(backtest_msg)) backtest_cache.publish('kite_simulator'+cache_type,json.dumps(backtest_msg)) # Step 6: Return 0 to reset n_intervals count return 0
def update_trade_log(t, s, p, q, b, e, j): #pinfo("update_trade_log # 1") job = session.query(Jobs).filter(Jobs.job_id == j).first() #pinfo(job.job_id) #pdebug("{},{},{},{},{},{},{}".format(t,s,p,q,b,e,j)) job.trades.append( Trades(timestamp=t, stock=s, price=p, qty=q, buy_or_sell=b, en_or_ex=e, order_id="")) #session.add(trade) try: session.commit() #pinfo("update_trade_log # 2") except Exception as e: pinfo(e)
def toggle_trade(n1, n2, d1, d2): if n2 > 0 and d1 == True: #Trade is onoging: Connected if is_connected() == True: live_cache.publish('kite_ticker_handlerlive', 'CLOSE') pinfo('Stopping Connection') else: pinfo("Connection is already closed") return False, True elif n1 > 0 and d2 == True: # Trade is stopped: Closed if is_connected() == False: live_cache.publish('kite_ticker_handlerlive', 'START') live_cache.set('Kite_Status', 'connecting') pinfo('Start Trade') return True, False return False, True
def sell_limit(kite, symbol, price, quantity=1, tag='freedom_v2'): pinfo("S Limit: {}[{}]=> {}".format(symbol, quantity, price)) #return -1 try: order_id = kite.place_order(tradingsymbol=symbol, exchange=kite.EXCHANGE_NSE, transaction_type=kite.TRANSACTION_TYPE_SELL, quantity=quantity, order_type=kite.ORDER_TYPE_LIMIT, product=kite.PRODUCT_MIS, #trigger_price=round(trigger,1), #trigger_price=round(price,1), price=price, variety=kite.VARIETY_REGULAR, tag=tag) pinfo("Order placed. ID is: {}".format(order_id)) return order_id except: pinfo("Order placement failed: {}".format(sys.exc_info()[0])) return -1
def getOrders(kite): # Fetch all orders pinfo(kite.orders()) return pd.DataFrame(kite.orders())