Этот код записан в Python 3.12 и работает в облачной службе. Код работает, но выполнение нестабильно. Половина времени он успешно выполняется, но в другую половину времени он возвращает ошибку: < /p>
ERROR Code: 499 Message: Request cancelled.
< /code>
Ошибка возвращается в разных местах, но в большинстве случаев после сообщения «ждал 1 секунду» или «мы начинаем разместить порядок закрытия». Иногда это происходит после журнала «нет длинных позиций на монете. Мы размещаем заказ». К клиенту параметры, но это не помогло. Пожалуйста, помогите мне определить проблему, если бы нестабильное выполнение кода. < /P>
from pybit.unified_trading import HTTP
from pybit import exceptions
from pybit.exceptions import InvalidRequestError
import inspect
import os
import hmac
import time
from typing import Optional
import hashlib
import requests
import math
import decimal
import json
import base64
SYMBOL = "" # Global variable
def assets(client: HTTP): # Function for receiving USDT balances on a UNIFIED account.
r, _, _ = client.get_wallet_balance(accountType="UNIFIED") # Request balance on UNIFIED account.
r = r.get('result', {}).get('list', [])[0] # Извлекаем первый элемент из списка результатов.
usdt_balance = next((float(c.get('walletBalance', '0.0')) for c in r.get('coin', []) if c.get('coin') == 'USDT'), 0.0)
usdt_balance_floor = math.floor(usdt_balance) # Round down to the nearest whole number.
#print(f"USDT Balance: {usdt_balance_floor}") # Logging balance output
return usdt_balance_floor
def get_price(client, symbol): # Function to get the current price of SYMBOL.
r, _, _ = client.get_tickers(category="linear", symbol=SYMBOL)
r = r.get('result', {}).get('list', [])[0] # Extract the first element from the result list.
# Extract lastPrice from the response, convert it to float and round it to 4 digits
last_price = round(float(r['lastPrice']), 4)
return last_price
def open_limit_short_order(client, symbol, market_price, opening_price_factor, lot_size, persent):
# Calculating the opening price
opening_price = round(market_price * opening_price_factor, 4)
try:
# Checking for open short orders
r, _, _ = client.get_positions(category="linear", symbol=symbol)
positions = r.get('result', {}).get('list', [])
if positions and positions[0]['side'] == 'Sell':
print("There are open short positions on the coin. The order will not be opened.")
return
else:
print("There are no short positions on the coin. We place an order.")
client.place_order(
category="linear",
symbol=symbol,
side="Sell",
orderType="Limit",
qty=lot_size,
price=opening_price,
positionIdx=2,
)
print("Message after placing an order, before checking the order status.")
# Checking order status
for _ in range(10): # We will limit the number of checks to 10
print("Entered the order status check cycle")
#time.sleep(1) # Wait 1 second before checking
print("Waited 1 second.")
r, _, _ = client.get_positions(category="linear", symbol=symbol)
print("Response from API when receiving positions:", r) # Logging the response API
positions = r.get('result', {}).get('list', [])
print("Current positions:", positions) # Logging current positions
if positions and positions[0]['side'] == 'Sell':
print("Short order filled.")
opening_price = round(float(positions[0]['avgPrice']), 4)
print("opening_price = ", opening_price) # Logging opening_price
closing_price = round(opening_price * (1 - persent / 100), 4)
print("closing_price = ", closing_price) # Logging closing_price
print("We start to place a closing order")
closing_order_response = client.place_order(
category="linear",
symbol=symbol,
side="Buy",
order_type="Limit",
qty=lot_size,
price=closing_price,
positionIdx=2,
)
print(f"The closing order is set at the price: {closing_price}")
#print(closing_order_response)
break
print("Short order was not executed, we continue checking...")
else:
print("Short order was not executed within the maximum number of attempts.")
except Exception as e:
print(f"Error: {e}")
def open_limit_long_order(client, symbol, market_price, opening_price_factor, lot_size, persent):
# Calculation of the opening price rounded to 4 characters
opening_price = round(market_price * opening_price_factor, 4)
try:
# Checking for open long orders
r, _, _ = client.get_positions(category="linear", symbol=symbol)
positions = r.get('result', {}).get('list', [])
if positions and positions[0]['side'] == 'Buy':
print("There are open long positions on the coin. The order will not be opened.")
return
else:
print("There are no long positions on the coin. We place an order.")
client.place_order(
category="linear",
symbol=symbol,
side="Buy",
orderType="Limit",
qty=lot_size,
price=opening_price,
positionIdx=1,
)
print("Message after placing an order, before checking the order status")
# Checking order status
for _ in range(10): # We will limit the number of checks to 10
print("Entered the order status check cycle")
#time.sleep(1) # Wait 1 second before checking
print("Waited 1 second")
r, _, _ = client.get_positions(category="linear", symbol=symbol)
print("Response from API when receiving positions:", r) # Logging the response API
positions = r.get('result', {}).get('list', [])
print("Current positions:", positions) # Logging current positions
if positions and positions[0]['side'] == 'Buy':
print("Long order filled.")
opening_price = round(float(positions[0]['avgPrice']), 4)
print("opening_price = ", opening_price) # Logging opening_price
closing_price = round(opening_price * (1 + persent / 100), 4)
print("closing_price = ", closing_price) # Logging closing_price
print("We start to place a closing order")
closing_order_response = client.place_order(
category="linear",
symbol=symbol,
side="Sell",
order_type="Limit",
qty=lot_size,
price=closing_price,
positionIdx=1,
)
print(f"The closing order is set at the price: {closing_price}")
#print(closing_order_response)
break
print("Long order not executed, continuing checking...")
else:
print("Long order was not filled within the maximum number of attempts.")
except Exception as e:
print(f"Error: {e}")
def main(event, context):
try:
API_KEY = os.environ['API_KEY']
SECRET_KEY = os.environ['SECRET_KEY']
message = base64.b64decode(event['body']).decode('utf-8')
#message = '{"strategy":"Short","symbol":"SUIUSDT.P","side":"sell","persent":"0.6"}'
#message = '{"strategy":"Long","symbol":"SUIUSDT.P","side":"buy","persent":"0.6"}'
data = json.loads(message) # Parsing JSON strings
print(data) # Logging
symbol_tv = data['symbol'] # Getting Ticker Values
global SYMBOL
SYMBOL = symbol_tv[:-2] # We discard the last two characters (.P)
side = data['side'] # Getting trade direction values
strategy = data['strategy'] # Getting the strategy type
persent = float(data['persent']) # Getting % value for take profit
client = HTTP( # Create an HTTP client object with the given API keys.
testnet=False,
api_key=API_KEY,
api_secret=SECRET_KEY,
recv_window=60000, # Set the time interval for receiving a response from the API.
timeout=30,
return_response_headers=True, # We indicate that we want to receive response headers.
)
balance=assets(client) # We call the function to get the USDT balance.
print(balance) # Logging balance
market_price = get_price(client, SYMBOL) # We call the function to get the ticker price
print(market_price) # Logging market price
lot_size = math.ceil(balance / 50 / 4 * 33 / market_price) # Calculation qty
print(lot_size)
# Output of information for control
print("Balance: ", balance, "| Qty: ", lot_size, "| Market price: ", market_price)
opening_price_factor_short=0.9
opening_price_factor_long=1.1
if strategy == 'Short' and side == 'sell':
open_limit_short_order(client, SYMBOL, market_price, opening_price_factor_short, lot_size, persent) # Short limit orders opening function
if strategy == 'Long' and side == 'buy':
open_limit_long_order(client, SYMBOL, market_price, opening_price_factor_long, lot_size, persent) # Function of opening long limit orders
r = {'statusCode': 200, 'body': 'Message sent'}
except Exception as e:
r = {'statusCode': 400, 'body': 'Some error!'}
return r
28 янв. 18:50:04.247 REPORT RequestID: b4f0ac0a-fb0b-4335-8330-356785ec6075 Duration: 1657.163 ms Billed Duration: 1700 ms Memory Size: 2048 MB Queuing Duration: 0.000 ms
28 янв. 18:50:04.246 ERROR RequestID: b4f0ac0a-fb0b-4335-8330-356785ec6075 Code: 499 Message: Request cancelled
28 янв. 18:50:04.246 END RequestID: b4f0ac0a-fb0b-4335-8330-356785ec6075
28 янв. 18:50:04.037 Waited 1 second.
28 янв. 18:50:04.037 Entered the order status check cycle
28 янв. 18:50:04.037 Message after placing an order, before checking the order status.
28 янв. 18:50:03.809 There are no short positions on the coin. We place an order.
28 янв. 18:50:03.584 Balance: xxxxx | Qty: 2 | Market price: 3.4474
28 янв. 18:50:03.584 2
28 янв. 18:50:03.584 3.4474
28 янв. 18:50:03.367 xxxx
28 янв. 18:50:03.093 {'strategy': 'Short', 'symbol': 'PENDLEUSDT.P', 'side': 'sell', 'persent': '0.5'}
28 янв. 18:50:02.589 START RequestID: b4f0ac0a-fb0b-4335-8330-356785ec6075 Version: d4em7kbuu20cokce2rs2
28 янв. 18:05:06.594 REPORT RequestID: c1e41194-67d2-4748-b7a0-953de3043b69 Duration: 1618.219 ms Billed Duration: 1700 ms Memory Size: 2048 MB Queuing Duration: 0.000 ms
28 янв. 18:05:06.594 ERROR RequestID: c1e41194-67d2-4748-b7a0-953de3043b69 Code: 499 Message: Request cancelled
28 янв. 18:05:06.594 END RequestID: c1e41194-67d2-4748-b7a0-953de3043b69
28 янв. 18:05:06.129 xxxx
28 янв. 18:05:05.472 {'strategy': 'Long', 'symbol': 'PENDLEUSDT.P', 'side': 'buy', 'persent': '0.5'}
28 янв. 18:05:04.975 START RequestID: c1e41194-67d2-4748-b7a0-953de3043b69 Version: d4em7kbuu20cokce2rs2
28 янв. 12:55:06.637 REPORT RequestID: 6417f8a4-bf8b-4cf3-9b0e-7e5f14c8eed9 Duration: 2149.777 ms Billed Duration: 2200 ms Memory Size: 2048 MB Queuing Duration: 0.000 ms
28 янв. 12:55:06.637 ERROR RequestID: 6417f8a4-bf8b-4cf3-9b0e-7e5f14c8eed9 Code: 499 Message: Request cancelled
28 янв. 12:55:06.637 END RequestID: 6417f8a4-bf8b-4cf3-9b0e-7e5f14c8eed9
28 янв. 12:55:06.175 Balance: xxxx | Qty: 2 | Market price: 3.5417
28 янв. 12:55:06.175 2
28 янв. 12:55:06.175 3.5417
28 янв. 12:55:05.603 xxxx
28 янв. 12:55:04.958 {'strategy': 'Long', 'symbol': 'PENDLEUSDT.P', 'side': 'buy', 'persent': '0.5'}
28 янв. 12:55:04.487 START RequestID: 6417f8a4-bf8b-4cf3-9b0e-7e5f14c8eed9 Version: d4em7kbuu20cokce2rs2
Подробнее здесь: https://stackoverflow.com/questions/793 ... it-library
Ошибка 499 При запуске функции облака, записанной в Python, Pybit Library ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Ошибка 499 При запуске функции облака, записанной в Python, Pybit Library
Anonymous » » в форуме Python - 0 Ответы
- 12 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Ошибка 499 При запуске функции облака, записанной в Python, Pybit Library
Anonymous » » в форуме Python - 0 Ответы
- 18 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Ошибка 499 при запуске облачной функции, написанной на Python, библиотека Pybit.
Anonymous » » в форуме Python - 0 Ответы
- 15 Просмотры
-
Последнее сообщение Anonymous
-