trading-bot / main.py
main.py
Raw
from gate_api.exceptions import ApiException, GateApiException
import gate_api
import json
import _thread

f = open('keysGateioV4.json')
data = json.load(f)

configuration = gate_api.Configuration(host="https://api.gateio.ws/api/v4", key=data["apiKey"],
                                       secret=data["apiSecret"])
api_client = gate_api.ApiClient(configuration)
api_instance = gate_api.DeliveryApi(api_client)
asi = gate_api.SpotApi(api_client)
settle = 'usdt'
token = input("Enter token: ").upper()
token_pair = f'{token}_USDT'
auto_buy = input("Do you want to try and auto-buy? y/n : ").lower()
manual_quoted = input("How much do you want to trade? ")
auto_sell_option = input("Do you want to auto-sell?: y/n: ").lower()
auto_sell_amount = ""
if auto_sell_option == "y":
    auto_sell_amount = input("How much? (Enter profit % number, without percentage) i.e. 5% would be 5: ")


def get_token_balance():
    try:
        # get available of token in currency
        v = asi.list_spot_accounts(currency=token)[0].available
        return v
    except GateApiException as ex:
        print('Gate api exception, label : %s, message: %s\n' % (ex.label, ex.message))
    except ApiException as e:
        print("Exception when calling DeliveryApi->list_delivery_contracts: %s\n" % e)


def get_token_start_time():
    try:
        x = asi.get_currency_pair(currency_pair=token_pair)
        return x
    except GateApiException as ex:
        print('Gate api exception, label : %s, message: %s\n' % (ex.label, ex.message))
    except ApiException as e:
        print("Exception when calling DeliveryApi->list_delivery_contracts: %s\n" % e)


def get_token_details():
    try:
        x = asi.list_tickers(currency_pair=token_pair)
        return x
    except GateApiException as ex:
        print('Gate api exception, label : %s, message: %s\n' % (ex.label, ex.message))
    except ApiException as e:
        print("Exception when calling DeliveryApi->list_delivery_contracts: %s\n" % e)


def get_last_order(id):
    try:
        x = asi.get_order(order_id=id, currency_pair=token_pair)
        return x
    except GateApiException as ex:
        print('Gate api exception, label : %s, message: %s\n' % (ex.label, ex.message))
    except ApiException as e:
        print("Exception when calling DeliveryApi->list_delivery_contracts: %s\n" % e)


# THINGS TO DO
# Switch from highest_bid to highest_ask

##### Check if trading #####
details = get_token_details()
while details[0].highest_bid == '0':
    details = get_token_details()
    if details[0].highest_bid != '0':
        print("Listed")
        break
    print(f'Not Listed: {details[0].highest_bid}')
#### END Check if trading #####

###### AUTO BUY ######
token_buy_price = float(details[0].lowest_ask) * 1.05
balance = 0
order_buy_res = None
amount_in_token = 0
if auto_buy == "y":
    amount_in_token = float(manual_quoted) / float(details[0].highest_bid)
    while float(balance) == 0:
        print(f'Amount in token: {amount_in_token} |', f'Token limit buy price: {token_buy_price}')
        try:
            create_order = gate_api.Order(currency_pair=token_pair, side="buy", amount=(str(amount_in_token)),
                                          price=f'{token_buy_price:.12f}', time_in_force="ioc")
            order_buy_res = asi.create_order(create_order)
            print(f'Order: {order_buy_res}')
        except GateApiException as ex:
            print('Gate api exception, label : %s, message: %s\n' % (ex.label, ex.message))
            pass
        except ApiException as e:
            print("Exception when calling DeliveryApi->list_delivery_contracts: %s\n" % e)
            pass
        balance = get_token_balance()
        if float(balance) > 0:
            break
        else:
            token_buy_price = float(get_token_details()[0].lowest_ask) * 1.01
            print("Trying to buy!")

###### END AUTO BUY ######

##### Profit Sell #####

while True:
    order_book = None
    limit_sold = False


    def input_thread(a_list):
        input()
        a_list.append(True)


    def calc_profit():
        a_list = []
        _thread.start_new_thread(input_thread, (a_list,))
        while not a_list:
            details = get_token_details()
            token_last_price = details[0].last
            current_per = float(balance) * float(token_last_price)
            profit_per = 100 * ((current_per - float(order_buy_res.filled_total)) / float(order_buy_res.filled_total))
            print(f'Profit Percentage: {profit_per:.4f}% |', f'Token value: {current_per:.2f} |',
                  f'Token price: {float(token_last_price)} |', f'Auto sell amount: {float(auto_sell_amount)}')
            if auto_sell_option == "y" and profit_per >= float(auto_sell_amount):
                try:
                    # generate sell order of token
                    profit_order = gate_api.Order(currency_pair=token_pair, side="sell", amount=(str(balance)),
                                                  price=f'{float(details[0].highest_bid) * 0.98:.12f}')
                    # send sell order to the exchange
                    asi.create_order(profit_order)
                    print("Profit target hit!")
                    return True
                except GateApiException as ex:
                    print('You\'re holding none of the currency_pair: %s, message: %s\n' % (ex.label, ex.message))
                except ApiException as e:
                    print("Exception when calling DeliveryApi->list_delivery_contracts: %s\n" % e)

            # print(f'Profit/Loss: {round(profit_per, 2)}%')


    limit_sold = calc_profit()

    try:
        # cancel_res = asi.cancel_spot_price_triggered_order_list(market=token_pair)
        cancel_limit = asi.cancel_orders(currency_pair=token_pair, side="sell")
    except GateApiException as ex:
        print('Gate api exception, label : %s, message: %s\n' % (ex.label, ex.message))
    except ApiException as e:
        print("Exception when calling DeliveryApi->list_delivery_contracts: %s\n" % e)

    # declare global available variable
    # balance = None

    # get available of token in currency
    # try:
    #     available = asi.list_spot_accounts(currency=token)[0].available
    # except GateApiException as ex:
    #     print('Gate api exception, label : %s, message: %s\n' % (ex.label, ex.message))
    # except ApiException as e:
    #     print("Exception when calling DeliveryApi->list_delivery_contracts: %s\n" % e)

    # Get order book, retrieve the first buy order, and generate a sell price from it
    balance = get_token_balance()
    if not limit_sold:
        try:
            order_book = asi.list_order_book(token_pair, limit=3)
        except GateApiException as ex:
            print('Gate api exception, label : %s, message: %s\n' % (ex.label, ex.message))
        except ApiException as e:
            print("Exception when calling DeliveryApi->list_delivery_contracts: %s\n" % e)

        order_book_first_bid = float(order_book.bids[0][0])
        limit_sell_price = order_book_first_bid * 0.85

        try:
            # generate sell order of token
            order = gate_api.Order(currency_pair=token_pair, side="sell", amount=(str(balance)),
                                   price=f'{limit_sell_price:.12f}')
            # send sell order to the exchange
            order_sell_res = asi.create_order(order)
        except GateApiException as ex:
            print('You\'re holding none of the currency_pair: %s, message: %s\n' % (ex.label, ex.message))
        except ApiException as e:
            print("Exception when calling DeliveryApi->list_delivery_contracts: %s\n" % e)
    balance = get_token_balance()
    print("Sold!", f'Balance is: {float(balance) * float(details[0].last)}')

    close = input("If initial sell didn't work, press Enter to try again. Otherwise, type in close and hit enter: ")
    if close.lower() == "close":
        break

f.close()