Python code to place trades with (a Japan) exchange – Part 3

In the present article I am continuing the construction of a trading bot in Python that I am suggesting is able to work 24/7 and to bring a positive result consistently. The goal is to implement no manual trades placed with the crypto-exchange (eventually manual trades will be only on exceptional basis i.e. just for testing the code), but only those originated by several pre-defined triggers (so far my trading strategy has only two criteria: RSI at extremes, i.e. RSI < 25 or RSI > 75 and increase (or decrease) in price by 0.1% from the previous candle – this trading strategy will be subject of further improvements). The code uses mainly the well-known ccxt library.

In the previous article (see PART 2) I have achieved the followings:

  • Once the “magic” tools (Python and “pip” utility) got installed and after that an open source library named “ccxt” was added (see PART 1), I have continued with opening an account with, created an API token and then I took advantage of reduced trading fees at Liquid exchange (50% discount … 👍 … if the trader has Qash in his/her account and does a proper setting to pay trading fees with Qash)
  • I have made a code snippet that lists all available pairs at exchange
  • I have defined my trading strategy
  • I started to assess two out of four available products in i.e. Spot Trading and Margin Trading. I have interrupted the previous article at the stage of assessing cost of borrowing funds when Trading with Margin.

I said in the previous article “Let’s hope for the best, but prepare for the worst” because trading crypto-assets i.e. a market in early stages of development is like wild west (too many have reported losses).

I strongly recommend to anyone willing to risk some money in this field (crypto currencies): don’t put more money in crypto-currencies than you cannot afford to lose (don’t borrow money from friends to buy crypto currencies or crypto assets, don’t sell your house, don’t do stupid things like that because crypto currencies markets will eat your hard earned money if you are a beginner in this space and if you don’t do your own research).

One important note: NOT A FINANCIAL ADVICE

I provide no financial advice, if you follow the trading strategy I use in this series of articles you will do it at your own risk.

Personally I put in this experiment an amount of money that I can afford to lose without that such a potential event (if it happens to lose that amount) to have dramatic consequences to my life.

In this article I am going to:

  1. depict the whole process of Margin Trading product at crypto exchange.
  2. continue with coding. So, I am set to achive the goals of trading in an automated way by exploring the ccxt (a library written in Python) and what it can provide as code to allow for Trading with Margin at

Margin Trading process at

So, for Margin Trading I have to take into consideration two types of interests:

  • opening interest
  • daily interest says on their website: “Both interests have one same rate which is decided by the lender”

The above screenshot is extracted from this link and the same source provides more details about the fee structure, as follows:

Ok, so either maker or taker it’s the same trading fee: 0.13%.

I picked up that range (>= 50k$) because the trading volume will exceed 50 000 USD thresold as a monthly volume. Calculations: I envisage to trade the entire amount of EUR 2000 per day (either in one trade or split it in smaller amounts and place many trades), so I am going to trade an equivalent of 2000 EURO daily, meaning 60k$ per month.

Digging more, I found that the interest rate (for both opening and daily) is not so significant at, so for your convenience I will ignore it for now. But when you sit down and take the pen and see that figures do not add exactly, keep in mind that it’s about this interest rate that completes the picture. You will probaly see I was right in saying those interests (both opening and daily) are not significant compared to the trading fees.

Margin trading it’s trading with leverage. What is this?

