def build_candles(ticker: str, trader: shift.Trader, state: Dict[str, Any], end_time): queue_size = 30 while trader.get_last_trade_time() < end_time: s = 0 price = trader.get_last_price(ticker) candle = Candle(price, price, price, price) while s < candle_size: price = trader.get_last_price(ticker) if price < candle.low: candle.setLow(price) if price > candle.high: candle.setHigh(price) sleep(1) s += 1 price = trader.get_last_price(ticker) candle.setClose(price) try: state[candles_key][ticker] += [candle] except KeyError: state[candles_key][ticker] = deque(maxlen=queue_size) sleep(0.5) state[candles_key][ticker] += [candle]
def run_save_prices(ticker: str, trader: shift.Trader, state: Dict[str, Any]) -> None: """ save prices for a given ticker to the state """ queue_size = 30 frequency = 60 # if prices_key not in state: # state[prices_key] = {} print = False while True: price = trader.get_last_price(ticker) try: state[prices_key][ticker] += [trader.get_last_price(ticker)] except KeyError: state[prices_key][ticker] = deque(maxlen=queue_size) sleep(0.5) state[prices_key][ticker] += [trader.get_last_price(ticker)] # # print(f"Prices Stored: {state[prices_key][ticker]}") # print(f"Last Price: {trader.get_last_price(ticker)}") # print(f"updated prices for AAPL @ {trader.get_last_trade_time()} there are {len(state[prices_key][ticker])} entries for price - last price {price}") # print(f"{ticker} PRICE UPDATED") sleep(frequency)
def get_unrealized_short_pnl(trader: shift.Trader): total_unrealized_short_pnl = 0 for item, value in trader.get_portfolio_items().items(): if(value.get_shares() < 0): total_unrealized_short_pnl += trader.get_unrealized_pl(item) return total_unrealized_short_pnl
def portfolioSummary(trader: shift.Trader): """Takes Trader Object and Prints Summary of Portfolio to Console""" print("Buying Power\tTotal Shares\tTotal P&L\tTimestamp") print("%12.2f\t%12d\t%9.2f\t%26s" % ( trader.get_portfolio_summary().get_total_bp(), trader.get_portfolio_summary().get_total_shares(), trader.get_portfolio_summary().get_total_realized_pl(), trader.get_portfolio_summary().get_timestamp(), )) print() print("Symbol\t\tShares\t\tPrice\t\t P&L\tTimestamp") for item in trader.get_portfolio_items().values(): print("%6s\t\t%6d\t%9.2f\t%9.2f\t%26s" % ( item.get_symbol(), item.get_shares(), item.get_price(), item.get_realized_pl(), item.get_timestamp(), )) print() return
def run_mm_short(ticker: str, trader: shift.Trader, end_time): minimum_spread = 0.02 maximum_allocation = 0.1 while trader.get_last_trade_time() < end_time: sleep(frequency) item = trader.get_portfolio_item(ticker) short_shares = item.get_short_shares() ask,bid,mid = get_prices(ticker) if int(ask) == 0 or int(bid) == 0: continue spread = (ask-bid) portfolio_value_of_ticker = (short_shares*mid) allocation = maximum_allocation*1000000 if allocation > portfolio_value_of_ticker: lots = 3 price=ask if spread < minimum_spread: price += 0.01 order = place_limit_order(shift.Order.Type.LIMIT_SELL, ticker, lots, price) check_order(order, trader) else: continue
def buy_ticker(self, trader: shift.Trader, tickers, buy_order_size): lg.debug('buy_tickers :' + str(tickers)) for ticker in tickers: ticker_buy = shift.Order(shift.Order.Type.MARKET_BUY, ticker, buy_order_size) trader.submit_order(ticker_buy) lg.debug('ticker bought:' + str(ticker))
def run_mm_long(ticker: str, trader: shift.Trader, end_time): minimum_spread = 0.02 maximum_allocation = 0.15 while trader.get_last_trade_time() < end_time: sleep(frequency) item = trader.get_portfolio_item(ticker) shares = item.get_shares() ask,bid,mid = get_prices(ticker) if bid == 0 or ask == 0: continue spread = (ask-bid) portfolio_value_of_ticker = shares*mid allocation = maximum_allocation*1000000 if allocation > portfolio_value_of_ticker: lots = 3 price = bid if spread < minimum_spread: price -= 0.01 order = place_limit_order(shift.Order.Type.LIMIT_BUY, ticker, lots, price) status = get_order_status(order) check_order(order, trader) else: continue
def buy_back_shorted(ticker: str, trader: shift.Trader): item = trader.get_portfolio_item(ticker) while(item.get_shares() < 0): orders_placed = place_orders(shift.Order.Type.MARKET_BUY,ticker, int(-1* item.get_shares() / 100)) sleep(10) item = trader.get_portfolio_item(ticker) print(f'submitted buy for {ticker}')
def sell_ticker(self, trader: shift.Trader, tickers, sell_order_size): lg.debug('sell_tickers :' + str(tickers)) for ticker in tickers: # if ticker == 'VIXY': # order_size = 100 ticker_sell = shift.Order(shift.Order.Type.MARKET_SELL, ticker, sell_order_size) trader.submit_order(ticker_sell) lg.debug('ticker sold:' + str(ticker))
def update_open_interest(trader: shift.Trader, ls, open_interest, order_type): if order_type == "ask": o_i = [trader.get_best_price(sym).get_ask_size() for sym in ls] open_interest.loc[trader.get_last_trade_time(), :] = o_i if order_type == "bid": o_i = [trader.get_best_price(sym).get_bid_size() for sym in ls] open_interest.loc[trader.get_last_trade_time(), :] = o_i return open_interest
def limit_order(trader: shift.Trader, order_type, symbol, contract_size, limit_price): if order_type == "buy": limit_buy = shift.Order(shift.Order.Type.LIMIT_BUY, symbol, contract_size, limit_price) trader.submit_order(limit_buy) if order_type == "sell": limit_sell = shift.Order(shift.Order.Type.LIMIT_SELL, symbol, contract_size, limit_price) trader.submit_order(limit_sell) return
def sell_long(ticker: str, trader: shift.Trader): item = trader.get_portfolio_item(ticker) while(item.get_shares() > 0): orders_placed = place_orders(shift.Order.Type.MARKET_SELL,ticker, int(item.get_shares() / 100)) sleep(10) item = trader.get_portfolio_item(ticker) # sell = shift.Order(shift.Order.Type.MARKET_SELL,ticker, int(item.get_shares() / 100)) # Order size in 100's of shares, strictly as an int # trader.submit_order(sell) print(f'submitted sell for {ticker}')
def market_order(trader: shift.Trader, order_type, symbol, contract_size): if order_type == "buy": market_buy = shift.Order(shift.Order.Type.MARKET_BUY, symbol, contract_size) trader.submit_order(market_buy) if order_type == "sell": market_sell = shift.Order(shift.Order.Type.MARKET_SELL, symbol, contract_size) trader.submit_order(market_sell) return
def check_order(order, trader: shift.Trader): sleep(1) status = get_order_status(order) tries = 0 while status != shift.Order.Status.REJECTED and status != shift.Order.Status.FILLED and tries < 10: sleep(1) tries += 1 status = get_order_status(order) if status != shift.Order.Status.REJECTED and status != shift.Order.Status.FILLED: trader.submit_cancellation(order)
def closePositions(trader: shift.Trader, ticker): # Cancel pending orders print("Waiting list size:", trader.get_waiting_list_size()) for order in trader.get_waiting_list(): if order.symbol == ticker: trader.submit_cancellation(order) print("All", ticker, "pending orders cancelled" ) # Cancel open orders before submitting closing orders # Close / Cover all open positions #portfolioSummary(trader) # Print summary of portfolio**************************************************************************Good for developing item = trader.get_portfolio_item(ticker) if item.get_shares() > 0: closeLong = shift.Order( shift.Order.Type.MARKET_SELL, item.get_symbol(), int(item.get_shares() / 100)) # Order size in 100's of shares, strictly as an int trader.submit_order(closeLong) #print("Close all long positions") elif item.get_shares() < 0: coverShort = shift.Order(shift.Order.Type.MARKET_BUY, item.get_symbol(), int(item.get_shares() / -100)) trader.submit_order(coverShort) #print("Close all short positions") print("All", ticker, "closing orders submitted") return
def market_maker_one(trader: shift.Trader, ticker: str): tickSize = 0.01 # james code need to change maybe? today = trader.get_last_trade_time() endTime = dt.time(15, 30, 0) dayEnd = dt.datetime.combine(today, dt.datetime(endTime)) rightNow = trader.get_last_trade_time() #right < the end of day at 3:50 while today < dayEnd: ''' check inventory here ''' trader.sub_all_order_book() lastPrice = trader.get_last_price("AAPL") limitBuyPrice = lastPrice - tickSize limitSellPrice = lastPrice + tickSize limit_buy = shift.Order(shift.Order.Type.LIMIT_BUY, "AAPL", 1, limitBuyPrice) limit_sell = shift.Order(shift.Order.Type.LIMIT_SELL, "AAPL", 1, limitSellPrice) # market_buy = shift.Order(shift.Order.Type.MARKET_BUY, "AAPL", 1) # trader.submit_order(market_buy) trader.submit_order(limit_buy) trader.submit_order(limit_sell) time.sleep(10) return
def algo_1(trader: shift.Trader): '''Moving average algorithm''' print(trader.get_last_price("MSFT")) best_price = trader.get_best_price("MSFT") print(f"ask price: {best_price.get_ask_price()}") print(f"local ask: {best_price.get_local_ask_price()}") print(f"global ask: {best_price.get_global_ask_price()}") print(f"bid price: {best_price.get_bid_price()}") print(f"local bid: {best_price.get_local_bid_price()}") print(f"global bid: {best_price.get_global_bid_price()}") print(trader.get_close_price("MSFT"))
def demo_01(trader: shift.Trader): """ This method submits a limit buy order by indicating order type, symbol, size, and limit price. :param trader: :return: """ limit_buy = shift.Order(shift.Order.Type.LIMIT_BUY, "AAPL", 1, 10.00) trader.submit_order(limit_buy) return
def get_unrealized_pl(ticker: str, trader: shift.Trader): p = trader.get_last_price(ticker) item = trader.get_portfolio_item(ticker) upl = -1 if item.get_shares() < 0 else 1 currValue = item.get_shares() * p cost = item.get_shares() * item.get_price() if cost == 0: return 0 upl = upl*((currValue - cost)/cost) return upl
def manage_inventory(ticker: str, trader: shift.Trader, end_time): while trader.get_last_trade_time() < end_time: sleep(frequency) upl = get_unrealized_pl(ticker, trader) item = trader.get_portfolio_item(ticker) if int(item.get_price()) != 0: if upl >= 0.4 or upl <= -0.2: print(f"Closing positions on {ticker} for {'loss' if upl <= -0.2 else 'profit'}") if item.get_shares() > 0: sell_long(ticker) elif item.get_shares() < 0: buy_back_shorted(ticker)
def get_unrealized_pnl(trader: shift.Trader): short_profit = 0 long_profit = 0 for item, value in ziplist(trader.get_portfolio_items().keys(), trader.get_portfolio_items().values()): pnl = trader.get_unrealized_pl(item) #in short if value.get_shares() < 0: short_profit += pnl if value.get_shares() > 0: long_profit += pnl return short_profit, long_profit
def collect_data(trader: shift.Trader, ticker: str): today = trader.get_last_trade_time() print(today) endTime = dt.time(9, 35, 0) end_of_data_collection_period = dt.datetime.combine(today, endTime) prices = [] while (trader.get_last_trade_time() < end_of_data_collection_period): prices.append(trader.get_last_price(ticker)) print(trader.get_last_trade_time()) time.sleep(5) return {"prices": prices, **calculate_statistics(prices)}
def demo_02(trader: shift.Trader): """ This method submits 2 limit buy orders by indicating order type, symbol, size, and limit price. :param trader: :return: """ aapl_limit_buy = shift.Order(shift.Order.Type.LIMIT_BUY, "AAPL", 10, 10.00) trader.submit_order(aapl_limit_buy) xom_limit_buy = shift.Order(shift.Order.Type.LIMIT_BUY, "XOM", 10, 10.00) trader.submit_order(xom_limit_buy) return
def demo_08(trader: shift.Trader): """ This method shows how to submit market sell orders. :param trader: :return: """ aapl_market_sell = shift.Order(shift.Order.Type.MARKET_SELL, "AAPL", 1) trader.submit_order(aapl_market_sell) xom_market_sell = shift.Order(shift.Order.Type.MARKET_SELL, "XOM", 1) trader.submit_order(xom_market_sell) return
def demo_06(trader: shift.Trader): """ This method shows how to submit market buy orders. :param trader: :return: """ aapl_market_buy = shift.Order(shift.Order.Type.MARKET_BUY, "AAPL", 1) trader.submit_order(aapl_market_buy) xom_market_buy = shift.Order(shift.Order.Type.MARKET_BUY, "XOM", 1) trader.submit_order(xom_market_buy) return
def demo_09(self, trader: shift.Trader): """ This method prints all submitted orders information. :param trader: :return: """ lg.debug( "Symbol\t\t\t\tType\t Price\t\tSize\tExecuted\tID\t\t\t\t\t\t\t\t\t\t\t\t\t\t Status\t\tTimestamp" ) for order in trader.get_submitted_orders(): if order.status == shift.Order.Status.FILLED: price = order.executed_price else: price = order.price lg.debug("%6s\t%16s\t%7.2f\t\t%4d\t\t%4d\t%36s\t%23s\t\t%26s" % ( order.symbol, order.type, price, order.size, order.executed_size, order.id, order.status, order.timestamp, )) return
def demo_04(trader: shift.Trader): """ This method prints all current waiting orders information. :param trader: :return: """ print( "Symbol\t\t\t\tType\t Price\t\tSize\tExecuted\tID\t\t\t\t\t\t\t\t\t\t\t\t\t\t Status\t\tTimestamp" ) for o in trader.get_waiting_list(): print( "%6s\t%16s\t%7.2f\t\t%4d\t\t%4d\t%36s\t%23s\t\t%26s" % ( o.symbol, o.type, o.price, o.size, o.executed_size, o.id, o.status, o.timestamp, ) ) return
def demo_07(trader: shift.Trader): """ This method provides information on the structure of PortfolioSummary and PortfolioItem objects: get_portfolio_summary() returns a PortfolioSummary object with the following data: 1. Total Buying Power (get_total_bp()) 2. Total Shares (get_total_shares()) 3. Total Realized Profit/Loss (get_total_realized_pl()) 4. Timestamp of Last Update (get_timestamp()) get_portfolio_items() returns a dictionary with "symbol" as keys and PortfolioItem as values, with each providing the following information: 1. Symbol (get_symbol()) 2. Shares (get_shares()) 3. Price (get_price()) 4. Realized Profit/Loss (get_realized_pl()) 5. Timestamp of Last Update (get_timestamp()) :param trader: :return: """ print("Buying Power\tTotal Shares\tTotal P&L\tTimestamp") print( "%12.2f\t%12d\t%9.2f\t%26s" % ( trader.get_portfolio_summary().get_total_bp(), trader.get_portfolio_summary().get_total_shares(), trader.get_portfolio_summary().get_total_realized_pl(), trader.get_portfolio_summary().get_timestamp(), ) ) print() print("Symbol\t\tShares\t\tPrice\t\t P&L\tTimestamp") for item in trader.get_portfolio_items().values(): print( "%6s\t\t%6d\t%9.2f\t%9.2f\t%26s" % ( item.get_symbol(), item.get_shares(), item.get_price(), item.get_realized_pl(), item.get_timestamp(), ) ) return
def waiting_list_updated_cb(trader: shift.Trader): if trader.get_waiting_list_size() > 0: waiting_list = trader.get_waiting_list() print("Waiting List:") for order in waiting_list: print("%6s\t%21s\t%7.2f\t\t%4d\t\t%4d\t%36s\t%28s\t%26s" % ( order.symbol, order.type, order.price, order.size, order.executed_size, order.id, order.status, order.timestamp, )) else: print("Waiting List Empty!")
def demo_03(trader: shift.Trader): """ This method prints the local bid order book for corresponding symbols. :param trader: :return: """ print("AAPL:") print(" Price\t\tSize\t Dest\t\tTime") for o in trader.get_order_book("AAPL", shift.OrderBookType.LOCAL_BID): print("%7.2f\t\t%4d\t%6s\t\t%19s" % (o.price, o.size, o.destination, o.time)) print() print("XOM:") print(" Price\t\tSize\t Dest\t\tTime") for o in trader.get_order_book("XOM", shift.OrderBookType.LOCAL_BID): print("%7.2f\t\t%4d\t%6s\t\t%19s" % (o.price, o.size, o.destination, o.time))