Skip to content
This repository has been archived by the owner on Feb 16, 2020. It is now read-only.

[request] Consider to implement the trading capital, position sizing and market risk in gekko #1841

Closed
ilap opened this issue Feb 2, 2018 · 5 comments

Comments

@ilap
Copy link

ilap commented Feb 2, 2018

Note: for support questions, please join our Discord server

  • I'm submitting a ...
    [ ] bug report
    [x ] feature request
    [ ] question about the decisions made in the repository

The currently implemented trading engine in gekko is very risky for any users as it does not have the position sizing, market risk and trading capital features implemented.

Gekko currently trades as "all in", which means the market risk is very high (read this) instead of the common 1% (for newbies) or max. 2% (advanced traders), and it also reduces the market diversity to only 1 market and also does not allow pyramiding.

The initial potential solution could be the following:

  • define the trading capital that is based on the exchange balance or on some percentages of the exchange balance.
  • gekko should manage the memory balances based on the retrieved exchange balances and the actioned trades.
  • gekko should automatically calculate the position sizes (max amount of buying an asset for a particular trade) based on the trading risk and the memory balance.

This will reduce the trading risks and can increase the diversification of the markets as we would be able to run different gekko instances for the same exchange. It would allow us to play/test gekko on real exchange defining some very small trading capital e.g. running real trades using a very small amount of currency (0.001 BTC with ETH/BTC pair).

I had a look at the portfolioManager.js and the trader.js and it seems that the balance calculating feature can be easily implemented in gekko by using some abstract method in the portfolio manager (Interface Pattern similar to the Decorator Pattern, but not really).

The simple pseudo-code in ES6 is the following:

class PortfolioManager {
  constructor() {
  }

  setPortfolio(fullPortfolio) {
    // this is where the portfolio is set either by the PortfilioManager or by the Trader.
    // this is the original code:  this.portfolio = portfolio;
    this.portfolio = this.adjustPortfolio(portfolio)    
    //...
  }
  
  // Simply return w/ the original portfolio if it's not overwritten
  // So behavior won't change.
  adjustPortfolio(portfolio) {
    return portfolio
  }
}

class Trader {
  constructor() {
     this.portfolioManager = new PortfolioManager()
     // overwrite the Manager's adjustPortfolio
     this.portfolioManager.adjustPortfolio = this.adjustPortfolio
  }
  adjustPortfolio(portfolio) {
      // do whatever you want w/ the portfilio in portfolioManager
      return portfolio
  }
}
@ilap
Copy link
Author

ilap commented Feb 2, 2018

Here comes a brief example what I meant by trading account on an exchange and do some risk assessment by calculating the position size..

Imagine you have the following currencies/assets on an exchange:
Currencies: BTC(1.5), ETH(4), USDT(1000)
Assets: NEO(20), XRB(40), DRGN(5000), ENG(1000)

Account (trading account) balance is the estimated value of the currency and the assets you want to trade

  • BTC(0.5) you do not want to trade all your BTC currency
  • NEO(10), XRB(20) and DRGN(25) half of your assets

So the account balance is the BTC price of the assets above, and the trading risk is 1% you wil lhave 3 markets and each of them has 1% trading risk:

  1. binance.BTC(0.25)-NEO(10) -> 0.25 + 0.1250050 = 0.3750050 -> Max Risk/ trade 0.003750050
  2. binance.BTC(0.1)-XRB(20) -> 0.1 + 0.03530540 = 0.13530540 -> Max Risk/ trade 0.0013530540
  3. binance.BTC(0.15)-DRGN(2500) 0.15 + .50852500 = 0.65852500 -> Max Risk/ trade 0.0065852500
    So the account balance is ~1.16BTC as a whole

When you enter a position (short or long) you need to calculate the position size (the max amount you can trade) of the market.

This means when we get the signal we have the theoretical entry price (as the real entry price is the price when you actually buy or sell assets).

Assume, that the long entry price for the BTC-NEO market is 0.0125000 and as we have 0.25 BTC then we can buy max. 20 NEOs. but, if you buy all and the price drops for example 10% and your signal says to sell, then you will lose a lot. So, to stop the loss or get the profit, you need to have some stop-loss (cancel orders at the losing position) and an exit price (exit from winning position).

It's usually done by configuring some indicators (some crosses etc.) or use some volatility measurement such as TA-Lib's ATR or similar.

I really like the idea of the volatility measurement as the cryptocurrencies are very volatile, and the ATR gives you the Average True Range for a certain period, but it also means if the volatility is high you cannot buy that amount of NEOs because you will lose a lot on the lost position.
See this brief explanation below, where the ATR is used for risk-based position sizing:

