Почему я не могу разместить ордер на покупку. Правильно ли я его финансирую?Python

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Почему я не могу разместить ордер на покупку. Правильно ли я его финансирую?

Сообщение Anonymous »

Я внедрил бота для торговли на бумаге, и он работает нормально, но когда я перехожу на торговлю в реальном времени, он не размещает никаких ордеров на покупку. Мне интересно, правильно ли я финансирую свои заказы на покупку.
Вот моя функция:

Код: Выделить всё

def place_orders(base_price):
global capital, shib_owned, total_profit, total_loss, completed_orders
grid_levels, upper_limit, lower_limit = create_grid_levels(base_price)

if datetime.now() < trade_window_end:
print('Trading window end time:', trade_window_end)

# Place live buy orders using the new API request method
for level in grid_levels['buy']:
if capital >= investment_amount:
amount_to_buy = investment_amount / level
if amount_to_buy > 0 and not any(order['price'] == level for order in filled_buy_orders):
order_id = str(uuid.uuid4())  # Generate a unique ID
current_time = datetime.now().strftime("%I:%M:%S.%f %p")[:-3]

# Prepare the payload for the buy order
payload = {
"client_order_id": order_id,
"product_id": symbol,
"side": "BUY",
"order_configuration": {
"limit_limit_gtc": {
"base_size": f"{amount_to_buy:.2f}",
"limit_price": f"{level:.5f}"
}
}
}

headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer took out for privacy'
}

url = "https://api.coinbase.com/api/v3/brokerage/orders"
response = requests.post(url, json=payload, headers=headers)

if response.status_code == 201:
# If order is successful, log the details
orders['buy'].append({'id': order_id, 'price': level, 'amount': amount_to_buy})
filled_buy_orders.append({
'id': order_id, 'price': level, 'amount': amount_to_buy, 'timestamp': current_time
})
capital -= investment_amount
shib_owned += amount_to_buy

# 2-second delay to avoid rate limit issues
time.sleep(2)

# Place live sell orders based on filled buy orders
for buy_order in filled_buy_orders[:]:
buy_id, buy_price, amount_to_sell = buy_order['id'], buy_order['price'], buy_order['amount']
sell_level = next((lvl for lvl in grid_levels['sell'] if lvl > buy_price), None)

if sell_level and shib_owned >= amount_to_sell:
if not any(order['id'] == buy_id for order in filled_sell_orders):
profit = (sell_level - buy_price) * amount_to_sell
total_profit += profit
current_time = datetime.now().strftime("%I:%M:%S.%f %p")[:-3]

if profit <  0:
print(f"Loss of ${abs(profit):.2f} on order {buy_id}")
total_loss += profit

# Prepare the payload for the sell order
payload = {
"client_order_id": buy_id,
"product_id": symbol,
"side": "SELL",
"order_configuration": {
"limit_limit_gtc": {
"base_size": f"{amount_to_sell:.2f}",
"limit_price": f"{sell_level:.5f}"
}
}
}

response = requests.post(url, json=payload, headers=headers)

if response.status_code == 201:
# If order is successful, log the sell details
capital += sell_level * amount_to_sell
shib_owned -= amount_to_sell
orders['sell'].append({'id': buy_id, 'price': sell_level, 'amount': amount_to_sell})
filled_sell_orders.append({
'id': buy_id, 'price': sell_level, 'amount': amount_to_sell, 'profit': profit,
'timestamp': current_time
})

else:
exit()
Я хочу иметь возможность разместить заказ на покупку с помощью API

Подробнее здесь: https://stackoverflow.com/questions/791 ... -correctly
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»