Binance futures api php

Place orders on Binance’s futures with PHP #6315

Comments

Skowiz commented Dec 25, 2019 •

I would like to place orders on Binance’s futures with PHP but it doesnt work :

The text was updated successfully, but these errors were encountered:

kroitor commented Dec 25, 2019

We need you to elaborate, which particular output do you get? Can you plz paste your verbose request/response (without the keys) ?

kroitor commented Dec 25, 2019

@Skowiz also, for some reason, you’re sending uppercase order type (LIMIT) and side (BUY) – those should be lowercase, as shown in the Manual:

And you have to specify the price of the limit order, for some reason you’re missing the price argument in the createOrder call:

kroitor commented Dec 25, 2019

@Skowiz so, your code should look like:

Let us know if that does not help.

Skowiz commented Dec 25, 2019

The answer I have is

Request: Array ( [0] => POST [1] => https://fapi.binance.com/fapi/v1/order [2] => Array ( [0] => X-MBX-APIKEY: apikey [1] => Content-Type: application/x-www-form-urlencoded ) [3] => timestamp=1577305511040&recvWindow=5000&symbol=BTCUSDT&quantity=0.002&type=LIMIT&side=BUY&price=5000&timeInForce=GTC&signature=xxx ) Response: Array ( [0] => POST [1] => https://fapi.binance.com/fapi/v1/order [2] => 401 [3] => [4] => Array ( [content-type] => Array ( [0] => application/json ) [content-length] => Array ( [0] => 70 ) [date] => Array ( [0] => Wed, 25 Dec 2019 20:25:11 GMT ) [server] => Array ( [0] => Tengine ) [x-mbx-used-weight-1m] => Array ( [0] => 1 ) [x-response-time] => Array ( [0] => 0ms ) [access-control-allow-origin] => Array ( [0] => * ) [access-control-allow-methods] => Array ( [0] => GET, POST, PUT, DELETE, OPTIONS ) [x-cache] => Array ( [0] => Error from cloudfront ) [via] => Array ( [0] => 1.1 5e95d2e6aebe43cabd9dcdad89ad0a42.cloudfront.net (CloudFront) ) [x-amz-cf-pop] => Array ( [0] => AMS54-C1 ) [x-amz-cf-id] => Array ( [0] => xxx== ) ) [5] => <"code":-2015,"msg":"Invalid API-key, IP, or permissions for action.">)

kroitor commented Dec 26, 2019

@Skowiz it says: <"code":-2015,"msg":"Invalid API-key, IP, or permissions for action.">. Which steps from this troubleshooting sequence from the Manual have you tried?

Have you tried a fresh new keypair? Have you checked the API credentials themselves? Any other troubleshooting steps?

Skowiz commented Dec 26, 2019 •

I have last version of CCXT, I tried a new keypair .
But if I make the code run in default market, it works

This code place an order, I think it is really a problem with future market

kroitor commented Dec 26, 2019

@Skowiz have you enabled the futures account with Binance? Tried placing any future orders on their website?

I think it is really a problem with future market

It’s hard to tell without getting your answers to all of the above questions here: #6315 (comment)

Читайте также:  Инвестиции для начинающих новости

kroitor commented Dec 26, 2019 •

@Skowiz can you plz post the runtime version of CCXT, as shown below?

This also looks similar to an issue that has been resolved: #6196

kroitor commented Dec 26, 2019

@Skowiz check if the futures account had been activated for you in the futures section of Binance’s website. It won’t work for API keys created before activating the futures account, so the API keys have to be recreated after creating the futures account with Binance’s website. Let us know here if the above does not help.

Skowiz commented Dec 26, 2019 •

My version is : CCXT version: 1.21.15
Yes I have already placed orders with Binance Future website. And I created new keypair 1 hour ago, then I dont know what is the problem.

kroitor commented Dec 26, 2019 •

@Skowiz have you tried reaching out to Binance tech support on this issue? Also, it’s worth checking if your IP is whitelisted with that keypair, just in case. If you send them your verbose output they should be able to help you out quickly, or at least will provide some directions. Without your actual keys it’s hard to test this specific error:

↑ That usually means what it says, literally. The signing works the same way with both spot and futures, so if the key works for regular spot trades, but doesn’t work for futures trades – that’s most likely an issue with the key (wrong credentials in the script itself – you can see and verify those in verbose mode on your side to rule this out) or wrong permissions on that key or something else related to the key. This may also be a temporary block due to a rate-limit violation of some sort.

Does $binance->fetch_balance(); work with that key?

Skowiz commented Dec 27, 2019

Yes $binance->fetch_balance(); works, then my IP is OK and my API’s ID too.
Then I do not know what is the problem.
I sent a message to Binance support but I dont have any answer now.

Skowiz commented Dec 28, 2019

Binance is asking me to send them the full CURL of my request, how can I have access to ?

kroitor commented Dec 28, 2019

@Skowiz send them your complete verbose request+response pair that you can see in verbose mode, which you can enable as shown above: #6315 (comment)

Skowiz commented Dec 29, 2019

The answer they gave me is :

Then I do not know what is wrong because with verbose mode I have this message

Request: Array ( [0] => POST [1] => https://fapi.binance.com/fapi/v1/order [2] => Array ( [0] => X-MBX-APIKEY: KEY [1] => Content-Type: application/x-www-form-urlencoded ) [3] => timestamp=1577621294544&recvWindow=5000&symbol=BTCUSDT&quantity=0.002&type=LIMIT&side=BUY&price=5000&timeInForce=GTC&signature=033105bdb2a5629a62afd5b214557e4fdea674fb91b546437c693ab71b3d13dd ) Response: Array ( [0] => POST [1] => https://fapi.binance.com/fapi/v1/order [2] => 401 [3] => [4] => Array ( [content-type] => Array ( [0] => application/json ) [content-length] => Array ( [0] => 70 ) [date] => Array ( [0] => Sun, 29 Dec 2019 12:08:15 GMT ) [server] => Array ( [0] => Tengine ) [x-mbx-used-weight-1m] => Array ( [0] => 2 ) [x-response-time] => Array ( [0] => 0ms ) [access-control-allow-origin] => Array ( [0] => * ) [access-control-allow-methods] => Array ( [0] => GET, POST, PUT, DELETE, OPTIONS ) [x-cache] => Array ( [0] => Error from cloudfront ) [via] => Array ( [0] => 1.1 6642832e0f3e501fb9fdc5f35d4351d8.cloudfront.net (CloudFront) ) [x-amz-cf-pop] => Array ( [0] => AMS54-C1 ) [x-amz-cf-id] => Array ( [0] => 55Hl8ONQtU_Q-MMffy0ojAyhJVTHF3j1f5vIRV2PhY4XSbic_NFtug== ) ) [5] => <"code":-2015,"msg":"Invalid API-key, IP, or permissions for action.">)

Читайте также:  Расчет доходности капитала предприятия

kroitor commented Dec 29, 2019 •

@Skowiz have you tried the values they suggest (price=8400, side=’sell’, somewhat closer to the market price) ?

You see, the values you use are price=5000 and side=buy, which are beyond limits for BTC/USDT:

See the filters field above and also check out the following:

↑ Your value for the price (5000) does not satisfy the requirements. If the PERCENT_PRICE multiplierDown is 0.85 and the market price is

7200, then the minimal price you can submit is roughly 7200 * 0.85

= 6120 > 5000. And all other filters on that market should be satisfied as well.

Let me know if that does not help.

Skowiz commented Dec 29, 2019

Even if i but a price as they did 8400 and side «sell», it is correct with the market price (7400), it is not working.
Maybe the issue come from the recvWindow param wich is equal to 5000 in my request but it should be 60000 I think.
How can I change this value ?

Источник

Как создать криптовалютный дашборд с помощью Plotly и API Binance

Упрощаем отслеживание активов

Как установить API Binance

Binance предоставляет два типа доступа к API: реальный и тестовый.

Настраиваем реальный API Binance

Реальный API обеспечивает прямой доступ к аккаунту. В нем будут отражены любые сделки, совершенные через этот API. Поэтому использовать его следует с осторожностью.

Для начала нужно зарегистрироваться на Binance.

После регистрации вам будет предложено установить двухфакторную аутентификацию (2FA). Вы также можете подключить ее самостоятельно в настройках безопасности.

Затем переходим во вкладку API Management в настройках. Вам будет предложено установить метки для ключей API. Эта функция пригодится тем, у кого есть несколько ключей, связанных с одним аккаунтом.

Указываем метки и нажимаем Create API. После этого нужно пройти аутентификацию еще раз. Затем отобразятся API Key и Secret Key. Скопируйте их в безопасное место. По умолчанию получить доступ к ключам можно следующим способом, который можно изменить:

Мы будем использовать ключи как реального, так и тестового API, чтобы понять, как с ними работать. С целью не засорять реальный аккаунт установим доступ только для чтения для ключей реального API:

Сохранять ключи реального API мы будем в файл secret.cfg , как показано ниже. Не забывайте, что нельзя ни с кем делиться этим файлом.

Настраиваем тестовый API Binance

Тестовый API Binance полностью имитирует взаимодействие с реальным API. Рекомендуем для начала повзаимодействовать с ним, чтобы убедиться в корректности работы приложения.

Для начала необходимо войти в систему: https://testnet.binance.vision/ (на данный момент вход поддерживается только с GitHub).

Затем нажмите на Generate HMAC_SHA256 Key (Сгенерировать ключ HMAC_SHA256) и снова укажите метки для ключей. Отобразившиеся после создания ключи также скопируйте в безопасное место. Все подробности о тестовом API можно прочитать на главной странице.

Теперь добавим ключи тестового API в файл secret.cfg , как показано ниже:

Мы успешно настроили ключи реального и тестового API и сохранили их в файле secret.cfg . Теперь можно переходить к получению данных.

Как получить данные с помощью API Binance

Устанавливаем библиотеку python-binance

Binance не предоставляет библиотеку Python для взаимодействия с API. Поэтому мы воспользуемся популярным сторонним инструментом под названием python-binance .

Устанавливаем python-binance с помощью следующей команды:

Получаем информацию об аккаунте

В этом разделе мы воспользуемся тестовым аккаунтом. По умолчанию в нем будет отображаться баланс различных криптовалют. У python-binance нет доступа к тестовому API, поэтому мы поменяем URL-адрес конечной точки.

Код ниже предоставляет информацию о тестовом аккаунте:

Мы получаем такие важные данные, как тип аккаунта ( accountType ), баланс, разрешение и прочие.

Читайте также:  Сущность бизнес плана инвестиций

Теперь получим баланс ETH:

Библиотека python-binance предоставляет много возможностей. Подробную информацию о ней можно найти в документации.

Получаем архивные данные

Тестовый API выдает фиктивные архивные данные. Поэтому мы воспользуемся реальным API и его ключами.

Ниже показано, как получить стоимость ETH на Binance с самой ранней даты до текущего дня:

Вывод выше представляет следующие параметры, упомянутые в документации Binance API:

Преобразовываем полученные данные в датафрейм и сохраняем его как файл CSV:

Получаем данные в реальном времени

Чтобы передавать данные в реальном времени, можно воспользоваться WebSocket Binance. Вот как это сделать:

Ниже показано, как остановить потоковую передачу данных и закрыть WebSocket:

Итак, мы научились получать данные несколькими способами. Теперь можно переходить к созданию дашборда Plotly.

Как создать дашборд с помощью Plotly

В этом разделе мы создадим дашборд с помощью Plotly, который будет отслеживать криптовалютный портфель тестового аккаунта в реальном времени и изменять его общую стоимость в зависимости от получаемых данных.

Вот как будет выглядеть финальная версия дашборда. Детали внешнего вида можно изменить позднее:

В дашборд включены следующие функции:

  • Индикатор: общая стоимость портфеля в USDT.
  • Индикатор: общая стоимость портфеля в BTC.
  • Индикатор: конвертация BNB/USDT.
  • Круговая диаграмма: распределение портфеля (в USDT).
  • Столбчатая диаграмма: распределение токенов.

Теперь рассмотрим код.

  1. Импортируем все необходимые библиотеки:

2. Прочитываем все ключи, устанавливаем соединение и получаем информацию об аккаунте:

3. Определяем функции, которые будут обрабатывать потоковые данные и рассчитывать показатели на их основе:

4. Начинаем передавать данные в реальном времени:

5. Определяем макет, графики и хостинг:

Вот и все! Этот код позволяет отслеживать криптовалютный портфель тестового аккаунта. Его можно с легкостью настроить и для реального аккаунта без изменения URL-адреса конечной точки.

Весь код можно найти в репозитории на GitHub.

Источник

Binance futures api php

Larislackers-BinanceApi is a Binance.com API wrapper for PHP. Moreover, the API wrapper supports all available functionality given from Binance along with sockets.

All requests are following the HTTP/1.1 protocol and all responses are returned as a PSR-7 ResponseInterface.

Tests are available after providing your key and secret in the corresponding class.

Information on how to obtain your API key and secret from Binance can be found here.

First things first, in order to use the API wrapper you should initialize it with the aforementioned key and secret like this:

Then, use the initiated object/var like this:

You may find the rest of the supported commands inside the BinanceApiContainer.

All parameters required for each function must be in array format. More information can be found in the comments (phpdoc) and the links to the corresponding functions documented at Binance.

Avoid to use hardcoded values; enums are available (for intervals, types, sides, etc) for consistency and compliance with the Binance API.

You should use your own logger (like Sentry) and catch BinanceApiException for exceptions returned from Binance API and LarislackersException for exceptions returned from Websockets.

Don’t reinvent the wheel by trying to cache results in a request lifecycle with static classes. Use a framework that supports caching (like Laravel), an extension (like Memcached) or using files. Additional information can be found here.

More information on how to use the library can be found here.

See the official API documentation for more information about the endpoints and responses.

Larislackers-BinanceApi is open-sourced software licensed under the MIT license

If you find this library to your liking and enjoy using it, please consider a donation to one of the following addresses:

  • BTC: 13rSaL7ze89Pz28fNR9cNCnNVNvLWR3eFt
  • ETH: 0x03d4566d13ca7c7b30c39666b1f21ff97bee3f97
  • XMR: 49hxHRNwLSdQcXuCcac3ySMnAEuH4BhLWR8NddjHi6QBJHNvj1LqcSg2X8qpTQgsE1brzt37W6dLiiSN6uCj1CwyUPNr8R5

About

A PHP wrapper for the Binance API endpoints.

Источник

Оцените статью