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]
Example #2
0
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 longer(trader: shift.Trader, tickers):
    today = trader.get_last_trade_time()
    endTime = dt.time(15, 50, 0)
    dayEnd = dt.datetime.combine(today, endTime)
    tickSize = 0.01
    bp = (trader.get_portfolio_summary().get_total_bp())
    dpa = bp / float(len(tickers))

    for t in tickers:
        lastPrice = trader.get_last_price(t)
        while lastPrice == 0:
            lastPrice = trader.get_last_price(t)
        s = int((dpa / lastPrice) / 100)

        for i in range(0, s):
            # limitBuyPrice = lastPrice - tickSize
            limit_sell = shift.Order(shift.Order.Type.MARKET_BUY, t, 1)
            trader.submit_order(limit_sell)

    while trader.get_last_trade_time() < dayEnd:
        time.sleep(1)

    for order in trader.get_waiting_list():
        trader.submit_cancellation(order)

    for t in tickers:
        print(t)
        lastPrice = trader.get_last_price(t)
        item = trader.get_portfolio_item(t)
        if item.get_shares() > 0:
            sell = shift.Order(
                shift.Order.Type.MARKET_SELL, t,
                int(item.get_shares() /
                    100))  # Order size in 100's of shares, strictly as an int
            trader.submit_order(sell)
        elif item.get_shares() < 0:
            buy = shift.Order(
                shift.Order.Type.MARKET_BUY, t,
                int(-1 * item.get_shares() /
                    100))  # Order size in 100's of shares, strictly as an int
            trader.submit_order(buy)
            print(f'submitted buy for {t}')

    time.sleep(15)
    utils.print_portfolio_information(trader)
    utils.print_all_submitted_order(trader)
    print(trader.get_last_trade_time())

    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
Example #5
0
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
Example #6
0
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"))
Example #7
0
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)}
Example #8
0
def run_trades(trader: shift.Trader, state: Dict[str, Any]) -> None:
    """
    run buy / sell trades
    """
    run_trades_interval = 60  # seconds

    while True:
        sleep(run_trades_interval)

        unsorted_differences: List[float] = []
        unsorted_tickers: List[str] = []
        for ticker in tickers:
            prices = np.array(list(state[prices_key][ticker]))
            ema_difference, price_minus_bollinger = get_should_long(prices)
            unsorted_differences.append(ema_difference)
            unsorted_tickers.append(ticker)

        _, ranked_tickers = map(
            list, zip(*sorted(zip(unsorted_differences, unsorted_tickers))))

        for ticker in ranked_tickers:
            prices = np.array(list(state[prices_key][ticker]))
            ema_difference, price_minus_bollinger = get_should_long(prices)
            item = trader.get_portfolio_item(ticker)
            if item.get_shares() > 0:
                # check to sell
                if price_minus_bollinger > 0 or ema_difference < 0:
                    sell = shift.Order(
                        shift.Order.Type.MARKET_SELL, ticker,
                        int(math.ceil((item.get_shares() / 2) / 100.0)))
                    trader.submit_order(sell)
            else:
                for order in trader.get_waiting_list():
                    if order.symbol == ticker and order.type == shift.Order.Type.MARKET_BUY:
                        trader.submit_cancellation(order)
                if ema_difference > 0:
                    bp = trader.get_portfolio_summary().get_total_bp()
                    amount = 200e3
                    if bp >= amount:
                        lastPrice = trader.get_last_price(ticker)
                        s = int((amount / lastPrice) / 100.)
                        buy = shift.Order(shift.Order.Type.MARKET_BUY, ticker,
                                          s)
                        trader.submit_order(buy)
Example #9
0
def get_unrealized_pl(ticker: str, trader: shift.Trader):

    p = trader.get_last_price(ticker)
    item = trader.get_portfolio_item(ticker)
    long_shares = item.get_long_shares()
    short_shares = item.get_short_shares()
    upl = 0

    curr_long_value = long_shares * p
    cost_long = long_shares * item.get_long_price()
    curr_short_value = short_shares * p
    cost_short = short_shares * item.get_short_price()

    
    if cost_long != 0:
        upl += (curr_long_value - cost_long)/float(cost_long)
    if cost_short != 0:
        upl -= (curr_short_value - cost_short)/float(cost_short)

    return upl
