Я внедрил бота для торговли на бумаге, и он работает нормально, но когда я перехожу на торговлю в реальном времени, он не размещает никаких ордеров на покупку. Мне интересно, правильно ли я финансирую свои заказы на покупку.
Вот моя функция:
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
Я внедрил бота для торговли на бумаге, и он работает нормально, но когда я перехожу на торговлю в реальном времени, он не размещает никаких ордеров на покупку. Мне интересно, правильно ли я финансирую свои заказы на покупку. Вот моя функция: [code]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' }
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}" } } }
Я внедрил бота для торговли на бумаге, и он работает нормально, но когда я перехожу на торговлю в реальном времени, он не размещает никаких ордеров на покупку. Мне интересно, правильно ли я финансирую свои заказы на покупку.
Ниже приведена моя...
Я внедрил бота для торговли на бумаге, и он работает нормально, но когда я перехожу на торговлю в реальном времени, он не размещает никаких ордеров на покупку. Мне интересно, правильно ли я финансирую свои заказы на покупку.
Вот моя функция:
def...
Я провел два теста, которые четко объясняют сценарий. См. блок кода notify_order и notify_trade ниже.
**Тест 1 (выполнение только 1 ордера SellStop):
**
Когда я исполняю только ордер SellStop, я получаю то, что ожидалось.
В моем notify_order я...
Я размещаю ордер на покупку в своем методе стратегии next() и в порядке уведомления после проверки его завершения я размещаю два ордера (прибыль и убыток)
def notify_order(self, order):
This method is used to monitor the status of an order.
if...
Я пытаюсь разместить стоп-лимитный ордер на MEXC, используя их API, но постоянно сталкиваюсь с ошибкой. Я получаю сообщение об ошибке:
HTTP error occurred: 400 Client Error: Bad Request for url:
{ code :700013, msg : Invalid content Type. }