Example #1
0
def sell(quantity, symbol, limit):
    if limit is not None:
        ui.success(f"\nSelling {quantity} of {symbol} at ${limit}\n")
        result = rh.order_sell_limit(symbol, quantity, limit)
    else:
        ui.success(f'\nSelling {quantity} of {symbol} at market price....\n')
        result = rh.order_sell_market(symbol, quantity)
    ui.chec_ref(result)
Example #2
0
def sell(quantity, symbol, limit):
    if limit is not None:
        ui.success("Selling {} of {} at {}".format(quantity, symbol, limit))
        result = rh.order_sell_limit(symbol, quantity, limit)
    else:
        # market order
        ui.success("Selling {} of {} at market price".format(quantity, symbol))
        result = rh.order_sell_market(symbol, quantity)
    if 'ref_id' in result:
        ui.success(result)
    else:
        ui.error(result)
def sell_old_stocks():
    divies = [[x.get('instrument'), x.get('record_date')] for x in r.get_dividends()]
    positions_data = r.get_current_positions()
    for position in positions_data:
        for d in divies:
            if position.get('instrument') in d[0]:
                about = r.request_get(position['instrument'])
                div_diff = (datetime.strptime(d[1], '%Y-%m-%d') - today).days
                if div_diff <= 0:
                    stock_dict = r.stocks.get_stock_quote_by_symbol(about.get('symbol'))
                    last_trade_price = float(stock_dict.get('last_trade_price'))
                    if last_trade_price / float(position['average_buy_price']) > 1.005:
                        if float(position.get('shares_held_for_sells')) == 0:
                            if easygui.ccbox(msg=about.get('symbol') + '\n' + d[1] + '\nQuantity: ' + str(position['quantity']) + '\nPurchase $' + str(float(position['average_buy_price'])) + '\nCurrent price $' + str(last_trade_price) + '\nProfit per $' + str(float(last_trade_price) - float(position['average_buy_price'])) + '\nTotal win $' + str((float(last_trade_price) - float(position['average_buy_price']))*float(position['quantity'])) + '\nROI ' + str(100 - (float(last_trade_price) / float(position['average_buy_price']))*-100) + '%'  ):
                                r.order_sell_limit(about.get('symbol'), position['quantity'], round(last_trade_price*1.0035, 2))
                                print('selling ', about.get('symbol'))
                else:
                    stock_dict = r.stocks.get_stock_quote_by_symbol(about.get('symbol'))
                    last_trade_price = float(stock_dict.get('last_trade_price'))
                    if last_trade_price / float(position['average_buy_price']) > 1.015:
                        if float(position.get('shares_held_for_sells')) == 0:
                            if easygui.ccbox(msg='NO DIVVIE SALE\n' +about.get('symbol') + '\n' + d[1] + '\nQuantity: ' + str(position['quantity']) + '\nPurchase $' + str(float(position['average_buy_price'])) + '\nCurrent price $' + str(last_trade_price) + '\nProfit per $' + str(float(last_trade_price) - float(position['average_buy_price'])) + '\nTotal win $' + str((float(last_trade_price) - float(position['average_buy_price'])) * float(position['quantity'])) + '\nROI ' + str(100 - (float(last_trade_price) / float(position['average_buy_price'])) * -100) + '%'):
                                r.order_sell_limit(about.get('symbol'), position['quantity'], round(last_trade_price * 1.0035, 2))
                                print('selling ', about.get('symbol'))
def sell(quantity,symbol,limit):
    if limit is not None:
         click.echo(click.style("Selling {} of {} at ${}".format(quantity,symbol,limit), fg = "green", bold = True))
         result = rh.order_sell_limit(symbol,quantity,limit)
         
    else:
        click.echo(click.style("Selling {} of {} at market value".format(quantity,symbol), fg = "green", bold = True))
        result = rh.order_sell_market(symbol,quantity)
    
    
    
    if 'detail' in result:
        red_msg = click.style("ERROR",fg="red",blink = True,bold = True)
        print(red_msg)
    else:
        click.style(str(result),fg = "green",bold = True)
