crypto strategy

How to Create a Profitable Cryptocurrency Trading Bot (Part 1: Overview and Trading Strategy)

The logo for alpaca.markets

In this guide, we will attempt to create a cryptocurrency trading bot using TradingView, Alpaca Trading API, and Python. In this first part, we’ll go over our setup and create/backtest a strategy on TradingView that we’ll use to send buy and sell signals to the REST API we’ll build in part two. Let’s get straight to the point!

Our setup for this bot will be quite simple. We will create our trading strategy on Tradingview, configure buy and sell alerts for our strategy, create, dockerize and deploy a Python REST API that will receive alerts and execute trades on our Alpaca trading account.

Why TradingView?

With Tradingview, we can quickly view and test trading strategies without much effort. It also reduces the additional latency/difficulty (not that it matters for this particular example) that would otherwise be introduced if we had to manually get stock data, calculate indicators, and look up inputs/outputs. Note that the web callback alert feature on TradingView requires a premium subscription to TradingView, if you don’t want to do this and want to manually calculate the indicators and look for entry/exit comments below and I will post a Another guide on how to do so for free from Alpaca’s web socket API. If you are interested in TradingView premium (which I highly recommend), please consider signing up with my link here!

Why Alpaca?

Alpaca offers simple and modern API solutions to allow anyone, individual or company, to connect applications and create algorithms to buy and sell stocks or cryptos. This means that we can execute our transactions programmatically with only a little bit of work. Oh, and the best part? No minimum account or commission! They also offer paper trading accounts, on which I highly recommend trying out the trading API before risking real capital.

We will be trading the MATIC/USDT pair. Why? No particular reason other than the fact that it is supported by Alpaca and MATIC is currently one of my favorite projects. When you finally come up with your own strategy, you can choose the currency pair you want.

Our strategy for this project will be relatively simple which I have been playing with. It is basically a 9 and 21 period EMA crossover strategy that uses the Average True Range (ATR) indicator to set a profit (at 2x ATR + entry candle high) and a stop loss (at candle low input – 1x ATR). If you want to know more about the ATR indicator, read my article about it here! If you want to try the strategy without having to code it, you can find it here!

//@version=5
strategy("Helix", overlay=true, calc_on_every_tick = true, initial_capital = 100, default_qty_type = strategy.percent_of_equity, default_qty_value = 5, max_bars_back = 100)

ema_fast = ta.ema(close, 9)
ema_slow = ta.ema(close, 21)

ATR = ta.atr(14)
plot(ema_fast, color = color.aqua)
plot(ema_slow, color = color.fuchsia)

co = ta.crossover(ema_fast, ema_slow)
exit = ta.crossunder(ema_fast, ema_slow)

if (co)
strategy.entry("BUY", strategy.long, comment="BUY")
if(exit)
strategy.exit("SELL", from_entry = "BUY", qty_percent = 100, stop = low -1 *ATR, profit = high + 2 * ATR)

Let’s break this strategy down line by line:

//@version=5
strategy("Helix", overlay=true, calc_on_every_tick = true, initial_capital = 100, default_qty_type = strategy.percent_of_equity, default_qty_value = 5, max_bars_back = 100)

Trading strategies are written in a language called Pinescript. Here we upgrade to the version of Pinescript we are using at version 5. We then let tradingview know that we want to create a strategy using the strategy()function. Here are the parameters of our strategy:

  1. The first parameter of our strategy is our title. It’s quite arbitrary. I decided to name this one Helix.
  2. overlay=true this means that when we draw our indicators, we want them to be displayed
  3. calc_on_every_tick=trueSpecifies whether the strategy should be recalculated on every tick in real time. If true, when the strategy runs on a bar in real time, it recalculates each time the chart updates.
  4. initial_capital=100 Specifies the amount of money we want to use to test our strategy before using real money
  5. default_qty_type=strategy.percent_of_equity Specifies how to allocate the money we want to use per entry for backtesting. Here we will use one percent of the initial_capital for each profession.
  6. max_bars_back=100 This function defines the maximum number of bars available for the historical reference of a given built-in or user variable.
ema_fast = ta.ema(close, 9)
ema_slow = ta.ema(close, 21)
ATR = ta.atr(14)

The TA namespace contains the majority of the flags and functions that we will be using. Here we first use the EMA function to calculate the 9-period and 21-period EMA based on the closing price. We then use the ATR function to calculate the ATR over 14 periods.

plot(ema_fast, color = color.aqua)
plot(ema_slow, color = color.fuchsia)

Here we use the plot function to display our two calculated EMAs on the price chart.

co = ta.crossover(ema_fast, ema_slow)
exit = ta.crossunder(ema_fast, ema_slow)

Here we define the entry and exit conditions of our strategy. We say that co is true when the fast ema intersects the slow ema, and exit is true when the fast ema passes below the slow ema.

if (co)
strategy.entry("BUY", strategy.long, comment="BUY")
if(exit)
strategy.exit("SELL", from_entry = "BUY", qty_percent = 100, stop = low -1 *ATR, profit = high + 2 * ATR)

Here we actually enter and exit the long position based on the conditions we set in the previous step. We enter a long position (nicknamed “BUY”) when the entry condition is true. And we open a sell order on 100% of our open “BUY” position when the price crosses below the low of the entry candle – 1 * ATR (stop loss) or crosses above the high + 2 * ATR (take profit)

If all goes well, after adding the strategy to your chart using the “Add to Chart” button, it should look like this:

Example of what our strategy will look like

You can play with the intervals in your strategy, but for our chosen example of MATIC/USDT, it works best on the 4-hour interval, so that’s what we’ll be using. Even though our strategy is relatively simple, it is nonetheless powerful! If we go to the strategy tester tab at the bottom, we can see the performance of our strategy.

Let’s break down what these metrics mean:

  1. net profit: The overall profit or loss generated by our strategy. For us, we got about 42.94 USDT in profit on this strategy, which is about 43% of the initial capital we used for backtesting (100 USDT)
  2. Total Closed Deals: The total number of trades opened and closed by our strategy. This number includes both winning and losing trades.
  3. Profitability percentage: The percentage of open trades that were profitable. We’re currently sitting at around 78% profitability, which is pretty good! This means that out of the 117 trades opened by the strategy, 91 of the trades made money.
  4. profit factor: Gross profits divided by gross losses. This means that for every 1 USDT lost by the strategy, it returned approximately 3.668 USDT.
  5. Maximum reduction: This is an important measure that shows the amount of money lost in the biggest loss compared to its highest profits.
  6. Average trade: Average profit or loss per trade. This is the net profit / number of transactions.
  7. Average number of bars in trades: The number of bars elapsed between the opening and closing of a trade. Note that we are on the 4 hour time frame, so 30 bars means that on average our strategy closes a trade 4*30 = 120 hours or 5 days after opening it.

In this short guide, we’ve covered how to create and test a simple yet effective trading strategy on TradingView. In the next part, we will see how to configure alerts on our strategy and work on building the python REST API that will read our alerts and execute our commands for us in our Alpaca. I’m very excited about this series, and I hope you all enjoyed reading it as much as I enjoyed writing it for you. Please share and follow, so you don’t miss part 2 next week 🙂 Have a fantastic day.

Thanks for reading, please 👏 and share to help others find it. Follow me on Twitter for new content and free tech support @greg_jobs_

See you soon. 😃



#Create #Profitable #Cryptocurrency #Trading #Bot #Part #Overview #Trading #Strategy #crypto strategy

Related Articles

Back to top button