The best to understand this is by an example. So, lets suppose I want to place a trade with margin. This means 1) I have an amount of money (let’s say USD 2000) and 2) I borrow in addition from Liquid exchange an equivalent in Bitcoin of USD 2000. This is trading with leverage, the rate of leverage being named “2x” (signifying I place a trade with double amount of money I actually have in my account with

If that rate was 4x, then I might actually trade with 4 times the amount I own, I mean USD 2000 x 4 = USD 8000.

Of course, there are possibilities up to 25x to Trade with Margin at, but I will not touch those levels for reasons explained in my previous article: such a high leverage will wipe out your funds in a blink of an eye in case you are not sure what you are doing. Currently, although I am not a beginner in trading I am neither an expert. So, I am not certain that my trading strategy will provide a sufficient level of assurance in terms of a higher number of successul trades versus a lower number of bad trades (until actually I test it). Such testing is going to be done somewhere in the future. That is why I will I keep leverage at minimum (2x) for now.

You might ask why to trade with leverage? Is there a need to use 2x leverage? There is no need to use 2x, if there was available leverage of 1.5x I would have chosen 1.5x. Currently has 2x leverage as the minimum option available.

But the need to trade with leverage comes from what I want: to have the possibilty of shorting an asset. This way I can benefit from both increasing and decreasing in price of an asset and make profit even when an asset decreases in price (for beginners this is not so easy to understand, but I will offer more details below).

In fact, shorting an asset supposes that you own that asset. Margin Trading at offers to traders the possibility to borrow that asset (if you don’t have it already) and then short it.

I will explain in detail the whole process with longing and shorting assets.

To long an assets = to buy that asset. This is easy to understand: I dont’ have that asset, but I have USD 2000 and I buy the equivalent in Bitcoin – and I do it NOW (this is important to point out, you will see why).

No need to Trade with Margin in this case. However, I will use 2x leverage and Trade with Margin for the sake of simplicity in implementation of my Python code (besides, 2x is not such a huge leverage, so I am good with 2x).

LONG = I buy NOW and I sell LATER (when the asset will increase in price – hopefully). Profit (in USD) I gain from difference of price now versus later.

To short an asset = to sell that asset. I don’t have that asset, so I borrow Bitcoin (from and then what? Then, I sell it NOW and buy it LATER (when the asset will hopefully decrease in price).


SHORT = I sell NOW and I buy LATER (when the asset will decrease in price – hopefully).

Profit (in USD) I envisage to gain from the difference of price now (when I sell that asset that was just borrowed, i.e. Bitcoin, and I sell it at a higher price) versus later (when the asset will hopefully decrease in price), so this way I remain with an additional USD in my account.

Got it?

Remark: if the trader has no money to back up let’s say the quantity of Bitcoin he/she might want to borrow from an exchange (to be used further to short it), there are practically very slim possibilities to short an asset – because you do not get that Bitcoin lended to you if you don’t have a collateral (EURO, or USD, whatever). Therefore, you have to have some money in order to borrow Bitcoin and then short it. Your money will be used by the exchange to cover any loss incurred by your bad trades with borrowed assets (if any). I mean in this setup it’s like you have your money, you borrow more and you trade with the whole amount. Hence the product Margin Trading was born 😉.

I just hope now I have provided sufficient details to anyone willing to understand what I am going to do in my code and why I have chosen to Trade with Margin (i.e. to double my profits by also shorting assets, not only longing them).

Python code (with the help of ccxt) to place a Trade with Margin

Let’s code:

    'API_KEY': '9563846',
    'API_SECRET': '123456789101112131415161718192021222324252627282930313233343536373839404142434445464748=='

The above code is included in the file named: “”. You might want to replace some pieces of information in the code above, as follows:

API_KEY: instead of ‘9563846‘ – replace with the value of Token ID you have obtained from (see this article I wrote previously).

APY_SECRET: instead of ‘123456 …‘ – replace with the value of Token Secret you have obtained with the same occasion mentioned above.

The file “” has to be placed in the same folder with the following file:


The later has the content that follows below.


# Importing other Python libraries into our script / code. To be mentioned that those files that contain Python code (extention: *.py) are called “modules”.

import ccxt
import configAPIks     # this is the file I mentioned above
import time

# API Keys (Token and Secret) needed to authenticate in

api_keyValues = str(configAPIks.API_DETAILS['API_KEY'])
api_secretValues = str(configAPIks.API_DETAILS['API_SECRET'])

# Creation of ccxt instance of

bursa = ccxt.liquid({
        'apiKey': api_keyValues,
        'secret': api_secretValues,
        'enableRateLimit': True,

# Function to get the market price of any trading pair available at

def askBid(pair): 
	for i in rez:
		if i['symbol'] == pair:
			return [j['market_ask'],j['market_bid']]

# The above function provides a list that has two elements, i.e. the ask price and the bid price of the underlying asset (versus USD) at the moment when that function is called.

# Below is the main function to place a trade with either longing or shorting an asset – I have chosen Bitcoin (BTC) and Ether (ETH) as assets to trade and as Funding Currency (I will explain) I picked USDC (a crypto token pegged 1 to 1 to US Dollar, issued by Circle US).

def placeTradeLiquid(buySell, ETHorBTC, amountBTCorETH, percentTP, percentSL, percentTrailing):
		symbol = ETHorBTC+'/USD'
		amount = round(float(amountBTCorETH),6)
		type = 'trailing_stop'  # or market
		side = buySell
		mediaBidAsk=( float(a)+float(b) ) / 2
		price= round(float(mediaBidAsk),2)
		if buySell == 'buy':
			TP = round(  float(mediaBidAsk*(100+percentTP)/100),0)
			SL = round(  float(mediaBidAsk*(100-percentSL)/100),0)
		if buySell == 'sell':
			TP = round(  float(mediaBidAsk*(100-percentTP)/100),0)
			SL = round(  float(mediaBidAsk*(100+percentSL)/100),0)	
		print("TP = "+str(TP),"SL = "+str(SL))	
		order = bursa.create_order(symbol, type, side, amount, params={
			'trailing_stop_value': round(percentTrailing,1),
			'client_order_id': str(client_ordID),
			'take_profit': round(TP,2),
			'stop_loss': round(SL,2),
	except ccxt.InsufficientFunds as e:
		print('create_order() failed – not enough funds')
	except Exception as e:
		print('create_order() failed')


How to use the code for manual trading (just for the sake of understanding the code built so far)

In a new file (let’s say we create the file “” and place it in the same folder with “” and “” ) let’s put three lines of code:

from placeTradesAtLIQUID import placeTradeLiquid
manualOrder = placeTradeLiquid("buy", "BTC", 0.002, 1, 10, 0.15)

and … Bam! You placed your first trade with

Wasn’t that easy?

Let’s depict the parameters of the function named “placeTradeLiquid”, I mean what it is in the paranthesis at the second line of the file “”:

  1. “buy” means longing the asset. For shorting you can replace this by “sell”
  2. “BTC” is the name of crypto currency (or crypto asset) you want to long. In this case Bitcoin;
  3. 0.002 is the amount of Bitcoin you are longing. It’s the equivalent of approx USD 65 or USD 70 (at current prices)
  4. 1 is the percent of taking profit, i.e. how much you expect the price of Bitcoin to increase (compared to the buy price) to lock in some profit for you (we are in this for making money, right?);
  5. 10 is the percent of Stop Loss (if the trade goes unexpected, how much is the amount of loss – in percentage – of the whole stash you trade with at – by the “whole stash” I mean the entire amount of funds, i.e. formed by your own funds and the borrowed funds);
  6. 0.15 is the percent of trailing stop used for buying when the buy order is placed. This is a bit more complicated to explain, but I will do it in the More details section (see next).

Basically that’s all, I mean that was a manual trade you placed through the API of (once again: you placed a trade).

“Trade” – to be more precise – is formed by a buy and a sell. You buy the crypto currency and then you sell it hopefully for a profit (LONG asset) or you sell the borrowed asset and then you buy it (SHORT it) at lower prices (also for a profit) and you return the loan back to the lender.

By the way, the exchange has a list of assets to lend (at various interest rates) posted by lenders that traders use to borrow, but I recommend you don’t bother with this because these borrowing operations and reimbursements are all taking care off automatically for you by (the funds borrowed automatically within a trade are taken in the ascending order of their corresponding interest rates).

More details:

a) Funding Currency = this is the (crypto) currency of your choice used in Trading with Margin. In my example this is USDC (not USD), so a crypto token that is pegged 1:1 to US Dollar. In fact, almost 1:1, because there are slight variations when 1 USD is let’s say 1.001 USDC (sometimes), but this is not so relevant at this point. Funding Currency could be anything, including USD, EUR etc. Basically, from the definition of Marging Trading: “A margin trade is basically a bet, made with borrowed money …“. So, you bet on the increase of price of BTC/USD (Bitcoin versus US Dollar) and you use the Funding Currency (USDC) for that purpose (as a collateral from where the Liquid exchange will cover the loss in case you do a bad trade and lose that bet).

b) Funding Currency is also considered as your money for Trading with Margin. So, you have 2000 USDC and you borrow BTC in equivalent of 2000 USD (“2x”, remember?). And you trade with equivalent of 4000 USD to buy Bitcoin and sell it later (or short it).

c) You probably noticed this line of code: symbol = ETHorBTC+’/USD’, so the trading pairs are either “BTC/USD” or “ETH/USD”. So, you are betting on increase in price of BTC/USD (it could be also ETH/USD) for longing BTC or ETH or you bet for decrease in price (for shorting BTC or ETH) – in all cases with USDC as Funding Currency.

d) In this line of code: client_ordID=’Unique1’+client_ordID2+’Unique2′ you might want to replace Unique1 and Unique2 with some letters or figures upon your choice. This will ensure an order ID is uniqe each time a trade is placed. If the Liquid exchange finds out two orders with the same ID, the second trade is rejected. I made it unique also by what it’s in the middle, i.e. some figures generated by the code based on the time in milliseconds when that trade is placed. Anyway, not much trouble if you don’t change those (because the likelihood to place two orders by two traders that read this article, both ot them don’t bother to replace those Unique strings and each of them places a trade in the same millisecond … is … veeeery low).

e) You can change your leverage here: ‘leverage_level’:’2′. So, instead of 2 you can replace by 4, etc or whatever you want (maximum is 25).

f) Trailing stop. This is a percentage (in our case 0.15%) used when the buying takes place. It’s like this: I see now the market price for 1 Bitcoin is USD 30 000 (supposedly). I don’t buy now (not yet) because I want to maximise my profit in case the price goes lower i.e. under 30k$. When price effectively goes lower (let’s suppose this happens after 1 minute when BTC is USD 29k$ – don’t worry, it will not dump so fast, but I took a rounded figure for the sake of a better explanation), then nothing happens. But when the price from here (29k$ level) increases by 0.15% (this means to USD 29044), then… bam! the buy order is placed. Thus, you will have the trade placed at 1 Bitcoin = USD 29044. So, buying with Trailing Stop gives the trader a chance to buy at a lower price.