Example #10
0
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
    get_data_interval = 60  # seconds
    save_interval = timedelta(
        seconds=1)  # minimum time in between saving to state

    if prices_key not in state:
        state[prices_key] = {}
    last_save_time = datetime.now()
    current_data = []
    while True:
        sleep(get_data_interval)
        current_data.append(trader.get_last_price(ticker))
        curr_time = datetime.now()
        if curr_time > last_save_time + save_interval:
            if ticker not in state[prices_key]:
                state[prices_key][ticker] = deque(maxlen=queue_size)
            state[prices_key][ticker].extend(current_data)
            current_data = []
            last_save_time = curr_time
Example #11
0
def run_trades(trader: shift.Trader, state: Dict[str, Any]) -> None:
    """
    run buy / sell trades
    """
    run_trades_interval = 60 # seconds
    maxLoss = 0.01
    while True:
        # if (len())
        unsorted_differences: List[float] = []
        unsorted_tickers: List[str] = []
        for ticker in tickers:
            print(f"entered run trades: {ticker}")
            if (ticker not in state[prices_key]) or len(list(state[prices_key][ticker])) < 22:
                # print(f"have {len(list(state[prices_key][ticker]))} prices for {ticker}...moving on")
                continue
            prices = np.array(list(state[prices_key][ticker]))
            # print(f"Prices({len(prices)}): {prices} ")
            should_long = get_should_long(prices)
            if(should_long is None):
                # print(f"should_long is None {ticker}")
                continue
            ema_difference = should_long["ema_difference"]
            prev_ema_difference = should_long["prev_ema_difference"]
            # print(f"emaaaaa {ticker}: {ema_difference}")
            unsorted_differences.append(ema_difference)  
            unsorted_tickers.append(ticker)  
        
        if(len(unsorted_differences) < 5):
            sleep(5)
            continue
        print(unsorted_differences)
        print(unsorted_tickers)
        _, ranked_tickers = (reversed(list(t)) for t in zip(*sorted(zip(unsorted_differences, unsorted_tickers))))

        for ticker in ranked_tickers:
            prices = np.array(list(state[prices_key][ticker]))
            should_long = get_should_long(prices)
            if(should_long is None):
                sleep(1)
                continue
            ema_difference = should_long["ema_difference"]
            price_minus_bollinger_high = should_long["bollinger_band_high_difference"]
            price_minus_bollinger_low = should_long["bollinger_band_low_difference"]
            last_upper_bollinger_band = should_long["last_bollinger_band_high"]
            last_lower_bollinger_band = should_long["last_bollinger_band_low"]
            item = trader.get_portfolio_item(ticker)
            if item.get_shares() > 0:
                # check to sell
                target_hit_count = state[target_key][ticker][0]
                if ema_difference < 0:
                    cancel_all_trades(trader, ticker)
                    sleep(2)
                    print(f"{ticker} : HAVE SHARES, EMA CROSSED DOWN, SELL")
                    sell = shift.Order(shift.Order.Type.MARKET_SELL, ticker, int(item.get_shares()/100.0))
                    trader.submit_order(sell)

                # over band, never hit
                elif price_minus_bollinger_high > 0 and target_hit_count == 0:
                    cancel_all_trades(trader, ticker)
                    sleep(2)
                    s = item.get_shares()                    
                    print(f"{ticker} : HAVE SHARES, FIRST TARGET HIT, SELL HALF")
                    sell = shift.Order(shift.Order.Type.MARKET_SELL, ticker, int(math.ceil((s/2) / 100.0)))
                    trader.submit_order(sell)
                    sleep(5)
                    #check if you didn't happen to sell all due to minimum lot
                    if int(math.ceil((item.get_shares()/2) / 100.0)) < int(s/100):

                        lastPrice = trader.get_last_price(ticker)
                        initial_buy_price = item.get_price()
                        #keep track of this in state
                        trailing_stop_perc = (lastPrice - initial_buy_price) / initial_buy_price
                        trailing_stop_price = (1 - trailing_stop_perc) * lastPrice
                        print(f"{ticker} : HAVE SHARES, FIRST TARGET HIT, RESETTING LIMIT SELL")
                        sell = shift.Order(shift.Order.Type.LIMIT_SELL, ticker, int(math.ceil((item.get_shares()/2) / 100.0)), trailing_stop_price)
                        trader.submit_order(sell)
                        state[target_key][ticker] = [target_hit_count + 1, trailing_stop_perc]
                    
            
                elif target_hit_count > 0:
                    sold = 0
                    if price_minus_bollinger_low > 0:
                        cancel_all_trades(trader, ticker)
                        sleep(2)
                        sold = int(math.ceil((item.get_shares()/2) / 100.0))
                        print(f"{ticker} : HAVE SHARES, OVER FIRST TARGET HIT, TAKING MORE PROFIT SINCE STILL ABOVE BOLLINGER, SELL HALFT")
                        sell = shift.Order(shift.Order.Type.MARKET_SELL, ticker, sold)
                        trader.submit_order(sell)
                        sleep(5)
                    if sold < int(item.get_shares()/100):
                        
                        lastPrice = trader.get_last_price(ticker)

                        avg_last_two_prices = (state[prices_key][ticker][-2] + state[prices_key][ticker][-1]) / 2.
                        
                        if lastPrice >= avg_last_two_prices:
                            cancel_all_trades(trader, ticker)
                            sleep(2)
                            # keep same percentarange and update the loss PRICE
                            trailing_stop_perc = state[target_key][ticker][1]
                            trailing_stop_price = (1 - trailing_stop_perc) * lastPrice
                            print(f"{ticker} : HAVE SHARES, OVER FIRST TARGET HIT, SOLD MORE PROFIT SINCE STILL ABOVE BOLLINGER, STILL HAVE MORE, RESETTING LIMIT")
                            sell = shift.Order(shift.Order.Type.LIMIT_SELL, ticker, item.get_shares() / 100.0, trailing_stop_price)
                            trader.submit_order(sell)
                            sleep(5)
                        else:
                            pass
            elif item.get_shares() < 0:
                #check to see if we need to exit short positions
                target_hit_count = state[target_key][ticker][0]

                if ema_difference > 0:
                    cancel_all_trades(trader, ticker)
                    sleep(2)
                    buy = Shift.Order(shift.Order.Type.MARKET_BUY, ticker, -1*int(item.get_shares()/100.0))
                    trader.submit_order(buy)


                elif price_minus_bollinger_low < 0 and target_hit_count == 0:
                    cancel_all_trades(trader, ticker)
                    sleep(2)
                    s = item.get_shares()
                    buy = shift.Order(shift.Order.Type.MARKET_BUY, ticker, -1*int(math.ceil((s/2) / 100.0)))
                    trader.submit_order(buy)
                    sleep(5)
                    #check if you happen to buy all back due to minimum lot
                    #if still have short positions, reset limit buy
                    if -1*int(math.ceil((item.get_shares()/2) / 100.0)) < -1*int(s/100) :
                        lastPrice = trader.get_last_price(ticker)
                        initial_sell_price = item.get_price()
                        trailing_stop_perc = (lastPrice - initial_sell_price) / initial_sell_price
                        trailing_stop_price = (1 + trailing_stop_perc) * lastPrice
                        buy = shift.Order(shift.Order.Type.LIMIT_BUY, ticker, int(math.ceil((item.get_shares()/2) / 100.0)), trailing_stop_price)
                        trader.submit_order(buy)
                        state[target_key][ticker] = [target_hit_count + 1, trailing_stop_perc]

                #no close of position at all, so we just wanna reset the trailing stop loss
                elif target_hit_count > 0:
                    bought = 0
                    if price_minus_bollinger_low < 0:
                        cancel_all_trades(trader, ticker)
                        sleep(2)
                        bought = -1*int(math.ceil((item.get_shares()/2) / 100.0))
                        buy = shift.Order(shift.Order.Type.MARKET_BUY, ticker, bought)
                        trader.submit_order(buy)
                        sleep(5)
                    if bought < -1*int(item.get_shares() / 100.0):
                        lastPrice = trader.get_last_price(ticker)
                        avg_last_two_prices = (state[prices_key][ticker][-2] + state[prices_key][ticker][-1]) / 2.
                        # keep same percentarange and update the loss PRICE
                        #TODO: fix a dollar amount instead of percentage
                        if lastPrice <= avg_last_two_prices:
                            cancel_all_trades(trader, ticker)
                            sleep(2)
                            trailing_stop_perc = state[target_key][1]
                            trailing_stop_price = (1 + trailing_stop_perc) * lastPrice
                            buy = shift.Order(shift.Order.Type.LIMIT_BUY, ticker, item.get_shares() / 100.0, trailing_stop_price)
                            trader.submit_order(buy)
                        else: 
                            pass         
            else:
                #reset target_hit_count because no shores no more
                state[target_key][ticker] = [0,0]
                for order in trader.get_waiting_list():
                    if order.symbol == ticker and order.type == shift.Order.Type.MARKET_BUY:
                        trader.submit_cancellation(order)
                sleep(2)
                if ema_difference > 0 and prev_ema_difference < 0:
                    bp = trader.get_portfolio_summary().get_total_bp()
                    amount = 200e3
                    if bp >= amount:
                        lastPrice = trader.get_last_price(ticker)
                        s = int((amount / lastPrice) / 100.)
                        buy = shift.Order(shift.Order.Type.MARKET_BUY, ticker, s)
                        initial_buy_price = trader.get_last_price(ticker)
                        initial_stop_loss = shift.Order(shift.Order.Type.LIMIT_SELL, ticker, s, trader.get_last_price(ticker)*(1-maxLoss))
                        print(f"{ticker} : DONT HAVE SHARES, HIT TARGET, HAVE BP, BUY")
                        trader.submit_order(buy)
                        sleep(5)
                        print(f"{ticker} : DONT HAVE SHARES, HIT TARGET, HAVE BP, SETTING INITIAL STOP LOSS")
                        trader.submit_order(initial_stop_loss)
                elif ema_difference < 0:
                    bp = trader.get_portfolio_summary().get_total_bp()
                    short_profit, long_profit = get_unrealized_pl(trader)
                    #lost money on shorts
                    amount = (200e3 / 2)
                    amount_to_subtract = 0
                    if short_profit < 0:
                        amount_to_subtract += (-1*short_profit)
                    
                    if (0.995 * (amount - amount_to_subtract)) < bp:
                        lastPrice = trader.get_last_price()
                        s = int((amount / lastPrice) / 100.)
                        sell = shift.Order(shift.Order.Type.MARKET_SELL, ticker, s)
                        initial_sell_price = trader.get_last_price(ticker)
                        initial_stop_loss = shift.Order(shift.Order.Type.LIMIT_BUY, ticker, trader.get_last_price(ticker)*(1+maxLoss), s)
                        trader.submit_order(sell)
                        sleep(5)
                        trader.submit_order(initial_stop_loss)

            sleep(5)
        sleep(run_trades_interval)