Example #5
0
def sell(quantity, symbol, limit=None):
    content = open('config.json').read()
    config = json.loads(content)
    rh.login(config['username'], config['password'])
    
    if limit is not None:
        ui.success("Selling {} of {} at ${}".format(quantity, symbol, limit))
        result = rh.order_sell_limit(symbol, quantity, limit)
    else:
        ui.success("Selling  {} of {}".format(quantity, symbol))
        result = rh.order_sell_market(symbol, quantity)
    ui.success(result)

    if 'detail' in result:
        ui.error(result)
    else:
        ui.success(result)
Example #6
0
def sell_stock_units(stockName, quantity, price):

    count = 0
    stockOrdered = False
    while stockOrdered == False and count < orderRetries:
        orderStatus = rs.order_sell_limit(stockName,
                                          quantity,
                                          price,
                                          timeInForce='gfd',
                                          extendedHours=True)
        logging.debug(f'Order Status is {orderStatus}')
        sleep(1)
        stockOrdered = order_status(orderStatus['url'])
        count = count + 1
    # End of While
    if stockOrdered == False:
        logging.info(f'Order not placed. Maximum retries reached')
    # End of If
    return stockOrdered
Example #7
0
    async def run(self):
        r.login(os.getenv('ROBINHOOD_USERNAME'),
                os.getenv('ROBINHOOD_PASSWORD'))
        limit_price, stop_price, quantity, amountInDollars = 1.0, 1.0, 1, 1.0
        buy_sell = 'N/A'
        if '$order ' in self.content:
            stock = self.content.replace('$order ', '').upper().split()
            symbol, quantity, buy_sell, limit_price, stop_price, timeout_code = stock
            confirmation = r.order(str(symbol), int(quantity),
                                   (str(buy_sell)).lower(), float(limit_price),
                                   float(stop_price),
                                   (str(timeout_code)).lower())

        elif '$order_buy_market ' in self.content:
            stock = self.content.replace('$order_buy_market ',
                                         '').upper().split()
            symbol, quantity, timeout_code = stock
            confirmation = r.order_buy_market(str(symbol), int(quantity),
                                              str(timeout_code).lower())

        elif '$order_sell_market ' in self.content:
            stock = self.content.replace('$order_sell_market ',
                                         '').upper().split()
            symbol, quantity, buy_sell, limit_price, stop_price, timeout_code = stock
            confirmation = r.order_sell_market(str(symbol), int(quantity),
                                               str(timeout_code).lower())

        elif '$order_buy_limit ' in self.content:
            stock = self.content.replace('$order_buy_limit ',
                                         '').upper().split()
            symbol, quantity, limit_price, timeout_code = stock
            confirmation = r.order_buy_limit(str(symbol), int(quantity),
                                             float(limit_price),
                                             str(timeout_code).lower())

        elif '$order_sell_limit ' in self.content:
            stock = self.content.replace('$order_sell_limit ',
                                         '').upper().split()
            symbol, quantity, limit_price, timeout_code = stock
            confirmation = r.order_sell_limit(str(symbol), int(quantity),
                                              float(limit_price),
                                              str(timeout_code).lower())

        elif '$order_buy_stop_loss ' in self.content:
            stock = self.content.replace('$order_buy_stop_loss ',
                                         '').upper().split()
            symbol, quantity, stop_price, timeout_code = stock
            confirmation = r.order_buy_stop_loss(str(symbol), int(quantity),
                                                 float(stop_price),
                                                 str(timeout_code).lower())

        elif '$order_sell_stop_loss ' in self.content:
            stock = self.content.replace('$order_sell_stop_loss ',
                                         '').upper().split()
            symbol, quantity, stop_price, timeout_code = stock
            confirmation = r.order_sell_stop_loss(str(symbol), int(quantity),
                                                  float(stop_price),
                                                  str(timeout_code).lower())

        elif '$order_buy_trailing_stop ' in self.content:
            stock = self.content.replace('$order_buy_trailing_stop ',
                                         '').upper().split()
            symbol, quantity, trailAmount, trailType, timeout_code = stock
            confirmation = r.order_buy_trailing_stop(str(symbol),
                                                     int(quantity),
                                                     float(trailAmount),
                                                     (str(trailType)).lower(),
                                                     str(timeout_code).lower())

        elif '$order_sell_trailing_stop ' in self.content:
            stock = self.content.replace('$order_sell_trailing_stop ',
                                         '').upper().split()
            symbol, quantity, trailAmount, trailType, timeout_code = stock
            confirmation = r.order_sell_trailing_stop(
                str(symbol), int(quantity), float(trailAmount), str(trailType),
                str(timeout_code).lower())

        elif '$order_sell_stop_limit ' in self.content:
            stock = self.content.replace('$order_sell_stop_limit ',
                                         '').upper().split()
            symbol, quantity, limit_price, stop_price, timeout_code = stock
            confirmation = r.order_sell_stop_limit(str(symbol), int(quantity),
                                                   float(limit_price),
                                                   float(stop_price),
                                                   (str(timeout_code)).lower())

        elif '$order_buy_crypto_limit_by_price ' in self.content:
            stock = self.content.replace('$order_buy_crypto_limit_by_price ',
                                         '').upper().split()
            symbol, amountInDollars, limit_price, timeout_code = stock
            print(str(symbol), float(amountInDollars), float(limit_price),
                  (str(timeout_code)).lower())
            confirmation = r.order_buy_crypto_limit_by_price(
                str(symbol), float(amountInDollars), float(limit_price),
                (str(timeout_code)).lower())

        elif '$order_buy_crypto_by_quantity ' in self.content:
            stock = self.content.replace('$order_buy_crypto_by_quantity ',
                                         '').upper().split()
            symbol, quantity, timeout_code = stock
            confirmation = r.order_buy_crypto_by_quantity(
                str(symbol), int(quantity), (str(timeout_code)).lower())

        elif '$order_sell_crypto_limit_by_price ' in self.content:
            stock = self.content.replace('$order_sell_crypto_limit_by_price ',
                                         '').upper().split()
            symbol, amountInDollars, limit_price, timeout_code = stock
            confirmation = r.order_sell_crypto_limit_by_price(
                str(symbol), float(amountInDollars), float(limit_price),
                (str(timeout_code)).lower())

        elif 'order_sell_crypto_limit ' in self.content:
            stock = self.content.replace('$order_buy_crypto_by_quantity ',
                                         '').upper().split()
            symbol, quantity, limit_price, timeout_code = stock
            confirmation = r.order_sell_crypto_limit(
                str(symbol), int(quantity), float(limit_price),
                (str(timeout_code)).lower())
        print(confirmation)
        message = order_information(symbol, quantity, buy_sell, limit_price,
                                    stop_price, timeout_code)

        if 'id' not in confirmation:
            message = create_simple_message(
                '❌ Order Failed - Details',
                [j for i, j in confirmation.items()])

        self.response.add_response(message)

        if len(self.response.response) == 0:
            self.response.set_error_response(0)
        self.response.done = True
Example #8
0
 def order_sell_limit(self, symbol, quantity, limitPrice):
     sell_status = r.order_sell_limit(symbol, quantity, limitPrice)
     # Test if stocks are updated immediately or nah
     self.my_stocks = self.refresh_holdings()
     return sell_status
Example #9
0
if __name__ == "__main__":

    # ticker = input("Which stock would you like to trade: ")
    ticker = 'BYFC'

    # login
    login = r.login(username, password)

    # print out a summary and ask what to do
    cur_price = round(float(r.get_latest_price(ticker)[0]), 2)
    print("Current Price: ", cur_price)

    # now what?
    trade = input("Would you like to buy or sell (b/s): ")
    shares = int(input("How many shares: "))
    price_target = float(input("What price: "))

    if trade == 'b':
        # this means we want to buy
        print(ticker, ": Limit buy order for", shares,
              "shares has been placed at $", price_target)
        r.order_buy_limit(ticker, shares, price_target)

    elif trade == 's':
        # this means we want to sell
        print(ticker, ": Limit sell order for", shares,
              "shares has been placed at $", price_target)
        r.order_sell_limit(ticker, shares, price_target)

    else:
        print("ERROR: specify b/s for buy/sell")
Example #10
0
	def realtime_trader(self, hot=False, cap_limit=100):
		# make sure we get a reset, empty dict
		self.real_time_data = dict()
	
		# make sure we reset
		self.loop_count = 1
		
		# don't do this accidentally
		if hot:
			confirm = input("Authorize real-time trading?")

		# 'moving average' - init to real values so we don't get jumpy
		rolling_price = self.get_price_safe()
		last_price = rolling_price

		time.sleep(1)

		# PID stuff
		i_term = 0
		pid_term = 0

		# start trading here
		while True:
			# make sure we're getting a good price
			cur_price = self.get_price_safe()
			if cur_price == 0:
				pass

			# calculate the 'rolling average'
			rolling_price = rolling_price*0.9 + cur_price*0.1
			spread_percent = (rolling_price - cur_price)/cur_price
			change_percent = (last_price - cur_price)/cur_price

			# i_term should rollover from previous
			i_term += spread_percent*self._I_

			# CALCULATE PID
			pid_term = self._P_*spread_percent + i_term + self._D_*change_percent
			
			# adjust PID for relative volatility as well as shares we hold
			pid_term -= float(self.shares / self.SHARE_LIMIT)
			pid_term *= self.get_rel_volume()


			# update for next time - for 'd' term
			last_price = cur_price

			# by default, assume we don't have an order this second
			new_order = None # use this in the data struct

			# now, trade based on info
			if pid_term < -1*self.PID_LIM: 				# SELL

				# todo:
				price_target = cur_price
				trade_amount = self.SHARES_PER_TRADE

				# reset i term and moving average
				i_term = 0
				rolling_price = cur_price

				# don't oversell - this needs to be more robust
				if self.shares-trade_amount < 0:
					trade_amount = self.shares

				# place sell order
				if hot and trade_amount != 0:
					# let us know if it was placed
					print("[", self.loop_count, "] Order Placed: [ sell ] Q ", end='')
					print(trade_amount, "$", price_target)

					sell = r.order_sell_limit(self.tick, trade_amount, price_target)

					if sell != None:
						order_summary = dict()
						order_summary['id'] = sell['id']
						order_summary['quantity'] = float(sell['quantity'])
						order_summary['price'] = float(sell['price'])
						order_summary['side'] = sell['side']
						order_summary['state'] = 'placed'
						order_summary['average_price'] = None
						order_summary['created_at'] = sell['created_at']

						# store this, because we'll need to add it to datastruct
						new_order = order_summary
				else:
					# let us know if it was placed
					print("cold [", self.loop_count, "] Order Placed: [ sell ] Q ", end='')
					print(trade_amount, "$", price_target)
					
			elif pid_term > self.PID_LIM:				# BUY

				# todo:
				price_target = cur_price
				trade_amount = self.SHARES_PER_TRADE

				# reset i term if we order
				i_term = 0
				rolling_price = cur_price
				
				# cancel all other orders, and place buy order
				if hot and self.shares <= self.SHARE_LIMIT:
					# let us know if it was placed
					print("[", self.loop_count, "] Order Placed: [ buy ] Q ", end='')
					print(trade_amount, "$", price_target)

					buy = r.order_buy_limit(self.tick, trade_amount, price_target)

					if buy != None:
						order_summary = dict()
						order_summary['id'] = buy['id']
						order_summary['quantity'] = float(buy['quantity'])
						order_summary['price'] = float(buy['price'])
						order_summary['side'] = buy['side']
						order_summary['state'] = 'placed'
						order_summary['average_price'] = None
						order_summary['created_at'] = buy['created_at']

						# store this, because we'll need to add it to datastruct
						new_order = order_summary
				else:
					# let us know if it was placed
					print("(cold) [", self.loop_count, "] Order Placed: [ buy ] Q ", end='')
					print(trade_amount, "$", price_target)
					

			# add an entry to the full data group so we can keep
			# making predictions
			addon = dict()
			addon['tick'] = self.tick
			addon['price'] = cur_price
			addon['roll_price'] = rolling_price
			addon['pid'] = pid_term
			addon['order'] = new_order # if there was a trade, add it to the data we return

			self.real_time_data[self.loop_count] = addon
			self.loop_count += 1

			# see if any orders were filled, and update balanced
			self.update_orders()

			# see if we are making money
			self.calc_performance()

			# wait to recieve a request from plotting client, then send data
			# timeout set to 1000ms currently, so no need to sleep on except
			try:
				self.server.recv()
				self.server.send(bytes(str(self.real_time_data), 'utf-8'))
				time.sleep(1)
			except:
				pass