REMARK 1: this is a double-edge sword, meaning when the price goes only up after the trader placed the order with trailing stop, it will buy with 0.15% higher (compared to the moment when the order was placed). It depends on what the market does immediatelly after the trader places the buy order.

REMARK 2: there is also the possibility to place a trade without Trailing Stop, i.e. at the Market price. However, if market moves fast, there is a risk of slippage (this I am not going to explain as it’s out of the scope of this series of articles).

g) Trailing Stop is working the same in the opposite direction, I mean when the trader shorts an asset. I guess you can figure out now by yourself how trailing works. Anyway, the trader only needs to input that percentage of Trailing Stop and it’s an automatic process that is taken care off for you by the Liquid exchange itself (not by my code) in both directions: longing an asset or shorting it.

h) Obviously, Take Profit percentage (in our case 1%) as well as Stop Loss percentage (in our case 10%) is taking care off for you automatically, so when price goes up by 1% from buy price, the Liquid exchange does the thing and locks in the profit for you. The same with Stop Loss.

i) Remember: with 2x leverage your Profit or Loss figures are in fact doubled. So, if the trade is going as planned, you gain a 2% profit (2x for 1%) because … remember, you trade also with borrowed money (not only with your own stash). If the trade is not going as planned, your loss is in fact 20% (2x 10%), thus your own stash (USDC, or whatever Funding Currency is used) will decrease by 20% … because … the same argument: you trade with borrowed funds, so 10% loss from the entire amount traded is formed by 10% loss from your own funds and 10% loss from the borrowed funds (but you have to return the full amount borrowed*; hence the additional loss – that is covered from your own funds a.k.a. Funding Currency).