def run_trades(trader: shift.Trader, state: Dict[str, Any]) -> None:
    """
    run buy / sell trades
    """
    run_trades_interval = 30  # seconds
    maxLoss = 0.004
    maxGain = 0.004
    while True:

        unsorted_differences: List[float] = []
        unsorted_tickers: List[str] = []
        for ticker in tickers:
            if (ticker not in state[prices_key]) or len(
                    list(state[prices_key][ticker])) < 21:
                sleep(5)
                continue
            prices = np.array(list(state[prices_key][ticker]))
            should_long = get_should_long(prices)
            ema_difference = should_long["ema_difference"]
            unsorted_differences.append(ema_difference)
            unsorted_tickers.append(ticker)

        if ticker == "AAPL":
            print("PRE UNPACKING")
            print(unsorted_differences)
            print(unsorted_tickers)
            print((list(t) for t in zip(
                *sorted(zip(unsorted_differences, unsorted_tickers)))))

        _, ranked_tickers = (list(t) for t in zip(
            *sorted(zip(unsorted_differences, unsorted_tickers))))

        for ticker in ranked_tickers:
            prices = np.array(list(state[prices_key][ticker]))
            should_long = get_should_long(prices)
            ema_difference = should_long["ema_difference"]
            price_minus_bollinger_high = should_long[
                "bollinger_band_high_difference"]
            price_minus_bollinger_low = should_long[
                "bollinger_band_low_difference"]
            last_upper_bollinger_band = should_long["last_bollinger_band_high"]
            last_lower_bollinger_band = should_long["last_bollinger_band_low"]
            item = trader.get_portfolio_item(ticker)
            if item.get_shares() > 0:
                # check to sell
                target_hit_count = state[target_key][ticker][0]
                if ema_difference < 0:
                    cancel_all_trades(trader, ticker)
                    sell = shift.Order(shift.Order.Type.MARKET_SELL, ticker,
                                       int(item.get_shares() / 100.0))
                    trader.submit_order(sell)
                elif price_minus_bollinger_high > 0 and target_hit_count == 0:
                    # over band, never hit
                    cancel_all_trades(trader, ticker)
                    s = item.get_shares()
                    sell = shift.Order(shift.Order.Type.MARKET_SELL, ticker,
                                       int(math.ceil((s / 2) / 100.0)))
                    trader.submit_order(sell)

                    #check if you happen to sell all due to minimum lot
                    #if still have long positions, reset limit sell
                    if int(math.ceil(
                        (item.get_shares() / 2) / 100.0)) < int(s / 100):
                        lastPrice = trader.get_last_price(ticker)
                        initial_buy_price = item.get_price()
                        trailing_stop_perc = (
                            lastPrice - initial_buy_price) / initial_buy_price
                        trailing_stop_price = (1 -
                                               trailing_stop_perc) * lastPrice
                        sell = shift.Order(
                            shift.Order.Type.LIMIT_SELL, ticker,
                            int(math.ceil((item.get_shares() / 2) / 100.0)),
                            trailing_stop_price)
                        trader.submit_order(sell)
                        #keep track of this in state
                        state[target_key][ticker] = [
                            target_hit_count + 1, trailing_stop_perc
                        ]

                elif target_hit_count > 0:
                    sold = 0
                    if price_minus_bollinger_high > 0:
                        cancel_all_trades(trader, ticker)
                        sold = int(math.ceil((item.get_shares() / 2) / 100.0))
                        sell = shift.Order(shift.Order.Type.MARKET_SELL,
                                           ticker, sold)
                        trader.submit_order(sell)
                    if sold < int(item.get_shares() / 100):

                        lastPrice = trader.get_last_price(ticker)

                        avg_last_two_prices = (
                            state[prices_key][ticker][-2] +
                            state[prices_key][ticker][-1]) / 2.
                        #we have shares, hits target for 2nd time,  and price > upper bo, and we took 1/2 profit, we still have more
                        if lastPrice >= avg_last_two_prices:
                            cancel_all_trades(trader, ticker)
                            # keep same percentarange and update the loss PRICE
                            #TODO: fix a dollar amount instead of percentage
                            trailing_stop_perc = state[target_key][ticker][1]
                            trailing_stop_price = (
                                1 - trailing_stop_perc) * lastPrice
                            sell = shift.Order(shift.Order.Type.LIMIT_SELL,
                                               ticker,
                                               item.get_shares() / 100.0,
                                               trailing_stop_price)
                            trader.submit_order(sell)
                        else:
                            pass

            #comment this if you want to yeet the short logic
            elif item.get_shares() < 0:
                #check to see if we need to exit short positions
                target_hit_count = state[target_key][ticker][0]

                if ema_difference > 0:
                    cancel_all_trades(trader, ticker)
                    buy = Shift.Order(shift.Order.Type.MARKET_BUY, ticker,
                                      -1 * int(item.get_shares() / 100.0))
                    trader.submit_order(buy)

                elif price_minus_bollinger_low < 0 and target_hit_count == 0:
                    cancel_all_trades(trader, ticker)
                    s = item.get_shares()
                    buy = shift.Order(shift.Order.Type.MARKET_BUY, ticker,
                                      -1 * int(math.ceil((s / 2) / 100.0)))
                    trader.submit_order(buy)

                    #check if you happen to buy all back due to minimum lot
                    #if still have short positions, reset limit buy
                    if -1 * int(math.ceil(
                        (item.get_shares() / 2) / 100.0)) < -1 * int(s / 100):
                        lastPrice = trader.get_last_price(ticker)
                        initial_sell_price = item.get_price()
                        trailing_stop_perc = (lastPrice - initial_sell_price
                                              ) / initial_sell_price
                        trailing_stop_price = (1 +
                                               trailing_stop_perc) * lastPrice
                        buy = shift.Order(
                            shift.Order.Type.LIMIT_BUY, ticker,
                            int(math.ceil((item.get_shares() / 2) / 100.0)),
                            trailing_stop_price)
                        trader.submit_order(buy)
                        state[target_key][ticker] = [
                            target_hit_count + 1, trailing_stop_perc
                        ]

                #no close of position at all, so we just wanna reset the trailing stop loss
                elif target_hit_count > 0:
                    bought = 0
                    if price_minus_bollinger_low < 0:
                        cancel_all_trades(trader, ticker)
                        bought = -1 * int(
                            math.ceil((item.get_shares() / 2) / 100.0))
                        buy = shift.Order(shift.Order.Type.MARKET_BUY, ticker,
                                          bought)
                        trader.submit_order(buy)
                    if bought < -1 * int(item.get_shares() / 100.0):
                        lastPrice = trader.get_last_price(ticker)
                        avg_last_two_prices = (
                            state[prices_key][ticker][-2] +
                            state[prices_key][ticker][-1]) / 2.
                        # keep same percentarange and update the loss PRICE
                        #TODO: fix a dollar amount instead of percentage
                        if lastPrice <= avg_last_two_prices:
                            cancel_all_trades(trader, ticker)
                            trailing_stop_perc = state[target_key][1]
                            trailing_stop_price = (
                                1 + trailing_stop_perc) * lastPrice
                            buy = shift.Order(shift.Order.Type.LIMIT_BUY,
                                              ticker,
                                              item.get_shares() / 100.0,
                                              trailing_stop_price)
                            trader.submit_order(buy)
                        else:
                            pass

            else:
                #reset target_hit_count because no shares no more
                state[target_key][ticker] = [0, 0]
                for order in trader.get_waiting_list():
                    if order.symbol == ticker and order.type == shift.Order.Type.MARKET_BUY:
                        trader.submit_cancellation(order)
                    if order.symbol == ticker and order.type == shift.Order.Type.MARKET_SELL:
                        trader.submit_cancellation(order)
                if ema_difference > 0:
                    bp = trader.get_portfolio_summary().get_total_bp()
                    amount = 200e3
                    if bp >= amount:
                        lastPrice = trader.get_last_price(ticker)
                        s = int((amount / lastPrice) / 100.)
                        buy = shift.Order(shift.Order.Type.MARKET_BUY, ticker,
                                          s)
                        initial_buy_price = trader.get_last_price(ticker)
                        initial_stop_loss = shift.Order(
                            shift.Order.Type.LIMIT_SELL, ticker,
                            trader.get_last_price(ticker) * (1 - maxLoss), s)
                        trader.submit_order(buy)
                        trader.submit_order(initial_stop_loss)
                #comment this if you want to yeet the short logic
                elif ema_difference < 0:
                    bp = trader.get_portfolio_summary().get_total_bp()
                    short_profit, long_profit = get_unrealized_pl(trader)
                    #lost money on shorts
                    amount = (200e3 / 2)
                    amount_to_subtract = 0
                    if short_profit < 0:
                        amount_to_subtract += (-1 * short_profit)

                    if (0.995 * (amount - amount_to_subtract)) < bp:
                        lastPrice = trader.get_last_price()
                        s = int((amount / lastPrice) / 100.)
                        sell = shift.Order(shift.Order.Type.MARKET_SELL,
                                           ticker, s)
                        initial_sell_price = trader.get_last_price(ticker)
                        initial_stop_loss = shift.Order(
                            shift.Order.Type.LIMIT_BUY, ticker,
                            trader.get_last_price(ticker) * (1 + maxLoss), s)
                        trader.submit_order(sell)
                        trader.submit_order(initial_stop_loss)

                    #
                    # check to see if we should enter short position
                    pass
        sleep(run_trades_interval)