-1

I have made a program that executes a market order trade by utilizing the Coinbase Crypto Exchange Sandbox API. This code works fine when I execute it without a GUI. However, I want to create a GUI for it so I can execute some of the features without having to run through the code- more user-friendly and functional.

The problem: Since making a basic GUI and putting the market order/buy code into a function I cant execute trades.

I have tried calling the function and changing the position of the code.

I have a hunch it is not executing the Buy order due to the Buy order code being separate from the rest of the code. I tried putting all the code into the Buy order function but it still didn't work.

Any ideas or thoughts are welcome. Thanks!

import pandas as pd
import cbpro
import PySimpleGUI as sg    

api_secret = 
api_key =  
api_pass =

# creates client variable
url='https://api-public.sandbox.pro.coinbase.com'

client = cbpro.AuthenticatedClient(
    api_key,
    api_secret,
    api_pass,
    api_url=url
)

Accessing certain values

#websocket
class TextWebsocketClient(cbpro.WebsocketClient):
    # Connection to Website
    def on_open(self):
        self.url           = 'wss://ws-feed-public.sandbox.pro.coinbase.com'  #connection endpoint
        self.message_count = 0
    
    # creates message for onscreen
    def on_message(self,msg):   
        self.message_count += 1
        msg_type = msg.get('type',None)
        if msg_type == 'ticker':
            # returns a dict of keys&values.
            # we then select the ones we want- 'time','price',ect
            time_val   = msg.get('time',('-'*27))
            price_val  = msg.get('price',None)
            if price_val is not None:
                price_val = float(price_val)
            product_id = msg.get('product_id',None)
            
            print(f"{time_val:40} {price_val:.3f} {product_id}\tchannel type: {msg_type}")
    
    def on_close(self):
        print(f"<---Websocket connection closed--->\n\tTotal messages: {self.message_count}")
        
# 

# Closes after n messages or when loses connection or closed

stream = TextWebsocketClient(products=['BTC-USD'],channels=['ticker'])
stream.start()

#stream.close()
print ("Stream closed")


Placing a buy order. I put this into a function that doesn't now work but the same code works fine when not in a function or a part of the GUI.


#Placing a BUY market order
# Buy
def buy():
    client.place_market_order(product_id='BTC-USD',side='buy',funds=100)
    accounts = client.get_accounts()
    
    for acc in accounts:
        currency = acc.get('currency')
        if currency=='BTC':
            acc_id = acc.get('id')


    acc_history = client.get_account_history(acc_id)
    return "Buy Complete"

GUI below


# GUI 
#LAYOUT
theme_name_list = sg.theme('DarkGreen')
#Buttons
layout = [ 
            [sg.Text("Welcome to your Crypto Launch Pad!\n Select a command...")],
            [sg.Button('Buy')],
            [sg.Button('Sell')],
            [sg.Button('Current Price')],
            [sg.Button('Profit/Loss')],
            [sg.Button('Exit')]
    
         ]
 
window = sg.Window('Crypto Buy/Sell Launch Pad', layout, size = (400, 400)) # title of window

# saves the actions(clicks) and the inputted values
while True:
    event, values = window.read()
    print(event, values)
    if event is None or event == "Exit":
        break
    
    if event == "Buy":   # Connected to Buy Function
        buy()
        print(buy())
        
        
    
window.close()

dingoyum
  • 25
  • 4
  • 1
    Function wont execute ? it executed ! Maybe only one statement `print(buy())` required when event "Buy". Just add some `print` in your `buy` function to confirm if it executed as programming. – Jason Yang Jul 15 '22 at 08:53
  • I agree. I got it to execute the order whilst using the GUI button. I guess writing my problem helped me think it through. Thanks for your response and help! – dingoyum Jul 15 '22 at 14:16

1 Answers1

0

ANSWER:

After toying with it some more I decided to check whether the CoinbasePro Sandbox was fully functional. Turns out it won't execute any orders with BTC for some reason. I changed crypto to see if that made a difference. The site executed the new orders.

I played with the code again and inputted the new cryptocurrency values and rearranged some of the code blocks. Success! Got it working. I am sure there are some more improvements I can make but the code below works fine with no errors.

import pandas as pd
import cbpro
import PySimpleGUI as sg    

api_secret = ''
api_key =  ''
api_pass = ''

#websocket
class TextWebsocketClient(cbpro.WebsocketClient):
    def on_open(self):
        self.url           = 'wss://ws-feed-public.sandbox.pro.coinbase.com'  #connection endpoint
        self.message_count = 0
    
    def on_message(self,msg):   # creates message for onscreen
        self.message_count += 1
        msg_type = msg.get('type',None)
        if msg_type == 'ticker':
            # returns a dict of keys&values.
            # we then select the ones we want- 'time','price',ect
            time_val   = msg.get('time',('-'*27))
            price_val  = msg.get('price',None)
            if price_val is not None:
                price_val = float(price_val)
            product_id = msg.get('product_id',None)
            
            print(f"{time_val:40} {price_val:.3f} {product_id}\tchannel type: {msg_type}")
    
    def on_close(self):
        print(f"<---Websocket connection closed--->\n\tTotal messages: {self.message_count}")

# Closes after n messages or when loses connection
stream = TextWebsocketClient(products=['ETH-BTC'],channels=['ticker'])
stream.start()

#stream.close()
print ("Stream closed")

# creates client variable
url='https://api-public.sandbox.pro.coinbase.com'

client = cbpro.AuthenticatedClient(
    api_key,
    api_secret,
    api_pass,
    api_url=url
)

#Placing a BUY market order
def buy():
    client.place_market_order(product_id='ETH-BTC',side='buy',funds=0.00003)
    return "Buy Complete"

# Gets the account history

accounts = client.get_accounts()

for acc in accounts:
    currency = acc.get('currency')
    if currency=='ETH':
        acc_id = acc.get('id')
    
acc_history = client.get_account_history(acc_id)

# GUI 
theme_name_list = sg.theme('DarkGreen')

#Buttons
layout = [ 
            [sg.Text("Welcome to your Crypto Launch Pad!\n Select a command...")],
            [sg.Button('Buy')],
            [sg.Button('Sell')],
            [sg.Button('Current Price')],
            [sg.Button('Profit/Loss')],
            [sg.Button('Exit')]
         ]
            
window = sg.Window('Crypto Buy/Sell Launch Pad', layout, size = (400, 400)) # title of window

# saves the actions(clicks) and the inputted values
while True:
    event, values = window.read()
    print(event, values)
    if event is None or event == "Exit":
        break
    
    if event == "Buy":   # Connected to Buy Function
        buy()
    
window.close()

dingoyum
  • 25
  • 4