# # Introduction
#
# This notebook shows how to run a strategy against feeds from the Binance crypto exchange using the **roboquant** algo-trading framework. 
#
# <img src="https://upload.wikimedia.org/wikipedia/commons/1/12/Binance_logo.svg" alt="Binance" width="400"/>
#
# Roboquant includes a dedicated module for crypto trading and this module also includes the support for Binance.
# There are two types of feed supported, both based on the spot market prices:
#
# - Historic feed with price bars (candlesticks)
# - Live feed with price bars
#
# We start with the following three steps to load everything required:
#
# 1. As always, we load roboquant using the ```%use``` cell magic. This will retrieve all the required roboquant packages the first time it is invoked, and imports the most commonly used functionality. Depending on your internet speed, this might take a few seconds.
# 2. The Welcome() statement is optional, but it provides some insights into the used environment and available memory.

%use @http://roboquant.org/roboquant-crypto.json
Welcome()

# + [markdown] tags=[]
# # Binance Historic Feed
#
# We start with retrieving historic data from Binance. We have to pass two types of parameters: 
#
# 1. One or more currency pairs we are interested in. In this example we are interested in Bitcoin (BTC) and ether (ETH), both trading against the Binance USD (BUSD).
# > Please note how we defined a currency-pair: currency1-currency2
# 2. The timeframe that we want to retrieve, in this case we select the past calendar 500 days.
# > Please note that the Binance API has limits imposed, so too large timeframes are not allowed. 
#
# ### Optional parameters
# There are also several optional parameters available:
# - The interval, default being DAILY. But you can define many other values. You can use code completion to see the available values.
# - Limit the number of candelsticks to be returned per currency pair, default is 1000
#
# So a more eloborate call could look something like this:
#
# ```Kotlin
# feed.retrieve("BTCBUSD", "ETHBUSD", interval = Interval.FIVE_MINUTES, timeframe = tf, limit = 250)
# ```
#
# -

val feed = BinanceHistoricFeed()
val tf = Timeframe.past(500.days)
feed.retrieve("BTCBUSD", "ETHBUSD", timeframe = tf)
feed.timeframe

# ## Charts
#
# Lets plot the data we just received. Since the feed can contain multiple assets, we also need to tell the chart which asset to draw.
#
# Chart in roboquant are fully interactive, you can zoom and move the mouse to see details. In the top right part of the chart there is a toolbox with more options available.
#
# > There is a dedicated notebook called ```visualization.ipynb``` that shows the different available charts

for (asset in feed.assets) PriceBarChart(feed, asset).render()

# # Run Back-test
# We now create the other components we want to use. 
#
# - We start with defining a simple strategy that uses moving average crossover to generate BUY and SELL signals.
# - Because we won't be using USD as a base currency, we create a new SimBroker instance with an initial deposit of 1.000.000,- Binance USD (BUSD). We could also have used the default ```SimBroker``` with 1 million USD initial deposit. But in that case we would have needed to define the exchange rate from USD to BUSD, since we going to trade Bitcoin and Ether denominated in BUSD. 
# - We also define a metric  that will help afterwards to validate the performance: ```AccountSummary()```

# +
val strategy = EMACrossover.EMA_12_26
val broker = SimBroker(1_000_000, "BUSD")
val roboquant =  Roboquant(strategy, AccountSummary(), broker = broker)

roboquant.run(feed)
# -

roboquant.broker.account.summary()

val logger = roboquant.logger
logger.metricNames.summary()

# Lets see how the overal value of our account (= cash + positions) did during the back test.

MetricChart(logger.getMetric("account.equity"))

# We will now plot again the historic prices but this time also plot the actual trades that happened as part of our run. So you can easily see when a trade occured in time and the amount traded.

PriceBarChart(feed, feed.assets.last(), broker.account.trades)

# # Binance Live Feed
# Now we create an instance of the `BinanceLiveFeed` and subscribe to pricebar events (candlesticks) of the the BTC/USDT currency pair. It is also possible to subscribe to multiple currency pairs by providing additional parameters to the same ```subscribePriceBar``` method.  Optional you can also specify an interval, the default being 1 minute price-bars. 

val feed = BinanceLiveFeed()
feed.subscribePriceBar("BTCUSDT")

# # Run Live Test

# We use almost the same setup as in the previous section using the historic data, but this time we also add the EventRecorder. This metric will capture the received events from the live feed, so we can inspect them afterwards.

val strategy = EMACrossover(3, 5, minEvents = 3)
val broker = SimBroker(1_000_000.00, "USDT")
val eventRecorder = EventRecorder()
val roboquant =  Roboquant(strategy, AccountSummary(), eventRecorder, broker = broker)

# Because it is a live feed we have to specify for how long we want to run it otherwise it would run forever until interrupt the execution. In this case we run it for 60 minutes, but you can run it of course for any duration. If you run it for a short time, it is less likely that the used strategy will generate signals and as a result you won't see any trades or changes to the portfolio. 
#
# All that remains is to start the run and get some coffee. 

val timeframe = Timeframe.next(45.minutes)
roboquant.run(feed, timeframe)

val asset = feed.assets.first()
val account = roboquant.broker.account
PriceBarChart(eventRecorder, asset)

PriceChart(eventRecorder, asset, account.trades)

val accountValue = roboquant.logger.getMetric("account.equity")
MetricChart(accountValue)

# # Binance Paper Trading
# This is still very much work in progress and is currently not available. However the goal is that once released, you can also place and manage orders on Binance using roboquant. Instead of the ```SimBroker``` used in the above examples, you only need to specify ```BinanceBroker``` and you will be able to do paper- and live trading. 
#
# There is already some ground work done, so have a look at the roboquant source code if you want to see what is already there and perhaps contribute some code.



StarcoderdataJupyterScriptsDedupFiltered