import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
import ccxt
import gspread
import time
from oauth2client.service_account import ServiceAccountCredentials
from google.auth.exceptions import TransportError
# Ваши API-ключи для KuCoin
api_key = '23456'
secret_key = '123456'
api_passphrase = '23456'
# Настраиваем CCXT для KuCoin
exchange = ccxt.kucoin({
'apiKey': api_key,
'secret': secret_key,
'password': api_passphrase
})
# Настройка доступа к Google Sheets
def setup_google_sheet():
while True:
try:
scope = ["
https://spreadsheets.google.com/feeds",
"
https://www.googleapis.com/auth/spreadsheets",
"
https://www.googleapis.com/auth/drive.file",
"
https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name('23456.json', scope)
client = gspread.authorize(creds)
spreadsheet_name = "Strata" # Замените на название вашей таблицы
sheet = client.open(spreadsheet_name).worksheet("KuCoin") # Замените на нужный лист
return sheet
except TransportError as e:
print(f"Ошибка подключения к Google API: {e}")
time.sleep(10) # Повторная попытка через 10 секунд
except Exception as e:
print(f"Непредвиденная ошибка: {e}")
time.sleep(10)
# Получаем индексы столбцов по их названиям
def get_column_indices(sheet):
headers = sheet.row_values(1)
column_indices = {
"Coin": headers.index("Coin") + 1,
"Balance": headers.index("Balance") + 1,
"Price": headers.index("Price") + 1,
"Order Amount": headers.index("Order Amount") + 1,
}
return column_indices
# Получение баланса и цены
def get_balance_and_price(coin):
balance = exchange.fetch_balance()
coin_balance = balance['total'].get(coin, 0)
if coin == "USDT":
coin_price = 1
else:
ticker_symbol = f"{coin}/USDT"
for attempt in range(5):
try:
ticker_data = exchange.fetch_ticker(ticker_symbol)
coin_price = ticker_data['last']
break
except ccxt.NetworkError as e:
print(f"Ошибка сети: {e}. Повтор через 5 секунд...")
time.sleep(5)
except Exception as e:
print(f"Другая ошибка: {e}")
raise
return coin_balance, coin_price
# Выполнение ордера
def execute_order(coin, usdt_amount):
ticker_symbol = f"{coin}/USDT"
price = get_balance_and_price(coin)[1]
amount = abs(usdt_amount) / price
min_order_usdt = 1
if abs(usdt_amount) < min_order_usdt:
print(f"Пропускаем ордер для {coin}, сумма {usdt_amount} USDT меньше {min_order_usdt}.")
return
if usdt_amount > 0:
print(f"Покупаем {amount:.6f} {coin} на сумму {usdt_amount} USDT.")
exchange.create_market_buy_order(ticker_symbol, amount)
elif usdt_amount < 0:
print(f"Продаем {amount:.6f} {coin} на сумму {-usdt_amount} USDT.")
exchange.create_market_sell_order(ticker_symbol, amount)
# Обновление данных в Google Sheets
def update_google_sheet(sheet):
column_indices = get_column_indices(sheet)
data = sheet.get_all_records()
for i, row in enumerate(data, start=2):
coin = row["Coin"]
balance, price = get_balance_and_price(coin)
for attempt in range(5):
try:
sheet.update_cell(i, column_indices["Balance"], balance)
time.sleep(1)
sheet.update_cell(i, column_indices["Price"], price)
time.sleep(1)
break
except gspread.exceptions.APIError as e:
if '503' in str(e):
print("Google Sheets API временно недоступен. Повтор через 5 секунд...")
time.sleep(5)
else:
raise e
data = sheet.get_all_records()
for row in data:
coin = row["Coin"]
order_amount = row.get("Order Amount", 0)
if order_amount != 0:
execute_order(coin, order_amount)
# Основная функция с обработкой ошибок
def main():
while True:
try:
print("Запуск main()")
sheet = setup_google_sheet()
update_google_sheet(sheet)
time.sleep(1)
except Exception as e:
print(f"Ошибка: {e}. Перезапуск через 10 секунд...")
time.sleep(10)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("Скрипт остановлен пользователем.")