Testing Trading Strategies using Binance testnet API
Algo traders most often test their strategies before jumping into live trading. Backtesting certainly helps to evaluate and to estimate the performance and the risk of trading strategies. However, it is often required to examine trade strategies using a demo account with virtual money, as past performance is no guarantee of future results. In this article, I focus on cryptocurrency trading in Binance and explain how to test trading strategies there using a demo account.
Introduction
Binance provides test platforms for spot, future and vanilla options. Depending on the type of trading, any of these platforms can be employed to emulate strategies. In this post, I focus on spot trading and explain with an example how to use it on binance testnet platform. Note that there is one limitation of spot testnet platform currently, that is it resets the positions roughly every month. That might be problematic for low-frequency trading strategies. The advantage is, thanks to python-binance , the implemented strategy on testnet platform can be directly used for real live spot trading simply by changing the API key and the secret!
Before starting with the implementation, the environment must be set up. We need python 3 with package python-binance , an API key and an API secret to establish connection to the binance testnet. First, package python-binance is required to be installed. In a development environment with python 3, this can be done by:
The next step is to log into spot testnet platform. To do this, at the time of writing this post, it is required to have a github account. After login, click on Generate HMAC_SHA256 Key to create an API key and secret and then save them for later to be used in the algorithm. That is all we need.
Strategy implementation
Now it is the time to implement a simple strategy, which is the “hello world” trading algorithm moving average crossover. The idea is to keep track of moving price average of an asset for a long- and a short-term period, then, use these values to determine when to enter and exit the market. When the short-term moving average goes above the long-term moving average we will go long; otherwise we go short, of course if we hold a position in the asset. The following parameters are defined for the strategy:
- g_symbol is the symbol name of the asset,
- g_cycle is the operating cycle of the algorithm in seconds, that means every g_cycle second(s) the algorithm takes the most recent asset price, updates the moving averages and submits orders if any,
- g_longterm is the number of cycles of the long-term moving average. For instance if it equals 50 with g_cycle being 60, the average over the last 50 minutely prices will be computed as the long-term moving average,
- g_shortterm is the same as g_longterm but for the short-term moving average,
- g_quantity is the number of shares of the asset in buy and sell orders.
The complete implementation of the algorithm comes below. The code block to define all of the parameters is located between line 4 to 9.
The logic of the algorithm is implemented in SmaCrossOver class. The class also handles establishing and closing the connection to the binance testnet platform. Moreover, it continuously fetches the current price of the asset to be used for computing the short- and the long-term moving averages. The class handles its requests to binance platform in an asynchronous manner. That is why, all of its method definitions are followed by async keyword. It implies that the methods can operate concurrently, specially if the response to a request in a method is not ready yet, it does not block the execution of the other methods. For instance, while fetch_price should wait to get the latest price of the asset, the execution can switch to run to update moving averages on already available price data. This way leads to making better use of CPU cycles by avoiding unnecessary waiting time. The two main methods of the class are explained in detail.
fetch_price uses websocket to fetch price information of the asset continuously using method symbol_book_ticker_socket of class BinanceSocketManager . The price information contains the current price and the quantity of the asset available for sell (bid) or buy (ask). This information is actually the head item in the corresponding order book, which is stored in self._price_info as a dictionary:
run executes the algorithm. Each cycle, it gets the newest price data, which are fetched by fetch_price and computes the moving averages. At the beginning the algorithm waits for the first g_longterm price ticks to come such that it has enough data points to compute the moving averages. Afterwards, in each cycle it updates the moving averages, then compares them and submits the appropriate order if they cross each others. It is done between line 54 to 68.
Now it is the time to put all the pieces together to execute the algorithm, which is done in function main . It creates an instance of class SmaCrossOver , which needs the API key and the API secret generated by binance testnet platform. Note that one can also pass those from binance spot platform and set testnet to False to go live with real money instead of virtual one. After creating an instance of SmaCrossOver , the function executes fetch_price and run methods concurrently using async.gather in line 84, which actually runs the strategy.
Conclusion
Binance provides platforms to test trading algorithms with virtual money. This enables an strategy to be evaluated in a setting that is very close to the real trading environment with live price data. Testnet platform is well supported by python-binance package. The implemented algorithm can be used for real live trading only by changing the API key and secret and resetting a flag.
Развертывание смарт-контрактов в смартчейне Binance с Truffle

Это четвертая и последняя статья в серии, в которой мы создаем DApp с нуля с помощью специально созданного смарт-контракта BEP-20.
В этой статье мы рассмотрим, как развернуть смарт-контракт в тестовой сети Binance вместо нашего локального экземпляра Ganache.
-
— эта статья поможет вам понять основы Solidity — вторая статья, в которой мы рассмотрим более сложные элементы Solidity и реализуем стекинг и вознаграждение. — третья статья из серии, в которой мы узнаем, как подключиться к цепочке блоков через веб-приложение с помощью MetaMask.
- [Развертывание смарт-контрактов в смарт-цепочке Binance с помощью Truffle] — четвертая и последняя статья, в которой мы узнаем, как развернуть наш смарт-контракт в реальных сетях.
Вы можете найти полный код из предыдущих частей здесь.
Мы начнем с обновления конфигурации Truffle в нашем truffle-config.js. Мы откроем три сети, чтобы мы могли развернуть их во всех трех сетях. Самую свежую информацию о развертывании, которая указывает на правильные исходные данные для сетей, можно найти здесь. Нам также нужно будет использовать поставщика трюфелей / hdwallet, который вам необходимо загрузить.
После этого нам нужно раскомментировать поля module.exports и добавить следующие три сети.
Прежде чем это сработает, вы должны заметить, что мы читаем файл с именем .secret. Этот файл должен содержать только одно — вашу мнемонику.
Это список слов, которые используются для доступа к вашему кошельку. Считайте это паролем, но длинным. Вы должны были получить начальную фразу при создании учетной записи в MetaMask. Но если вы его забыли, вы можете просмотреть его, перейдя по этой ссылке.
Развертывание в TestNet
Если вы вставили мнемонику в файл .secret, пора попробовать развернуть смарт-контракт. Мы начнем развертывание в TestNet, чтобы увидеть, насколько легко это развернуть. Теперь причина развертывания в TestNet заключается в том, что он будет работать как тест, чтобы убедиться, что смарт-контракт работает должным образом.
Тестовая сеть — это полная копия реальной производственной сети, поэтому это отличный способ все опробовать. Его использование позволит нам также иметь среду разработки (Ganache), Test (Testnet), Production (настоящая интеллектуальная цепочка Binance).
Помните, как мы запускали truffle migrate для развертывания в Ganache?
Самое прекрасное здесь то, что для развертывания в тестовой или производственной среде мы можем использовать ту же процедуру, просто добавив в команду флаг — network и укажите, в какой сети развертывать. Помните, что для перехода к тестированию и производству вам придется платить за газ.
Попробуйте запустить команду, чтобы увидеть, что произойдет. Если вы используете новую учетную запись MetaMask, как я делал в этой серии статей, вы увидите следующее.

Причина в том, что, как я уже много раз повторял, развертывание смарт-контракта стоит затрат. Помните об этом, если вы отправите смарт-контракт в реальную смарт-цепочку Binance, он привлечет ваши деньги.
Но мне не нужно платить за развертывание для тестирования! — Дешевый застройщик
К счастью для нас, в тестовой сети есть сборщики, которые позволяют бесплатно получить тестовый Ethereum. Давайте подключим MetaMask к тестовой сети, добавив еще одну сеть. Сеть является официальной тестовой сетью Binance. Если вы забыли, как добавить Сеть, перейдите к третьей статье этой серии или прочтите здесь.
При добавлении настраиваемого RPC используются следующие сетевые данные.
Имя сети: Smart Chain — Testnet
Новый URL RPC: https://data-seed-prebsc-1-s1.binance.org:8545/
ChainID: 97
Символ: BNB
URL-адрес обозревателя блоков: https: // testnet .bscscan.com
После того, как вы добавили это, возьмите адрес своей учетной записи, щелкнув учетную запись в MetaMask.
Посетите официальный смарт-кран TestNet, который дает вам жетоны для использования. Просто введите свой адрес и нажмите Дайте мне BNB. Подождите несколько секунд, и ваша учетная запись должна быть пополнена. Теперь вы должны увидеть, что у вас есть 1 BNB в MetaMask. Пора дать трюфелю новое вращение.
Примечание. Если у вас есть несколько учетных записей в MetaMask и вы предоставили бесплатные токены чему-то другому, кроме первой, вам необходимо указать учетную запись, которая будет использоваться во время миграции. Truffle по умолчанию использует первую доступную учетную запись. Добавьте в конфигурацию вашей тестовой сети следующее.
Снова запустите команду migrate для тестирования сети с учетной записью, на которую вы получили финансирование.

Поздравляем, вы развернулись в Testnet. Вы можете скопировать адрес контракта. Затем вы можете найти его в тестовом проводнике сети. Теперь вы можете добавить токен в MetaMask, чтобы просмотреть текущий баланс учетной записи. Выберите Добавить токен и введите запрашиваемую информацию, которая должна быть адресом контракта. Чтобы перейти на основную сеть, просто измените сеть в команде migrate на основную сеть, но не забудьте, что в вашей учетной записи должно быть достаточно газа.

Тестирование DApp в TestNet
Давайте попробуем DApp, который мы создали в части 3 этой серии статей, и посмотрим, работает ли он.
Перейдите к ужасной жестко запрограммированной функции getContractAddress, расположенной в App.js, и замените возвращенный ею контракт, чтобы он соответствовал вашему адресу смарт-контракта.
Если вы выбрали сеть TestNet в MetaMask и свою учетную запись, снова запустите DApp, используя

Просматривайте транзакции и события в проводнике Binance Testnet.
Давайте проведем Stake и посетим обозреватель тестовой сети, чтобы просмотреть информацию так же, как мы могли бы это сделать в Ganache.
После нажатия кнопки вам будет предложен запрос MetaMask.

Теперь дождитесь появления всплывающего окна MetaMask о том, что транзакция прошла успешно. Когда он появится, либо щелкните его, чтобы вызвать проводника, либо посетите проводник и найдите адрес жетонов.

Это приведет вас к проводнику, где вы сможете просмотреть все транзакции, которые происходят в смарт-контракте, а также все события.

Если вы перейдете на вкладку Events, вы также сможете увидеть запущенное событие Staked.
Заключение
Поздравляю! Если вы следовали всем частям этой серии, значит, вы создали свой первый DApp.
В сериале мы узнали
- Базовая твердость
- Реализована простая механика ставок.
- Реализована система вознаграждений
- Веб-интерфейс для использования и управления контрактом
- Как развернуть в тестовой и основной сети.
Надеюсь, вы чему-то научились. И спасибо, что прочитали!
Не стесняйтесь комментировать или отправлять мне сообщения, если есть какие-либо вопросы или отзывы.
Binance запустила тестнет для своей децентрализованной биржи. Зачем она нужна?
Крупнейшая криптобиржа запустила тестнет для собственной DEX и Binance Chain. CEO Binance Чанпэн Чжао заявил, что руководство компании ставит в приоритет скорость, безопасность и юзабилити своего нового проекта. Как и всегда, Чжао готовится занять доминирующее положение на рынке — Binance DEX должна стать лучшей децентрализованной биржей в индустрии.
Запуск Binance DEX
За последние 12 месяцев популярность DEX сильно упала на фоне коррекции крипторынка. По сути обычный пользователь должен торговать на децентрализованной бирже с таким же успехом, как и на обычной. Однако за последние пару лет так и не была сформирована тенденция массового перехода от традиционных централизованных торговых площадок к DEX.
Руководство компании обещает, что Binance DEX совместит в себе все лучшие качества обоих типов бирж. Трейдеры смогут получить полный контроль за своими средствами, а их торговые сделки будут выполняться с ещё большей скоростью.
DEX базируется на блокчейне Binance Chain, который должен стать основой для проведения всех операций на децентрализованной площадке. Чжао рассказал о некоторых преимуществах новинки.
Транзакции в Binance Chain совершаются практически мгновенно, генерация блока занимает не больше одной секунды. В сравнении с другими блокчейнами это лучшее решение. Binance DEX может обрабатывать такие же объёмы, как и наша основная биржа. Мы решили проблемы, с которыми ранее столкнулись другие децентрализованные обменники.
Стоимость нативной криптовалюты Binance Coin с конца января подскочила на 76 процентов с 6,2 до 10,97 доллара, что говорит о растущей заинтересованности инвесторов в новом проекте. Самую свежую информацию об обновлениях Binance DEX можно получить в нашем крипточате. За курсами монет рекомендуем следить в рейтинге криптовалют.
The Binance Smart Chain Testnet
The importance of protocol functionality testing.
![]()
![]()
As Lendefi takes steps towards the final two milestones along our development roadmap, it is important to understand the necessity and value of testing blockchain protocols.
The testnet process is a valuable aspect of a robust security regime that reflects Lendefi’s priority for user security. The upcoming testnet period is also a valuable time for Lendefi to stress test the protocol’s functionality.
Our launch onto the Binance testnet is set for the 28th of June and the mainnet launch is planned for the 12th of July.
Launched at the end of 2020, the Binance Smart Chain runs concurrently with Binance’s original Binance Chain in what is called a “dual-chain system”. It delivers numerous additional features to the Binance Chain and has enabled the integration of smart contracts and faster transaction speeds.
The Binance Smart Chain represents a significant value proposition when compared to the high gas fees currently in operation on the Ethereum network. This has compelled increasing numbers of investors and developers to utilize the Binance Smart Chain. The reduced transaction costs and faster speeds will positively impact the Lendefi user experience.
The Binance testnet functions as a testing environment for protocols before they move into full operation on the mainnet. It is open to developers and run by the Binance Smart Chain development community.
Testing the functionality of blockchain projects is an important step towards full mainnet operation. This process works in conjunction with the auditing process to identify any potential security risks and functionality issues. Rigorous testing is necessary to stress test the Lendefi protocol and ensure it is ready for launch onto the mainnet. This is in the interest of the Lendefi community and users.
The final aspect of the trilogy of security testing is the implementation of a robust bug bounty program. Lendefi’s bug bounty will reward individuals for identifying unidentified bugs within the system. The combination of auditing, testnet period and bug bounty program reflects Lendefi’s commitment to user security.
As Lendefi moves towards launch on the Binance testnet Lendefi will continue to provide our community with regular updates.
The Lendefi protocol will deliver leveraged trading and secured lending for cryptocurrency markets. Utilizing an undercollateralized loan model, Lendefi facilitates a trustless relationship between lender and borrower, managed by the protocol to remove counterparty risk.
For further information please join our global Telegram group, visit our website, join our Twitter feed or inspect our Gitbook documentation.