*) As mentioned earlier, Liquid exchange takes care off of this reimbursement (it is done also in the background, being an instant process when the trade is closed).

Recommendation: as a “food” to that function ( placeTradeLiquid() ) you are free to fill in what parameters suits you, according to your appetite for risk. If 10% stop loss is too much, just replace that figure with 5% or less. Or if 1% Take Profit is too low, replace it with a higher figure.

Progress status

So far so good, we have created the main tool to place trades with the crypto exchange, using ccxt library, i.e. the Python function placeTradeLiquid()


Still I have not developed the triggers, so in the next article I am going to attack the code that produces RSI for any trading pair and for any timeframe.

I am happy with the current progress. The ccxt library is damn useful!

Thus, today:

  • I have explained in detail the product Trading with Margin at crypto exchange;
  • I created the relevant Python function that is going to place trades; this function is to be used along with several relevant triggers; these triggers are to be set according to the trading strategy envisaged in the previous article; the trading bot (when is ready) is going to place trades 24/7 on both directions, i.e. either longing or shorting Bitcoin (BTC) and/or Ether (ETH), such trades trigerred while RSI < 25 and by an increase in price by 0.1% (for longing crypto assets) as well astriggeres by a decrease in price by 0.1% while RSI > 75 (for shorting crypto assets);
  • I have explained the parameters to be used when the above-mentioned function is used, including Trailing Stop at buying, as well as what is Funding Currency;
  • I warned you about correctly evaluating your both (i) target of profit as well as (ii) your limit of losses (hopefully the later will be rare) when trading with leverage (and demonstrated that those figures should be doubled in both cases, i.e. successful trades and bad trades).

About the construction of triggers that will be at the origin of this trading bot that is to work tirelessly 24/7 using the code developed so far: see the next article (PART 4).

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: