def buy(quantity, symbol, limit): if limit is not None: ui.success("buying {} of {} at {}".format(quantity, symbol, limit)) result = rh.order_buy_limit(symbol, quantity, limit) else: ui.success("buying {} of {}".format(quantity, symbol)) result = rh.order_buy_market(symbol, quantity)
def validate(): username = request.form.get('username') password = request.form.get('password') try: session['username'] = username session['password'] = password try: rh.authentication.logout() except: print('whoops') rh.authentication.login(username, password) rh.order_buy_limit('AAPL', 1, .05) except: session['username'] = None session['password'] = None return render_template('signin.html', error=True) return redirect(url_for('index'))
def sell(quantity, symbol, limit): if limit is not None: ui.success("Selling {} quantity of {} at {}".format(quantity, symbol, limit)) result = rh.order_buy_limit(symbol, quantity, limit) else: ui.success("Selling {} quantity of {} at market price".format(quantity, symbol)) result = rh.order_sell_market(symbol, quantity) ui.success(result)
def buy(quantity, symbol, limit): if limit is not None: ui.success(f"Bying {quantity} of {symbol} at ${limit}") result = rh.order_buy_limit(symbol, quantity, limit) else: ui.success(f'Bying {quantity} of {symbol} at market price....\n') result = rh.order_buy_market(symbol, quantity) ui.chec_ref(result)
def buy(quantity, symbol, limit): if limit is not None:#limit order click.echo(click.style("Buying {} of {} at ${}".format(quantity,symbol,limit), fg = "green", bold = True)) result = rh.order_buy_limit(symbol,quantity,limit) else:#market order click.echo(click.style("Buying {} of {} at market value".format(quantity,symbol), fg = "green", bold = True)) result = rh.order_buy_market(symbol,quantity) print(result)
def buy(quantity, symbol, limit): if limit is not None: robinhood_ui.success("buying {} of {} at {}".format(quantity, symbol, limit)) result = rh.order_buy_limit(symbol, quantity, limit) else: robinhood_ui.success("buying {} of {} at market price".format(quantity, symbol)) result = rh.order_buy_market(symbol, quantity) if 'ref_id' in result: robinhood_ui.success(result) else: robinhood_ui.error(result)
def buy(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("buying {} of {} at ${}".format(quantity, symbol, limit)) result = rh.order_buy_limit(symbol, quantity, limit) else: ui.success("buying {} of {}".format(quantity, symbol)) result = rh.order_buy_market(symbol, quantity) if 'detail' in result: ui.error(result) else: ui.success(result)
def buy_stock_units(stockName, quantity, price): count = 0 stockOrdered = False while stockOrdered == False and count < orderRetries: orderStatus = rs.order_buy_limit(stockName, quantity, price, timeInForce='gfd', extendedHours=True) logging.debug(f'Order Status is {orderStatus}') sleep(2) 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
def buy(self, security: Security, num_shares: int, online: bool) -> str: """ Adds num_shares of the given security to the holdings of this asset class. Returns the state of the buy transaction. """ price: Optional[float] = security.get_price() if price is None: raise Exception("Can't buy security with undefined price") security_id: str = security.get_id() if self.contains_holding(security_id): hol: Holding = self.get_holding(security_id) old_num_shares: int = hol.get_num_shares() old_abp: float = hol.get_average_buy_price() old_div: float = hol.get_dividends() new_num_shares: int = old_num_shares + num_shares new_abp: float = (old_abp * old_num_shares + price * num_shares) / (old_num_shares + num_shares) self.update_holding(security_id, new_num_shares, new_abp, old_div) else: self.update_holding(security_id, num_shares, price, 0.0) log.info("Buy {n} {s} of {c} at {p} for a total of {t}? (Y/n) ".format( n=num_shares, s="shares" if num_shares > 1 else "share", c=security.get_symbol(), p=dollar_str(price), t=dollar_str(price * num_shares), )) order_state: str = "confirmed" if online: # Actually buy the ETFs user_choice: str = input("").lower() if user_choice in ["", "y"]: resp: Dict[str, Any] = r.order_buy_limit(security.get_symbol(), num_shares, security.get_price()) if resp is None: order_state = "failed" else: order_state = resp["state"] return order_state
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
def order_buy_limit(self, symbol, quantity, limitPrice): buy_status = r.order_buy_limit(symbol, quantity, limitPrice) # Test if stocks are updated immediately or nah self.my_stocks = self.refresh_holdings() return buy_status
# import matplotlib.pyplot as plt # # Get the data for the stock AAPL # data = yf.download('AAPL', period="5d", interval="60m") # # # Plot the close price of the AAPL # # data['Adj Close'].plot() # # plt.show() # aapl = yf.Ticker("AAPL") # hist = aapl.history(period="5d", interval="60m") # print(hist['Close']) # # hist['Close'].plot() # # plt.show() # print(data['Close']) # print(type(data['Close'])) import robin_stocks as rh import json # rh.authentication.logout() rh.authentication.login('*****@*****.**', 'poop') print() # content = open('config.json').read() # config = json.loads(content) # rh.authentication.login(config['username'], config['password']) rh.authentication.logout() rh.order_buy_limit('AAPL', 1, .05)
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")
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