We set the stop-loss signal based on the ATR(20, SMA) ( I have checked and it's 0.000212545 at the moment), so if we set

  • the stop loss to curr price - 2 * ATR, assuming that the price drop is much higher (double) than the usual volatility, then we can buy
  • a curr balance(0.25) * market risk (0.001) / (2*ATR(0.000212545 )) NEOs, means we can buy only ~5.88 NEO of the max of 20 for 0.07351384413

This means if we lose the position and we will sell the ~5.88 NEO at 0.01207491 price (curr - 2*ATR), we will get 0.07101384413, that means we will only lose 0.07101384413 - 0.07351384413 = -0.002500 which is the 1% of the current (not the whole market balance the 0.375) balance.
This calculation is not quite accurate, as it does not take into account the whole account or the related market balance, and also it does not calculate the exit price (exit price follows the candle while the stop loss does not as it's fixed at entry time), and it also has some other issues, but I hope that this brief explanation above makes sense anyway.

@scragz
Copy link

scragz commented Feb 16, 2018

There's the beginnings of a stop loss implementation in #1317. Would just need to be extendable to do the ATR for half of this feature.

What I really want is the ability to only trade with a portion of currency though. Would be really nice to have multiple gekkos running on one exchange with the same pairing.

@ansonphong
Copy link
Contributor

@ilap Yes, it is very well understood what you are implying here, very important. There has been discussions about this going for months, and sophisticated users of Gekko end up implementing their own version of this by modifying the core source code. Due to where the project is at, and how many people are using it in different ways, this is something which could take a long time to get consensus on how to implement, so that is why people go ahead and implement it on their own.

Long term it needs to be addressed in the core functionality of Gekko to add support for various types of position and portfolio sizing, risk management, etc.

Since this is very much an open source effort, the best way at this point I'd suggest would be to study the existing app structure and propose different ways to implementing and consult members of the community here on their opinions, get consensus, make a roadmap, and start implementing incrementally with pull requests.

Or else make a fork, and fully implement your vision for it, and then work on getting it merged back into the core. That type of effort would be appreciated by the Gekko power users, as some people end up taking shortcuts and hacking these features in, though it doesn't end up making it back into the source.

@ilap
Copy link
Author

ilap commented Feb 16, 2018

@scragz Unfortunately, it's not as easy as it looks, as Gekko does not really track the orders.
It implemented the simplest trading functionalities, which comes w/ some trade-offs.
For example:

  1. you can only sell or buy once which must be followed by the opposite trade buy->sell or sell->buy. Gekko skips advice anyway, so it means that Gekko trades are stateless at the moment.

  2. Gekko does not track orders, which is required for using memory balance, means:
    When an order is placed it has some states e.g. Placed/Filled/Partially Filled, Cancelled etc. and almost on all state changes, we need to adjust the memory balance. For example: when we place an order the purchase price is reserved i.e. amount is reduced from the exch's currency/asset balance.
    When it filled (best case), it also requires some adjustment, due to some possible slippage that can happen (as an order can have several trades w/ slightly different price).
    When it cancelled, it also needs some re-adjustment (release the reserved amount in the exchange balance) and in the worst case, when it's just partially filled, it also requires re-adjustment.
    Also, different exchanges handle their orders differently.
    So, the orders must be tracked, that means that some client side order id is required. That means when a callback comes back w/ an order, we need exactly to know which order was it. Currently, Gekko just handles one order and using the all available balance in the exchange, due to the buy follows sell, sell follows buy restriction and the order tracking hardness I have mentioned. So the currently implemented simple add/check/check order works properly.

  3. It uses limit order despite Gekko only implemented the basic features. This can cause some unexpected behaviours in Gekko, For this simple trading functionality that Gekko currently has, a market order would do with some safety markers (implements some slippage relative to the candle price) to not allow to buy or sell w/ very high/low prices in the order book.

So it's harder than it looks, but not impossible.

Note: Proper definition for trade and order is required, as the order != trade, as one order can have multiple trades, as the exchange trading engines probably would buy/sell from/to different sellers/buyers to fulfil the order.

@ansonphong I think, the get consensus is the hardest part of the game, as in general, the decisions are made by personal believes, emotions and opinions which do not represent any scientific approach.:)

@askmike
Copy link
Owner

askmike commented Sep 25, 2018

Very old issue, apologies for never responding here.

Right now portfolio management inside your strategy is out of scope. While I agree it's great to have it, it complicates a lot of things. I've gone into this in here: #1619 (comment) and here: #2173.

Implementing this would have to start with a discussion on design. Since it's throwing away all of Gekko's core principles we need to come up with new ones. The forum would be a more appropiate place for this as this is the bug tracker.

@askmike askmike closed this as completed Sep 25, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants