Trading with Poloniex API in Python

Poloniex is a cryptocurrency exchange, you can trade ~80 cryptocurrencies against Bitcoin and a few others against Ethereum. I chose to trade on Poloniex because it supports a lot of currencies and the liquidity is usually very good, we can easily implement an algorithmic trading strategy on this exchange.

The most traded currencies are:
– Bitcoin (BTC)
– Ethereum (ETH)
– Monero (XMR)
– Tether (USDT)

The Setup

Fortunately for us, Poloniex provides an API to get market data, to get balances for each currency and to send buy/sell orders to the market. You can find a documentation here.

I found a Python wrapper for their API on GitHub, this one is super easy to use.
You can install the package like this:

pip install https://github.com/s4w3d0ff/python-poloniex/archive/v0.3.5.zip

Once it’s installed, you need to insert the appropriate import in your code:

from poloniex import Poloniex

Now you need to get an API key in order to be able to retrieve your account balances and to send orders to the market. If you just want to get market data you can skip that part.
Go to https://poloniex.com/apiKeys , click on Create new key, now you have the API key and you may need to get some email validation to see the secret key (which you also need). Check the options you want, if you want to trade via the API, just select the appropriate check box, same for withdrawals.

Using the API

In your code, you need to set up the connection so that you can get authenticated. You can just use the commented line if you only want to access the public API:

apiKey = "API_KEY"
secret = "SECRET_KEY"
polo = Poloniex(apiKey, secret)
# polo = Poloniex()

If you want to get market data for a ticker:

market_data = polo.returnTicker()['BTC_ETH']
bid = market_data["highestBid"]
ask = market_data["lowestAsk"]
volume = market_data["baseVolume"]

Now to send an order, it’s pretty simple:

pair = "BTC_ETH"
price = 0.1
order = polo.buy("BTC_ETH", price, 1)
order = polo.sell("BTC_ETH", price, 1)

You’ll get an order object in JSON, resultingtrades is an array of trades generated by the order, the order can be filled straight away with multiple trades:

{‘orderNumber’: ‘0000000’, ‘resultingTrades’: []}

To manage your risks, you’ll need to retrieve your balances:

balance = polo.returnBalances()
print("ETH="+str(balance ["ETH"]))

With this basic API you can code any algorithmic strategy in Python for Poloniex, you can try to predict the value of a cryptocurrency using our previous tutorials for example.

Using feature selection to improve a machine learning strategy

For this tutorial, we’re going to assume we have the same basic structure as in the previous article about the Random Forest article. The idea is to do some feature engineering to generate a bunch of features, some of them may be useless and reduce the machine learning algorithm prediction score, that’s where the feature selection comes into action.

Feature engineering

This is not a tentative of a perfect feature engineering, we just want to generate a good number of features and pick the most relevant afterwards. Depending on the dataset you have, you can create more interesting feature like the day, the hour, if it’s the weekend or not etc.
Let’s assume we only have one column, ‘Mid’ which is the mid price between the bid and the ask. We can generate moving average for various windows, 5 to 50 for example, the code is quite simple using pandas:

for i in range(5, 50, 5):
data["mavgMid"+str(i)] = pd.rolling_mean(data["Mid"], i, min_periods=1)

This way we get new columns: MavgMid5, MavgMid10 and so on.
We can also do that for the moving standard deviation which can be useful for a machine learning algorithm, almost the same code as above:

for i in range(5, 50, 5):
data["stdMid"+str(i)] = pd.rolling_std(data["Mid"], i, min_periods=1)

We can continue with various rolling indicators, see the full list here. I personally like rolling_corr() because in the crypto-currencies world, correlation is very volatile and contains a lot of information, especially for inter exchange arbitrage opportunities. In this case you need to add another column with prices from another source.

Here is an example of a full function:

def featureEngineering(data):
# Moving average
for i in range(5, 50, 5):
data["mavgMid"+str(i)] = pd.rolling_mean(data["Mid"], i, min_periods=1)

# Rolling standard deviation
for i in range(5, 50, 5):
data["stdMid"+str(i)] = pd.rolling_std(data["Mid"], i, min_periods=1)

# Remove the 50 last rows since 50 is our max window
data = data.drop(data.head(50).index)

return data

Feature selection

After the feature engineering step we should have 20 features (+1 Signal feature). I ran the algorithm with the same parameters as in the previous article, but on XMR-BTC minute data over a week using the Crypto Compare API (tutorial to come soon) and I got the decent score of 0.53.

That’s a good score but maybe our 20 features are messing with the Random Forest ability to predict.

We’re going to use the SelectKBest algorithm from Sci-kit learn which is quite efficient for a simple strategy, we need to add some import in the code first:

from sklearn.feature_selection import SelectKBest, f_classif

SelectKBest() takes 2 parameters at minimum: an algorithm, here we picked f_classif since we’re using Random Forest Classifier and the number of features you want to keep:

data_X_train = SelectKBest(f_classif, k=10).fit_transform(data_X_train, data_Y_train)
data_X_test = SelectKBest(f_classif, k=10).fit_transform(data_X_test, data_Y_test)

Now data_X_train and data_X_test contains 10 features each, selected using the f_classif algorithm.

Finally the score I got with my XMR-BTC dataset is 0.60, 6% is a pretty nice improvement for a basic feature selection. I picked 10 randomly as a number of feature to keep, but you can loop through different number to determine the best number of features, but be careful of over fitting!

Common Mistakes to Avoid When Cryptocurrency Trading

This article by Steven Buchko was originally published at CoinCentral.com

Whether you’re a crypto expert or just getting your feet wet with investing, there’s plenty to be aware of when trading your way through the cryptocurrency industry. Unlike in traditional markets, cryptocurrency trading is chock full of volatility, nefarious players, and irrational price movements.

In this article, we’ll teach you about some of the common mistakes in cryptocurrency trading and how you can avoid them.

Mistake #1: Chasing Pumps aka FOMO

Probably the most common (and easiest) mistake to make in cryptocurrency trading is buying into a coin after it’s already risen a significant amount. Investors that bought into Ripple (XRP) and Tron (TRX) at the peak of their runs in 2017 definitely felt the pain just a few weeks later in 2018. It may be your instinct to throw some money in the ring when you see a coin shoot up 30-40% because it’s “hot.” Don’t.

ripple fomo chart

Extreme increases in price are almost always accompanied by some type of pullback. By the time you hear about a “hot” coin, it’s usually too late. Unless you’ve done your research, believe in the fundamentals of the coin, and want to hold it for the long-term (>1 year), wait until the pullback to invest.

Pump and Dumps

Pump and dumps (PnDs) are a special breed of pumps that are guaranteed to leave you burned. If you see an unknown coin skyrocket all of a sudden, be wary. It’s most likely part of a PnD scheme. They’re basically coordinated efforts to artificially drive up the price of a coin (the pump) before selling it to those who FOMO’d in (the dump).

When you come across a coin like this, the first thing to check is the trading volume. CoinMarketCap is a great resource for this. Any 24-hour trading volume under $1 million should raise a red flag.

Mistake #2: Not Knowing Your Investments

Don’t just blindly follow the advice of some Twitter or YouTube “guru” for investment picks. Many times, these high-profile individuals are paid to promote certain coins. Even John McAfee, one of the most well-known figures in the space admitted that he gets paid to promote projects. Question the coins that you’re told to invest in.

At the bare minimum, you should devote a half hour to researching any project in which you plan to invest in. Check out what problem it’s attempting to solve, the team building it, and the economics of the coin. Has the project partnered with anyone significant? Any notable names as advisors? These are all things you should know.

Even a quick Google search could unveil some information that turns what may seem like gold into trash. Taking it a step further, you should ideally read the white paper of each project you invest in.

bitconnect scam google search

Joining or forming an investment group can do wonders to help with this. It forces you to do research so you can explain your investment reasoning to your peers. It also puts you an environment in which you have to challenge your assumptions as others question your reasoning.

Mistake #3: Selling At Inappropriate Times

The opposite of chasing pumps, emotion-driven selling is still cut from the same cloth. It’s difficult, but you need to stay level-headed when trading – keep emotions out of it. Time and time again, coins have dipped down double-digit percentages before rocketing to 200-300% gains.

When a coin you own starts to drop in value, before you sell, re-evaluate your position. If you invested because you believe in the coin’s fundamentals, there are a few questions you can ask yourself:

Have any of the fundamentals changed?
Were there any announcements that would have affected the price?
Have you stopped believing in the long-term vision of the coin?

If your answer to all of these questions is “No”, then consider holding on. This strategy becomes much easier when you follow the golden rule of cryptocurrency trading: Don’t invest more money than you’re comfortable losing.

On the other side of this equation, seeing some solid gains may also tempt you to sell. Although taking profits is wise, you may want to avoid selling your entire stack. Depending on the situation, the coin could rise further. A popular trading strategy is to take out your initial investment while keeping your earnings invested in the coin after gaining a certain percentage. This decreases your downside risk while still exposing you to the upside potential.

Mistake #4: Being Uninformed

In a market that moves as rapidly as cryptocurrency does, you need to stay up-to-date with industry news. Without tuning in weekly, or even daily, the investment tides could shift without you even knowing.

Twitter, Reddit, and projects’ Telegram channels are also great resources you can use to stay informed. Oftentimes, teams share project updates and important announcements on these platforms before they hit mainstream media. Joining these communities also gives you the opportunity to be more involved with the projects while sometimes even impacting future development.

Good Luck Out There

Even with these tips, there’s bound to be mistakes that you make. Don’t let that discourage you – it happens to everyone. Part of the investing process is to learn from those mistakes and not make them again.

Continuous improvement is the name of the game. And, as long as you’ve got that going for you, you’ll be a trading whiz in no time.