first commit

This commit is contained in:
Francois Klieber committed 2021-06-06 20:25:14 +02:00
commit aa7869eb33
386 files changed
+69375

No files matched your search

+41
View File
@@ -0,0 +1,41 @@
# Importing
*Note: this documentation was written for running Gekko via the command line. If you are using the UI you can simply use the importer under the "local data" tab.*
If you want to use Gekko to [backtest against historical data](./backtesting.md), you most likely need some historical data to test against. Gekko comes with the functionality to automatically import historical data from some exchanges. However, only a few exchanges support this. You can find out with which exchanges Gekko is able to do this [here](https://github.com/askmike/gekko#supported-exchanges).
## Setup
For importing you should [enable and configure](./plugins.md) the following plugin:
- candleWriter (to store the imported data in a database)
Besides that, make sure to configure `config.watch` properly.
## Configure
In your config set the `importer.daterange` properties to the daterange you would like to import.
## Run
node gekko --config config.js --import
The result will be something like this:
2016-06-26 09:12:16 (INFO): Gekko v0.2.2 started
2016-06-26 09:12:16 (INFO): I'm gonna make you rich, Bud Fox.
2016-06-26 09:12:17 (INFO): Setting up Gekko in importer mode
2016-06-26 09:12:17 (INFO):
2016-06-26 09:12:17 (INFO): Setting up:
2016-06-26 09:12:17 (INFO): Candle writer
2016-06-26 09:12:17 (INFO): Store candles in a database
2016-06-26 09:12:17 (INFO):
2016-06-26 09:12:17 (WARN): The plugin Trading Advisor does not support the mode importer. It has been disabled.
2016-06-26 09:12:17 (WARN): The plugin Advice logger does not support the mode importer. It has been disabled.
2016-06-26 09:12:17 (WARN): The plugin Profit Simulator does not support the mode importer. It has been disabled.
2016-06-26 09:12:18 (DEBUG): Processing 798 new trades.
2016-06-26 09:12:18 (DEBUG): From 2015-09-09 12:00:04 UTC to 2015-09-09 13:58:55 UTC. (2 hours)
2016-06-26 09:12:20 (DEBUG): Processing 211 new trades.
(...)
+28
View File
@@ -0,0 +1,28 @@
# About the commandline
You don't have to use the UI to control Gekko, you can also use the commandline if you don't have access to a window manager or browser (on a server for example, or anything else you want to SSH into). This is only recommended for advanced users who feel comfortable editing config files and running shell commands.
Using the commandline you run one Gekko instance per command, eg. if you want to import 3 markets you need to run Gekko 3 times.
## Configuring Gekko
If you decide you want to run gekko over the commandline you need to decide two things:
1. What market / settings are you interested in?
2. What should Gekko do? This is either backtest, import or run live.
For the first one you configure a config file: copy `gekko/sample-config.js` to something else (for example `gekko/config.js`). Configure the plugins to your liking. What plugins you need to enable does depend on the answer of question 2. Check the documentation under commandline for that feature.
## Running Gekko
For live mode run:
node gekko --config config.js
To backtesting run:
node gekko --config config.js --backtest
To import run:
node gekko --config config.js --import
+71
View File
@@ -0,0 +1,71 @@
# Backtesting with Gekko
*Note: this documentation was written for running Gekko via the command line. If you are using the UI you can simply use the importer under the "local data" tab.*
Gekko is able to backtest strategies against historical data.
## Setup
For backtesting you should [enable and configure](./plugins.md) the following plugins:
- trading advisor (to run your strategy).
- paper trader (to execute simulated trades).
- performance analyzer (to calculate how succesfull the strategy would have been).
Besides that, make sure to configure `config.watch`.
## Historical data
Gekko requires historical data to backtest strategies against. The easiest way to get this is to let Gekko import historical data, however this is not supported by a lot of exchanges (see [here](https://github.com/askmike/gekko#supported-exchanges)). The second easiest and most universal way is to run Gekko on real markets using the UI (or alternatively via the commandline with the plugin sqliteWriter enabled). Though this takes a while, as you need to run Gekko for a week to have a week of data.
## Configure
In your config set the `backtest.daterange` to `scan`. This will force Gekko to scan the local database to figure out what dataranges are available. If you already know exactly what daterange you would like to backtest against, you can set the `backtest.daterange` directly (set `backtest.daterange` as an object with the keys `from` and `to` and the values as a data parsable by [moment](http://momentjs.com/docs/#/parsing/)).
## Run
node gekko --config config.js --backtest
The result will be something like this:
2016-06-11 08:53:20 (INFO): Gekko v0.2.1 started
2016-06-11 08:53:20 (INFO): I'm gonna make you rich, Bud Fox.
2016-06-11 08:53:20 (INFO): Setting up Gekko in backtest mode
2016-06-11 08:53:20 (INFO):
2016-06-11 08:53:20 (WARN): The plugin SQLite Datastore does not support the mode backtest. It has been disabled.
2016-06-11 08:53:20 (INFO): Setting up:
2016-06-11 08:53:20 (INFO): Trading Advisor
2016-06-11 08:53:20 (INFO): Calculate trading advice
2016-06-11 08:53:20 (INFO): Using the trading method: DEMA
2016-06-11 08:53:20 (INFO):
2016-06-11 08:53:20 (INFO): Setting up:
2016-06-11 08:53:20 (INFO): Profit Simulator
2016-06-11 08:53:20 (INFO): Paper trader that logs fake profits.
2016-06-11 08:53:20 (INFO):
2016-06-11 08:58:20 (INFO): Profit simulator got advice to long @ 2016-05-30 04:37:00, buying 1.1880062 BTC
2016-06-11 08:58:21 (INFO): Profit simulator got advice to short @ 2016-05-31 21:37:00, selling 1.1880062 BTC
2016-06-11 08:58:21 (INFO): Profit simulator got advice to long @ 2016-06-01 12:37:00, buying 1.14506098 BTC
2016-06-11 08:58:21 (INFO): Profit simulator got advice to short @ 2016-06-02 14:57:00, selling 1.14506098 BTC
2016-06-11 08:58:21 (INFO): Profit simulator got advice to long @ 2016-06-02 23:37:00, buying 1.11711818 BTC
2016-06-11 08:58:21 (INFO): Profit simulator got advice to short @ 2016-06-05 12:57:00, selling 1.11711818 BTC
2016-06-11 08:58:21 (INFO): Profit simulator got advice to long @ 2016-06-06 02:37:00, buying 1.08456953 BTC
2016-06-11 08:58:22 (INFO): Profit simulator got advice to short @ 2016-06-07 17:17:00, selling 1.08456953 BTC
2016-06-11 08:58:22 (INFO): Profit simulator got advice to long @ 2016-06-08 13:17:00, buying 1.05481755 BTC
2016-06-11 08:58:22 (INFO): Profit simulator got advice to short @ 2016-06-09 14:17:00, selling 1.05481755 BTC
2016-06-11 08:53:22 (INFO): (PROFIT REPORT) start time: 2016-05-29 23:34:00
2016-06-11 08:53:22 (INFO): (PROFIT REPORT) end time: 2016-06-10 08:56:00
2016-06-11 08:53:22 (INFO): (PROFIT REPORT) timespan: 11 days days
2016-06-11 08:53:22 (INFO): (PROFIT REPORT) start price: 516.19
2016-06-11 08:53:22 (INFO): (PROFIT REPORT) end price: 578.97
2016-06-11 08:53:22 (INFO): (PROFIT REPORT) Buy and Hold profit: 12.162189999999995%
2016-06-11 08:53:22 (INFO): (PROFIT REPORT) amount of trades: 10
2016-06-11 08:53:22 (INFO): (PROFIT REPORT) original simulated balance: 616.19000 USD
2016-06-11 08:53:22 (INFO): (PROFIT REPORT) current simulated balance: 602.59867 USD
2016-06-11 08:53:22 (INFO): (PROFIT REPORT) simulated profit: -13.59133 USD (-2.20570%)
2016-06-11 08:53:22 (INFO): (PROFIT REPORT) simulated yearly profit: -435.53244 USD (-70.68152%)
+214
View File
@@ -0,0 +1,214 @@
## Enabling plugins
*Note: this documentation was written for running Gekko via the command line. If you are using the UI you do not have to manually select plugins.*
Gekko currently has a couple plugins:
- trading advisor (run a TA strategy against a market)
- trader (execute advice from the TA strategy on a real exchange)
- advice logger
- paper trader
- Mailer
- IRC bot
- Campfire bot
- Redis beacon
- XMP Bot
- and more..
To configure a plugin, open up your `config.js` file with a text editor and configure the appropiate section.
## Trading Advisor
If you want Gekko to provide automated trading advice you need to configure this in Gekko. Note that this is a different plugin than the "trader" which is a responsible for actually creating orders based on this advice. (So if you want automated trading you need both this advice as well as the auto trader).
Documentation about strategies in Gekko can be found [here](../strategies/introduction.md).
### Trader
This plugin automatically creates orders based on the advice from the "Trading Advisor" from the market Gekko is watching. This turns Gekko into an automated trading bot.
Before Gekko can automatically trade you need to create API keys so that Gekko has the rights to create orders on your behalf, the rights Gekko needs are (naming differs per exchange): get info, get balance/portfolio, get open orders, get fee, buy, sell and cancel order. For all exchanges you need the API key and the API secret, for both Bitstamp and CEX.io you also need your username (which is a number at Bitstamp).
Configure it like this:
config.trader = {
enabled: true,
key: 'your-api-key',
secret: 'your-api-secret',
username: 'your-username' // your username, only fill in when using bitstamp or cexio
}
- enabled indicates whether this is on or off.
- key is your API key.
- secret is your API secret.
- username is the username (only required for CEX.io and Bitstamp).
### Advice logger
The advice logger is a small plugin that logs new advice calculated by Gekko as soon as there is any. Go to the config and configure it like this:
config.adviceLogger = {
enabled: true
}
- enabled indicates whether this is on or off.
The advice logged advice will look something like this in the terminal:
2014-01-15 14:31:44 (INFO): We have new trading advice!
2014-01-15 14:31:44 (INFO): Position to take: long
2014-01-15 14:31:44 (INFO): Market price: 5.96
2014-01-15 14:31:44 (INFO): Based on market time: 2014-01-15 14:31:01
### Paper trader
The paper trader listens to Gekko's advice and on a sell it will swap all (simulated) currency into (simulated) assets at the current price. On a buy it will be the other way around.
Go to the config and configure it like this:
// do you want Gekko to calculate the profit of its own advice?
config.paperTrader = {
enabled: true,
// report the profit in the currency or the asset?
reportInCurrency: true,
// start balance, on what the current balance is compared with
simulationBalance: {
// these are in the unit types configured in the watcher.
asset: 1,
currency: 100
},
// only want report after a sell? set to `false`.
verbose: false,
// how much fee in % does each trade cost?
feeMaker: 0.5,
feeTaker: 0.6,
// Using taker or maker fee?
feeUsing: 'maker',
// how much slippage should Gekko assume per trade?
slippage: 0.1
}
- enabled indicates whether this is on or off.
- reportInCurrency tells Gekko whether it should report in asset or in the currency.
- simulationBalance tells Gekko with what balance it should start.
- verbose specifies how often Gekko should log the results (false is after every trade, true is after every candle).
- fee is the exchange fee (in %) Gekko should take into consideration when simulating orders.
- slippage is the costs in (in %) associated with not being able to buy / sell at market price.*
*If you are trading a lot and you are buying 100% currency you might not get it all at market price and you have to walk the book in order to take that position. Also note that Gekko uses the candle close price and is unaware of the top asks bids, also take this into account. It is important that you set this number correctly or the resulted calculated profit be very wrong. Read more information [here](http://www.investopedia.com/terms/s/slippage.asp). Take these into consideration when setting a slippage:
- How much spread is there normally on this market?
- How thick is the top of the book normally?
- How volatile is this market (the more volatility the bigger the chance you will not get the price you expected)?
The output will be something like:
2013-06-02 18:21:15 (INFO): ADVICE is to SHORT @ 117.465 (0.132)
2013-06-02 18:21:15 (INFO): (PROFIT REPORT) original balance: 207.465 USD
2013-06-02 18:21:15 (INFO): (PROFIT REPORT) current balance: 217.465 USD
2013-06-02 18:21:15 (INFO): (PROFIT REPORT) profit: 10.000 USD (4.820%)
### Mailer
Mailer will automatically email you whenever Gekko has a new advice.
// want Gekko to send a mail on buy or sell advice?
config.mailer = {
enabled: false, // Send Emails if true, false to turn off
sendMailOnStart: true, // Send 'Gekko starting' message if true, not if false
Email: 'me@gmail.com', // Your GMail address
// You don't have to set your password here, if you leave it blank we will ask it
// when Gekko's starts.
//
// NOTE: Gekko is an open source project < https://github.com/askmike/gekko >,
// make sure you looked at the code or trust the maintainer of this bot when you
// fill in your email and password.
//
// WARNING: If you have NOT downloaded Gekko from the github page above we CANNOT
// guarantee that your email address & password are safe!
password: '', // Your GMail Password - if not supplied Gekko will prompt on startup.
tag: '[GEKKO] ' // Prefix all EMail subject lines with this
}
- enabled indicates whether this is on or off.
- sendMailOnStart will email you right away after Gekko started, you can also use this if you are automatically restarting Gekko to see crash behaviour.
- Email is your email address from which Gekko will send emails (to the same address).
- password is the email password: Gekko needs to login to your account to send emails to you:
> You don't have to set your password here, if you leave it blank we will ask it
> when Gekko's starts.
>
> NOTE: Gekko is an open source project < https://github.com/askmike/gekko >,
> make sure you looked at the code or trust the maintainer of this bot when you
> fill in your email and password.
>
> WARNING: If you have NOT downloaded Gekko from the github page above we CANNOT
> guarantee that your email address & password are safe!
- tag is some text that Gekko will put in all subject lines so you can easily group all advices together.
### IRC bot
IRC bot is a small plugin that connects Gekko to an IRC channel and lets users interact with it using basic commands.
config.ircbot = {
enabled: false,
emitUpdates: false,
channel: '#your-channel',
server: 'irc.freenode.net',
botName: 'gekkobot'
}
- enabled indicates whether this is on or off.
- emitUpdates tells Gekko that whenever there is a new advice it should broadcast this in the channel.
- channel is the IRC channel the bot will connect to.
- server is the IRC server.
- botName is the username Gekko will use.
### Campfire bot
Campfire bot is a small plugin that connects Gekko to a Campfire room and lets users interact with it using basic commands.
config.campfire = {
enabled: false,
emitUpdates: false,
nickname: 'Gordon',
roomId: 673783,
apiKey: 'e3b0c44298fc1c149afbf4c8996',
account: 'your-subdomain'
}
- enabled indicates whether this is on or off.
- emitUpdates tells Gekko that whenever there is a new advice it should broadcast this in the room.
- roomId is the ID of the Campfire room the bot will connect to.
- apiKey is the API key for the Campfire user Gekko will connect using.
- account is the subdomain for the account that the room belongs to.
### Redis beacon
This is an advanced plugin only for programmers! If you are interested in this read more [here](https://github.com/askmike/gekko/blob/stable/docs/internals/plugins.md#redis-beacon).
config.redisBeacon = {
enabled: false,
port: 6379, // redis default
host: '127.0.0.1', // localhost
// On default Gekko broadcasts
// events in the channel with
// the name of the event, set
// an optional prefix to the
// channel name.
channelPrefix: '',
broadcast: [
'small candle'
]
}
- enabled indicates whether this is on or off.
- port is the port redis is running on.
- host is the redis host.
- channelPrefix a string that Gekko will prefix all candles with.
- broadcast is a list of all events you want Gekko to publish.
+25
View File
@@ -0,0 +1,25 @@
# Tradebot
You can set Gekko up as a tradebot, this will instruct Gekko to:
- Watch a live market.
- Run a strategy (in semi-realtime) over live market data.
- Automatically create buy/sell orders based on signals coming from the strategy.
*As with everything in Gekko, the tradebot will make decisions based on the strategy selected/configured/created **by YOU**. If you end up losing money, you have no one to blame but yourself.*
## Configuration
First, set up Gekko for commandline usage (see [this document](./about_the_commandline.md) for details). After that, configure the following plugins:
- `config.watch` - the market to trade on.
- `candleWriter` - (optional) also store market data to disk.
- `tradingAdvisor` - configure the strategy and candle properties.
- `trader` - configure Gekko access to your exchange account.
- `performanceAnalyzer` - enable.
Turn off the paperTrader (there can only be 1 trade plugin active per instance).
Once done, run Gekko like so:
node gekko --config your-config-file.js
+38
View File
@@ -0,0 +1,38 @@
# Plugins
A plugin is a low level module or plugin that can act upon events bubbling
through Gekko. If you want to have custom functionality so that your rocket
flies to the moon as soon as the price hits X you should create a plugin for it.
All plugins live in `gekko/plugins`.
Note that in order to use custom plugins, you have to run Gekko over [the commandline](../commandline/about_the_commandline.md).
## Existing plugins:
- Candle Store: save trades to disk.
- Mailer: mail trading advice to your gmail account.
- Pushbullet: send messages to Pushbullet devices.
- Telegram: send messages over Telegram.
- IRC bot: logs Gekko on in an irc channel and lets users communicate with it.
- Paper Trader: simulates trades and calculates profit over these (and logs profit).
- Trading advisor (internal): calculates advice based on market data.
- Redis beacon (advanced): [see below!](#redis-beacon)
*And more! Take a look in the `gekko/plugins folder.`*
## Implementing a new plugin
If you want to add your own plugin you need to expose a constructor function inside
`plugins/[slugname of plugin].js`. The object needs methods based on which event you want
to listen to. All events can be found in [the events page](../architecture/events.md).
You also need to add an entry for your plugin inside `plugins.js` which registers your plugin for use with Gekko. Finally you need to add a configuration object to `sample-config.js` with at least:
config.[slug name of plugin] = {
enabled: true
}
Besides enabled you can also add other configurables here which users can set themselves.
That's it! Don't forget to create a pull request of the awesome plugin you've just created!
+181
View File
@@ -0,0 +1,181 @@
# Exchanges
*This is a technical document about adding a new exchange to Gekko and Gekko Broker.*
Gekko arranges all communication about when assets need to be bought or sold between the *strategy* and *Gekko Broker*. All differences between the different API's are abstracted away just below Gekko Broker inside an "exchange wrapper". This document describes all requirements for adding a new exchange wrapper (adding exchange support to Gekko).
When you add a new exchange to Gekko you need to expose an object that has methods to query the exchange. This exchange file needs to reside in `gekko/exchange/wrappers` and the filename is the slug of the exchange name + `.js`. So for example the exchange integration with Binance is explained in `gekko/exchange/wrappers/binance.js`.
Please use a npm module to query an exchange. This will separate the abstract API calls from the Gekko specific stuff (In the case of Bitstamp there was no module yet, so I [created one](https://www.npmjs.com/package/bitstamp)).
Finally Gekko needs to know how it can interact with the exchange, so add a static method `getCapabilities()` that returns it's properties. They are all described [here](#capabilities).
## Gekko's expectations
Gekko Broker implements an exchange like so:
const Exchange = require('./wrapper' + [exchange slug]);
this.exchange = new Exchange({key: '', secret: '', username: '', currency: 'USD', asset: 'BTC'});
It will run the following methods on the exchange object:
### getTrades
With this single method implemented Gekko won't be able to do live trading, but it will be able to do paper trading and storing market data for backtesting.
this.watcher.getTrades(since, callback, descending);
If since is truthy, Gekko requests as much trades as the exchange can give (up to ~10,000 trades, if the exchange supports more you can [create an importer](../features/importing.md)).
The callback expects an error and a `trades` object. Trades is an array of trade objects in chronological order (0 is older trade, 1 is newer trade). Each trade object needs to have:
- a `date` property (unix timestamp in either string or int)
- a `price` property (float) which represents the price in [currency] per 1 [asset].
- an `amount` property (float) which represent the amount of [asset].
- a `tid` property (float) which represents the tradeID.
## Gekko Broker's expectations
The methods below are needed for Gekko to automatically trade on the exchange.
### getTicker
this.exchange.getTicker(callback)
The callback needs to have the parameters of `err` and `ticker`. Ticker needs to be an object with at least the `bid` and `ask` property in float.
### getFee
this.exchange.getFee(callback);
The callback needs to have the parameters of `err` and `fee`. Fee is a float that represents the amount the exchange takes out of the orders Gekko places. If an exchange has a fee of 0.2% this should be `0.002`.
### getPortfolio
this.exchange.getPortfolio(callback);
The callback needs to have the parameters of `err` and `portfolio`. Portfolio needs to be an array of all currencies and assets combined in the form of objects, an example object looks like `{name: 'BTC', amount: 1.42131}` (name needs to be an uppercase string, amount needs to be a float).
### getLotSize
this.exchange.getLotSize(tradeType, amount, size, callback);
The callback needs to have the parameters of `err` and `lot`. Lot needs to be an object with `amount` and `purchase` size appropriately for the exchange. In the event that the lot is too small, return 0 to both fields and this will generate a lot size warning in the portfolioManager.
Note: This function is currently optional. If not implemented Gekko Broker will fallback to basic lot sizing mechanism it uses internally. However exchanges are not all the same in how rounding and lot sizing work, it is recommend to implement this function.
### buy
this.exchange.buy(amount, price, callback);
### sell
this.exchange.sell(amount, price, callback);
This should create a buy / sell order at the exchange for [amount] of [asset] at [price] per 1 asset. The callback needs to have the parameters `err` and `order`. The order needs to be some id that can be passed back to `checkOrder`, `getOrder` and `cancelOrder`.
### getOrder
this.exchange.getOrder(order, callback);
Will only be called on orders that have been completed. The order will be something that the manager previously received via the `sell` or `buy` methods. The callback should have the parameters `err` and `order`. Order is an object with properties `price`, `amount` and `date`. Price is the (volume weighted) average price of all trades necessary to execute the order. Amount is the amount of currency traded and Date is a moment object of the last trade part of this order.
### checkOrder
this.exchange.checkOrder(order, callback);
The order will be something that the manager previously received via the `sell` or `buy` methods. The callback should have the parameters `err` and a `result` object. The result object will have two or three properties:
- `open`: whether this order is currently in the orderbook.
- `executed`: whether this order has executed (filled completely).
- `filledAmount`: the amount of the order that has been filled. This property is only needed when both `open` is true and `completed` is false.
### cancelOrder
this.exchange.cancelOrder(order, callback);
The order will be something that the manager previously received via the `sell` or `buy` methods. The callback should have the parameters `err`, `filled` and optionally a `fill` object, `filled` should be true if the order was fully filled before it could be cancelled. If the exchange provided how much was filled before the cancel this should be passed in the `fill object` as a `amountFilled` property. If the exchange provided how much of the original amount is still remaining, pass this as the `remaining` property instead.
### roundPrice
this.exchange.roundPrice(rawPrice);
Should return a price. Rounds the price into a valid price Gekko Broker can later feed into a buy or sell order. *Note: if representation of the number is important for the exchange (for example if the exchange will not accept numbers expressed in scientific notation) you can return a string from this method (Gekko Broker will perform calculations so the string should be castable to a number.)*
### roundAmount
this.exchange.roundAmount(rawAmount);
Should return an amount. Rounds the amount into a valid amount Gekko Broker can later feed into a buy or sell order. *Note: if representation of the number is important for the exchange (for example if the exchange will not accept numbers expressed in scientific notation) you can return a string from this method (Gekko Broker will perform calculations so the string should be castable to a number.)*
## Gekko Broker's optional methods
### isValidPrice
this.exchange.isValidPrice(price);
Should return true or false. If the exchange has restrictions on the price you can submit limit orders at. If there are no such restrictions you should not implement this method.
### isValidLot
this.exchange.isValidLot(price, amount);
Should return true or false. If the exchange has restrictions on the lot size (order size expressed in "currency" amount) you can check for that here. If there are no such restrictions you should not implement this method.
## Error handling
It is the responsibility of the wrapper to handle errors and retry the call in case of a temporary error. Gekko exposes a retry helper you can use to implement an exponential backoff retry strategy. Your wrapper does need pass a proper error object explaining whether the call can be retried or not. If the error is fatal (for example private API calls with invalid API keys) the wrapper is expected to upstream this error. If the error is retryable (exchange is overloaded or a network error) an error should be passed with the property `notFatal` set to true. If the exchange replied with another error that might be temporary (for example an `Insufficient funds` error right after Gekko canceled an order, which might be caused by the exchange not having updated the balance yet) the error object can be extended with an `retry` property indicating that the call can be retried for n times but after that the error should be considered fatal.
For implementation refer to the bitfinex implementation, in a gist this is what a common flow looks like:
- (async call) `exchange.buy`, then
- handle the response and normalize the error so the retry helper understands it, then
- the retry helper will determine whether the call needs to be retried, then
- based on the error it will retry (for example `nonFatal` or `retry`)
- if no error it will pass it to your handle function that normalizes the output
## Capabilities
Each exchange *must* provide a `getCapabilities()` static method that returns an object with these parameters:
- `name`: Proper name of the exchange
- `slug`: slug name of the exchange (needs to match filename in `gekko/exchanges/`)
- `currencies`: all the currencies supported by the exchange implementation in gekko.
- `assets`: all the assets supported by the exchange implementation in gekko.
- `pairs`: all allowed currency / asset combinations that form a market
- `maxHistoryFetch`: the parameter fed to the getTrades call to get the max history.
- `providesHistory`: If the getTrades can be fed a since parameter that Gekko can use to get historical data, set this to:
- `date`: When Gekko can pass in a starting point in time to start returning data from.
- `tid`: When Gekko needs to pass in a trade id to act as a starting point in time.
- `false`: When the exchange does not support to give back historical data at all.
- `fetchTimespan`: if the timespan between first and last trade per fetch is fixed, set it here in minutes.
- `tradable`: if gekko supports automatic trading on this exchange.
- `requires`: if gekko supports automatic trading, this is an array of required api credentials gekko needs to pass into the constructor.
- `forceReorderDelay`: if after canceling an order a new one can't be created straight away since the balance is not updated fast enough, set this to true (only required for exchanges where Gekko can trade).
- `gekkoBroker`: set this to "0.6.2" for now, it indicates the version of Gekko Broker this wrapper is compatible with.
- `limitedCancelConfirmation` set to true if (in any case) the wrapper does NOT include partial fill information in the response (which is passed as the cancel callback)
Below is a real-case example how `bistamp` exchange provides its `getCapabilities()` method:
```
Trader.getCapabilities = function () {
return {
name: 'Bitstamp',
slug: 'bitstamp',
currencies: ['USD', 'EUR'],
assets: ['BTC', 'EUR'],
maxTradesAge: 60,
maxHistoryFetch: null,
markets: [
{ pair: ['USD', 'BTC'], minimalOrder: { amount: 1, unit: 'currency' } },
{ pair: ['EUR', 'BTC'], minimalOrder: { amount: 1, unit: 'currency' } },
{ pair: ['USD', 'EUR'], minimalOrder: { amount: 1, unit: 'currency' } }
],
requires: ['key', 'secret', 'username'],
fetchTimespan: 60,
tid: 'tid',
gekkoBroker: '0.6.2',
limitedCancelConfirmation: false
};
}
```
+21
View File
@@ -0,0 +1,21 @@
# Other Software
Since Gekko version 0.4 Gekko can launch a process which exposes a web (REST and Websocket) API that can be used to control Gekkos (start a backtest, start a running Gekko, etc). This makes it easy for other people to build new functionality on top of Gekko without having to work with Gekko internals, the runtime (or even javascript at all).
## List
### Backtesters
- [japonicus](https://github.com/Gab0/japonicus)
- [gekkoga](https://github.com/gekkowarez/gekkoga)
- [Gekko-BacktestTool](https://github.com/xFFFFF/GekkoBacktestTool)
- [Gekko Automated Backtest](https://github.com/tommiehansen/gab)
- [Gekko Warez Bruteforce Backtester](https://github.com/gekkowarez/bruteforce)
### UI mode
- [Unofficial Material UI](https://github.com/H256/gekko-quasar-ui)
- [Controlling bots](https://github.com/CyborgDroid/gekko-python)
### CLI mode
- [Batch generation of configuration files](https://github.com/bettimms/multi-gekko)
### Plugins
- [Store trades in Google SpreadSheet](https://github.com/RJPGriffin/google-forms-gekko-plugin)
+23
View File
@@ -0,0 +1,23 @@
# Backtesting
Gekko supports backtesting strategies over historical data. A Backtest is a simulation where you simulate running a strategy over a long time (such as the last 30 days) in a matter of seconds. Backtesting requires having market data locally available already. After a backtest Gekko will provide statistics about the market and the strategy's performance.
![screen shot of gekko backtesting](https://cloud.githubusercontent.com/assets/969743/24838718/8c790a86-1d45-11e7-99ae-e7e551cb40cb.png)
**Important things to remember:**
- Just because a strategy performed well in the past, does not mean it will perform well in the future.
- Be careful of overfitting, in other words: don't simply tweak a strategy until you get high profit and assume that will be as profitable when going live. Read more about overfitting in [this article](https://laplaceinsights.com/backtesting-strategies-and-overfitting/).
- The backtest simulation is limited, this is not really a problem on bigger markets (such as BTC/USD) but the differences between backtests and live traders on very low volume markets might be big. Read more about this below in the simplified simulation below.
## Simplified simulation
Simulating trades is done through a module called the paper trader. This module will use market candles together with fee, slippage and spread numbers to estimate trade executions costs. While the default settings work great for most big markets (USD/BTC or BTC/ETH), it becomes a lot less acurate on smaller markets with low volume and liquidity.
In live trading the notion of the "price" is more complicated than a single number. Both `spread` and `slippage` will effect your trade prices: these numbers describe your desired trades in relation to what people are currently offering in the market (this is called the orderbook). Read more about this in [this explanation](https://github.com/askmike/gekko/issues/2380#issuecomment-408744682).
If you look at the following backtest result:
![screen shot of backtesting at an illiquid market](https://cloud.githubusercontent.com/assets/969743/24840243/8f307022-1d61-11e7-9964-e6614d7433ea.png)
You can see a lot of "spikes" of the price moving up and down. These are not actually price fluctuations but simply trades that happen on both sides of the orderbook (a bid is taken then an ask is taken). How far it jumps up and down is the spread (between the asks and the bids). In these cases the statistics from the simulation won't be very accurate (unless you configured a higher slippage to account for the spread). This is unfortunately a limitation in Gekko's backtesting model.
+11
View File
@@ -0,0 +1,11 @@
# Importing
In order to [backtest](./backtesting.md) your strategies you will need to have historical market data to test with. The easiest way of getting this data is importing it directly from the exchange using the Gekko UI (note that this is not supported at all exchanges, check [this list](../introduction/supported_exchanges.md) to see what exchanges Gekko can import from).
You can start an import by navigating to the tab "Local tab" and scrolling to the bottom and click "Go to the importer". This brings you to the importing page with this at the bottom:
![importing wizard](https://user-images.githubusercontent.com/969743/28596822-a79509cc-7192-11e7-9293-53066f598053.png)
Once you configure the market and daterange you want to watch and click import Gekko will automatically download historical market data from the exchange:
![gekko importer](https://user-images.githubusercontent.com/969743/28597211-914dbe32-7194-11e7-8352-60a69afdf846.png)
+7
View File
@@ -0,0 +1,7 @@
# Paper trading
Gekko can automatically run a strategy over the live markets and simulate in realtime what happen if you would have traded on its signals. Paper trading and [backtesting](./backtesting.md) are the two simulation modes that come with Gekko. It's a great way to experiment with strategies without putting your money on the line.
You can start a paper trader by going to live gekkos and clicking on "Start a new live Gekko".
Keep in mind that a paper trader is a simulation, and the accuracy depends on the market you decide to run it on (you'll get pretty accurate results on big markets like USD/BTC). You can read more about the details and limitations of the simulation on [the backtesting page](./backtesting.md#Simplified-simulation).
+22
View File
@@ -0,0 +1,22 @@
# Trading bot
Once you have run enough simulations (using [backtesting](./backtesting.md) and [paper trading](./paper_trading.md)) and you are confident in your strategy you can use Gekko as a trading bot.
Gekko will run your strategy on the live market and automatically trade on your exchange account when trade signals come out of your strategy.
## Preparation
1. Make sure you are fully confident in your strategy! If you want to play around use either the [paper trader](./paper_trading.md) or the [backtester](./backtesting.md). Once you are confident continue with this list.
2. Gekko will need to have API keys to your exchange account that have permissions to view balances and orders and create new orders. Keep in mind:
- Gekko does NOT need withdrawal access, for your safety DO NOT create API keys that can withdraw.
- Make sure you only use the API key for Gekko, and for nothing else. If in doubt create a new key (and remove stale ones).
- If possible try to restrict the API key to the IP address you will run Gekko from (this makes moest sense in server environments)
3. Start your gekko through either the UI or the commandline interface!
## Notes
Gekko will trade on the market you configured that consists of two currencies (for example USD/BTC):
- Try to not trade either of these currencies on the account you use with Gekko. (in the example above: don't trade any USD nor any BTC).
- Try to not withdraw or deposit more of either of these currencies.
While Gekko will handle the situations above, all the profit calculations will be incorrect since your balances are taken into account while calculating profits.
+130
View File
@@ -0,0 +1,130 @@
# Gekko Broker
Order execution library for bitcoin and crypto exchanges. This library is Gekko's execution engine for all live orders (simulated orders do not through Gekko Broker, they go through the paper trader). This library is intended for developers of trading systems in need for advanced order types on multiple exchanges over a unified API.
## Introduction
This library makes it easy to do (advanced) orders all crypto exchanges where Gekko can live trade at. See the complete list [here](https://gekko.wizb.it/docs/introduction/supported_exchanges.html).
This library allows you to:
- Get basic market data
- ticker (BBO)
- ~orderbook~ (TODO)
- historical trades
- Get portfolio data
- Do an (advanced) order:
- Submit the order to the exchange
- Receive events about the status of the order:
- submitted
- open (accepted)
- partially filled
- rejected
- completed
- Mutate the order
- cancel
- amend
- move
- move limit
- Tracks orders submitted through the library.
## Status
Early WIP. All communication is via the REST APIs of exchanges. Not all exchanges are supported, see which ones are in [this doc](../introduction/supported_exchanges.md).
## Order types
This library aims to offer advanced order types, even on exchanges that do not natively support them by tracking the market and supplementing native order support on specific exchanges.
Working:
- Base orders
- [Sticky Order](./sticky_order.md)
TODO:
- Base orders:
- Limit Order
- Market Order
- Triggers:
- Stop
- If Touched (stop but opposite direction)
### Example
Set up a Gekko Broker instance:
// from the gekko repo (make sure you have deps installed
// inside the exchange folder).
const Broker = require('../gekko/exchange/GekkoBroker');
// or from NPM
// const Broker = require('gekko-broker');
const binance = new Broker({
currency: 'USDT',
asset: 'BTC',
private: true,
exchange: 'binance',
key: 'x', // add your API key
secret: 'y' // add your API secret
});
Now we have an instance that can create a [sticky order](./sticky_order.md):
const type = 'sticky';
const side = 'buy';
const amount = 1;
const order = binance.createOrder(type, side, amount);
order.on('statusChange', s => console.log(now(), 'new status', s));
order.on('fill', s => console.log(now(), 'filled', s));
order.on('error', s => console.log(now(), 'error!', e));
order.on('completed', a => {
console.log(new Date, 'completed!');
order.createSummary((err, s) => {
console.log(new Date, 'summary:');
console.log(JSON.stringify(s, null, 2));
});
});
This one doesn't have an upper limit price for what it will buy at. It will stick it's bid offer at BBO until it's filled. If you have a limit in mind you can specify it when creating, do this instead:
const order = binance.createOrder(type, side, amount, { limit: 100 });
It will never offer to buy for more than 100, even if the BBO is above 100 (the bid will end up deep in the book).
At any point in time you can change the limit (or the amount), for example:
order.moveLimit(120);
Running the above example (without setting a limit and moving it) will yield:
root@foxtail:~/gb/nusadua# node b
2018-07-29 03:46:02 new status SUBMITTED
2018-07-29 03:46:02 new status OPEN
2018-07-29 03:46:04 filled 1
2018-07-29 03:46:04 new status FILLED
2018-07-29T03:46:04.127Z 'completed!'
2018-07-29T03:46:04.358Z 'summary:'
{
"price": 0.0017479,
"amount": 1,
"date": "2018-07-29T03:46:02.576Z",
"side": "buy",
"orders": 1,
"fees": {
"BNB": 0.00075
},
"feePercent": 0.075
}
NOTE: not all status changes are documented and more events are planned but not implemented.
### TODO
- finish all exchange integrations that gekko supports
- finish all order types and triggers (under todo)
- implement websocket support (per exchange)
- use native move API calls wherever possible (poloniex)
+48
View File
@@ -0,0 +1,48 @@
# Sticky Order
An advanced order that stays at the top of the book (until the optional limit). The order will automatically stick to the best BBO until the complete amount has been filled.
TODO:
- implement fallback for when this order is alone at the top, some spread before everyone else
- finalize API
- add more events / ways to debug
- pull ticker data out of this order market data should flow from the broker (so we can easier move to at least public websocket streams).
## Example usage
const Broker = require('gekko-broker');
const gdax = new Broker({
currency: 'EUR',
asset: 'BTC',
exchange: 'gdax',
// Enables access to private endpoints.
// Needed to create orders and fetch portfolio
private: true,
key: 'x',
secret: 'y',
passphrase: 'z'
});
gdax.portfolio.setBalances(console.log);
const type = 'sticky';
const amount = 0.5;
const side = 'buy';
const limit = 6555;
const order = gdax.createOrder(type, side, amount, { limit });
order.on('statusChange', status => console.log(status));
order.on('filled', result => console.log(result));
order.on('completed', () => {
order.createSummary(summary => console.log)
});
// mutate like so
// order.moveAmount(1);
// order.moveLimit(6666);
+22
View File
@@ -0,0 +1,22 @@
# Wrapper API
Gekko Broker is a library that sits between trading applications and Gekko Broker Exchange Wrappers. Which means it has two APIs to communicate with other code:
![diagram describing Gekko Broker API interface](https://user-images.githubusercontent.com/969743/41892153-566293a0-7941-11e8-9998-7a5b5b554ffd.png)
This document descibres the API layer between the exchange wrappers and Gekko Broker.
## Wrapper API spec
The current API documentation is currently located [here](../extending/add_an_exchange.md).
## Wrapper API Changelog
### Gekko 0.5.x to Gekko (Broker) 0.6.0
NOTE: this API design might still have minor changes leading up to the release of Gekko 0.6. See [this thread](https://forum.gekko.wizb.it/thread-57279-post-59207.html) for more information.
- The wrapper files are now nested different (from `gekko/exchanges` to `gekkobroker/wrappers` (which equals `gekko/exchange/wrappers` for Gekko users).
- cancelOrder now requires a second parameter to be passed (that indicates whether the order was filled before it was canceled), see [details](https://github.com/askmike/gekko/commit/0e301f7d66e24ec97327f5f01380f691cc2d3725#diff-dbfe320ca090e208be32459d98fc11ed).
- checkOrder now expects an object with a few properties to be returned, see [details](https://github.com/askmike/gekko/commit/e0d4a7362cd74b4b4f50759b1012ce489ea44a0c#diff-dbfe320ca090e208be32459d98fc11ed).
- Error handling has gotten a lot more complex, with an updated error interface between a retry system (provided by Gekko) and the exchange wrapper. [Read more here](https://github.com/askmike/gekko/commit/e0d4a7362cd74b4b4f50759b1012ce489ea44a0c#diff-dbfe320ca090e208be32459d98fc11ed).
@@ -0,0 +1,148 @@
# Configuring Gekko on a server
*NOTE: unfortunately configuring Gekko to run on a server is hard. Unless you are running in a completely trusted network (home network) you WILL need to get an SSL certificate, upstream Gekko through a webserver, etc. I am creating an official Gekko service called [Gekko Plus](https://gekkoplus.com/) that will NOT require any of this stuff.*
Gekko runs great headless (on a server, raspberry PI) but the default configuration assumes that you will be using a browser from the same machine to access the interface.
# Installation
Please see the normal [installing gekko](./installing_gekko.md) document, but before starting gekko please update the configuration as stated below:
# Configuring Gekko
In order to setup Gekko so that you can access it remotely you need to open and edit the following file: `gekko/web/vue/dist/UIconfig.js`. You need to configure this file according to your use case:
- You want to Gekko headless in a trusted environment (eg. on a raspberry pi or old laptop in your home network) - [see here](#configuring-gekko-to-run-headless-in-a-trusted-environment).
- You want to run Gekko in the cloud on a server - [see here](#configuring-gekko-to-run-in-the-cloud).
## Configuring Gekko to run headless in a trusted environment
Edit the uiconfig file like so:
const CONFIG = {
headless: true,
api: {
host: '0.0.0.0',
port: 3000,
},
ui: {
ssl: false,
host: 'x.x.x.x', // Set this to the IP of the machine that will run Gekko
port: 3000,
path: '/'
},
adapter: 'sqlite'
}
You can now access the Gekko UI by going to `http://x.x.x.x:3000` in a browser (change `x.x.x.x` with the IP of the machine that will run Gekko).
## Configuring Gekko to run in the cloud
Important note: if you expose Gekko to the open internet (or on any non trusted network) you are recommended to put a secure reverse proxy (for example with both [SSL](#Obtaining-a-SSL-certificate) and [BasicAuth](#Create-htpasswd-for-basic-password-authentication)) in front of it. While we believe Gekko is hard to exploit, it allows for 24/7 backtesting which will drain your machine's resources (possible DoS).
The following assumes you configured a reverse proxy, if you did not simply follow [these instructions](#Configuring-NGINX-as-a-reverse-proxy) to do so.
const CONFIG = {
headless: true,
api: {
host: '127.0.0.1',
port: 3000,
},
ui: {
ssl: true,
host: 'gekko.example.com',
port: 443,
path: '/' // change this if you are serving from something like `example.com/gekko`
},
adapter: 'sqlite'
}
## Configuring NGINX as a reverse proxy
NGINX is a highly configurable, lightweight, yet easily deployed webserver allowing features such as a reverse proxying using secure sockets layer with authentication and much more.
Installing NGINX using your Operating Systems package manager of choice is pretty straight forward. For Debian Linux it is a simple sudo apt-get install nginx
Once NGINX is installed you will need to modify the configuration file. For Debian Linux the config is located at /etc/nginx/sites-enabled/default
server {
listen 80;
listen [::]:80;
server_name gekko.example.com;
return 301 https://$server_name$request_uri;
}
upstream websocket {
server localhost:3000;
}
server {
listen 443 ssl;
listen [::]:443 ssl;
root /var/www/html;
ssl_certificate /etc/nginx/ssl/nginx.crt;
ssl_certificate_key /etc/nginx/ssl/nginx.key;
location / {
proxy_buffers 8 32k;
proxy_buffer_size 64k;
proxy_pass http://websocket;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-NginX-Proxy true;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 86400s;
proxy_send_timeout 86400s;
auth_basic "Restricted Content";
auth_basic_user_file /etc/nginx/.htpasswd;
}
}
## Obtaining a SSL certificate
Your OS may or may not ship with openssl preinstalled. In the case it doesn't, simply install openssl using your package manager of choice. eg: `sudo apt-get install openssl`.
Below you can choose between creating a self signed certificate useful if you do not have a fqdn (fully qualified domain name), or if you by chance do have a fqdn you can use certbot to obtain a Let's Encrypt CA signed certificate.
### To create a self signed certificate:
sudo mkdir /etc/nginx/ssl
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/nginx/ssl/nginx.key -out /etc/nginx/ssl/nginx.crt
### To obtain a Let's Encrypt CA signed certificate:
Install certbot, a client to obtain signed ssl certificates for your domain.
sudo apt-get install certbot
Run the following command:
certbot certonly --standalone -d example.com -d gekko.example.com
Modify your NGINX config and replace the ssl lines with the following:
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
add_header Strict-Transport-Security "max-age=31536000";
## Create htpasswd for basic password authentication
Change username to desired username and enter password when prompted:
printf "username:`openssl passwd -apr1`\n" >> /etc/nginx/.htpasswd
+62
View File
@@ -0,0 +1,62 @@
# Installing Gekko
*NOTE: unfortunately installing and managing Gekko is hard. You will need to touch the commandline and install a few developer tools. I am creating an official Gekko service called [Gekko Plus](https://gekkoplus.com/) that will NOT require any installation.*
- *Windows user? Please see the doc [installing Gekko on windows](./installing_gekko_on_windows.md) instead.*
- *Docker user? You can run Gekko in a docker container, see [installing Gekko using Docker](./installing_gekko_using_docker.md) instead.*
- *Server user? In order to run Gekko headless, see [configuring Gekko on a server](./configuring_gekko_on_a_server.md) instead.*
Here is a video of me explaining how to install Gekko the easiest way possible:
[![screen shot 2017-04-20 at 00 03 45](https://cloud.githubusercontent.com/assets/969743/25205894/e7f4ea64-255c-11e7-891b-28c080a9fbf2.png)](https://www.youtube.com/watch?v=R68IwVujju8)
To get Gekko running you need to do the following:
- install nodejs
- install git
- download Gekko
- install Gekko & Gekko Broker dependencies
## Installing nodejs
Gekko requires [nodejs](https://nodejs.org/en/) to be installed. Go ahead and install this if it's not already (Gekko requires at least version 8.11.2). We advice to download the current LTS.
## Installing git
As part of Gekko's installation process git is used, see [this guide](https://www.linode.com/docs/development/version-control/how-to-install-git-on-linux-mac-and-windows/) for installation instructions. If you do not already have git on your system.
## Downloading Gekko
The recommended way of downloading Gekko is by using git. This makes keeping Gekko up to date a lot easier. Run this in a terminal:
git clone git://github.com/askmike/gekko.git -b stable
cd gekko
This will download the latest stable version of Gekko, remove the final `-b stable` part to download the current latest release (which might not be as stable).
Alternatively you can manually download the latest stable version of Gekko on the [releases page](https://github.com/askmike/gekko/releases).
## Installing Gekko's dependencies
Once you have Gekko downloaded you need to install the dependencies, open your terminal and navigate to the gekko folder and run:
npm install --only=production
*NOTE: You may see a vulnerability warning from NPM, if you run npm audit with --force, Gekko will break. See [here](https://github.com/askmike/gekko/issues/2585#issuecomment-428450997).*
You also need to install Gekko Broker's dependencies, run:
cd exchange
npm install --only=production
cd ..
## Starting Gekko
After all the above you can start Gekko by running the following in your terminal:
node gekko --ui
## Updating Gekko
See the [updating Gekko](./updating_gekko.md) doc.
@@ -0,0 +1,74 @@
# Installing Gekko on Raspberry Pi 2 or 3
This manual is intended for a Raspberry Pi 2 or 3 with freshly installed Raspbian Stretch (Lite).
To get Gekko running on your Pi you need to do the following:
- update your package lists
- install nodejs
- download Gekko
- install Gekko's dependencies
- (optional) Configure your Pi as a headless server in your local network
## Update your package lists
sudo apt-get update
sudo apt-get upgrade
## Installing nodejs
We recommend installing the latest LTS Version of Node, currently 8.x.x
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
sudo apt-get install -y nodejs
Important: Ignore the errors!
=> It automatically builds from source instead, it can take over 10 minutes! Do not abort the process
## Downloading Gekko
The recommended way of downloading Gekko is by using git. This makes keeping Gekko up to date a lot easier. Run this in a terminal:
sudo apt-get install git
git clone git://github.com/askmike/gekko.git -b stable
cd gekko
This will download the latest stable version of Gekko, remove the final `-b stable` part to download the current latest release (which might not be as stable).
## Installing Gekko's dependencies
Once you have Gekko downloaded you need to install the dependencies, open your terminal and navigate to the gekko folder and run:
npm install --only=production
cd exchange
npm install --only=production
cd ..
## Configure your Pi as a headless server
cd web/vue/dist
nano UIconfig.js
Set headless to true
Set api.host to 0.0.0.0
Set ui.host to Pi's IP address (e.g. 192.168.1.74)
## Starting Gekko
After all the above you can start Gekko by running the following in your terminal:
node gekko --ui
Open your browser and type in Pi's IP:port (default port: 3000)
## Updating Gekko
See the [updating Gekko](./updating_gekko.md) doc.
## Run gekko in background
If you access Pi headless via SSH, you have to use a software like tmux to run Gekko in background
## Installing Gekko on Raspberry Pi 1
It is possible to run Gekko on Raspberry Pi 1, but you have to manually install Nodejs armv6 version
@@ -0,0 +1,77 @@
# Installing Gekko on windows
*NOTE: unfortunately installing and managing Gekko is hard. You will need to touch the commandline and install a few developer tools. I am creating an official Gekko service called [Gekko Plus](https://gekkoplus.com/), it will NOT require any installation.*
### Note:
#### Windows does not natively support TA-lib. We are currently working on implementing the Tulip Indicators Library, which will provide similar functionality (see [#708](https://github.com/askmike/gekko/issues/708)).
#### For advanced users only: As a temporary workaround until [#708](https://github.com/askmike/gekko/issues/708) is implemented, TA-lib can be used on Windows through Bash on Windows 10. See "Installing Gekko on Windows with bash on Windows 10"
Here is a youtube video I made that shows exactly how to set up Gekko:
[![screen shot 2017-04-20 at 00 03 45](https://cloud.githubusercontent.com/assets/969743/25205894/e7f4ea64-255c-11e7-891b-28c080a9fbf2.png)](https://www.youtube.com/watch?v=R68IwVujju8)
To get Gekko running on Windows you need to do the following:
- install nodejs
- download Gekko
- install Gekko's dependencies
## Install nodejs
Gekko runs on nodejs so we have to install that first. Head over the [nodejs homepage](http://nodejs.org/) and install the LTS version of nodejs.
## Install Gekko
The easiest way to download Gekko is to go to the [Github repo](https://github.com/askmike/gekko) and click on the 'zip' button at the top. Once you have downloaded the zip file it's the easiest to extract it. When you have done that we can begin with the cool stuff:
### Open up command line
* Start
* Type in 'cmd.exe'
* Press enter
### Install dependencies
(After every command, press enter)
First navigate to Gekko:
cd Downloads
cd gekko-stable
cd gekko-stable
Install Gekko's dependencies:
npm install --only=production
*NOTE: You may see a vulnerability warning from NPM, if you run npm audit with --force, Gekko will break. See [here](https://github.com/askmike/gekko/issues/2585#issuecomment-428450997).*
Install Gekko Broker's dependencies:
cd exchange
npm install --only=production
cd ..
### Install Tulip Indicators
If you are using Windows you will need to install python and the VC++ 2015 build tool, the easiest way to do this is through node as an administrator:
npm install windows-build-tools --global --production
Once your build tools are installed, or for other operating systems
npm install tulind --only=production
### Starting Gekko
node gekko --ui
Your browser should automatically open with the UI. If it doesn't, manually browse to [http://localhost:3000](http://localhost:3000).
### Stopping Gekko
In the command line hold `ctrl` + `c`.
### Updating Gekko
See the [updating Gekko](./updating_gekko.md) doc.
@@ -0,0 +1,91 @@
# Installing Gekko on Windows with bash on Windows 10
*NOTE: unfortunately installing and managing Gekko is hard. You will need to touch the commandline and install a few developer tools. I am creating an official Gekko service called [Gekko Plus](https://gekkoplus.com/), it will NOT require any installation.*
### Note:
#### This guide is for advance users only! This is a temporary solution until [#708](https://github.com/askmike/gekko/issues/708) is implemented
#### You must be running a 64-bit version of Windows 10 to use Bash on Windows 10
#### TA-lib does not support Windows 10, but it can be used on Bash on Windows 10 by following these instructions
## To get Gekko running on Bash on Windows you need to do the following:
- enable Bash on Windows 10
- install nodejs
- install git
- download and install Gekko and its dependencies
- edit the handle.js file
- install the correct version of TA-lib
## Enable Bash on Windows 10
To install Bash shell on your Windows 10 PC, do the following (see [here](https://www.windowscentral.com/how-install-bash-shell-command-line-windows-10) for more info):
- Open Settings.
- Click on Update & security.
- Click on For Developers.
- Under "Use developer features", select the Developer mode option to setup the environment to install Bash.
- On the message box, click Yes to turn on developer mode.
- After the necessary components install, you'll need to restart your computer.
- Once your computer reboots, open Control Panel.
- Click on Programs.
- Click on Turn Windows features on or off.
- Check the Windows Subsystem for Linux (beta) option.
- Click OK.
- Once the components installed on your computer, click the Restart now button to complete the task.
After your computer restarts, you will notice that Bash will not appear in the "Recently added" list of apps, this is because Bash isn't actually installed yet. Now that you have setup the necessary components, use the following steps to complete the installation of Bash:
- Open Start, do a search for bash.exe, and press Enter.
- On the command prompt, type y and press Enter to download and install Bash from the Windows Store.
Then you'll need to create a default UNIX user account. This account doesn't have to be the same as your Windows account. Enter the username in the required field and press Enter (you can't use the username "admin"). Close the "bash.exe" command prompt.
Now that you completed the installation and setup, you can open the Bash tool from the Start menu like you would with any other app.
## Install nodejs
Gekko runs on nodejs so we have to install that first.
Open up bash and install node.js: (taken from [here](https://nodejs.org/en/download/package-manager/#debian-and-ubuntu-based-linux-distributions))
```
sudo apt-get update
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
sudo apt-get install -y nodejs
sudo apt-get install -y build-essential
```
## Install Gekko and its dependencies
The easiest way to download Gekko is to use Git:
- Install Git
`sudo apt-get install git`
- Download and install gekko in you home directory (/home/yourusername): (taken from [here](https://gekko.wizb.it/docs/installation/installing_gekko.html)):
```
git clone git://github.com/askmike/gekko.git
cd gekko
npm install --only=production
cd exchange
npm install --only=production
cd ..
```
*NOTE: You may see a vulnerability warning from NPM, if you run npm audit with --force, Gekko will break. See [here](https://github.com/askmike/gekko/issues/2585#issuecomment-428450997).*
### Starting Gekko
`node gekko --ui`
Your browser should automatically open with the UI. If it doesn't, manually browse to [http://localhost:3000](http://localhost:3000).
### Stopping Gekko
In bash hold `ctrl` + `c`.
### Updating Gekko
See the [updating Gekko](./updating_gekko.md) doc.
@@ -0,0 +1,25 @@
# Installing Gekko using Docker
Installing and running gekko in a docker container for use on the same machine is simple with the following commands:
```
$ docker-compose build
$ docker-compose up -d
```
You can now find your gekko instance running on `localhost:3000`.
## Installing for external access
However if you want to run Gekko on another machine (in the cloud, on a server), you need to specify the host machine and its port like so:
```
$ docker-compose build
$ HOST=mydomain.com PORT=3001 docker-compose up -d
```
You can now find your gekko instance running on `mydomain.com:3001`.
If running behind an SSL-terminating proxy, make sure to set `USE_SSL=1` to tell the Gekko to use the HTTPS and WSS protocols instead of the default HTTP and WS protocols.
To see logs: `docker logs -f gekko_gekko_1`. View which dockers are running by executing `docker ps`.
+42
View File
@@ -0,0 +1,42 @@
# Updating Gekko
## Prepare
Before updating your local version of Gekko it's good to keep a few things in mind:
- If you have configured a UIconfig (to run Gekko on a server for example) make a copy of the UIconfig file (stored in `gekko/web/vue/dist/`) first and call it something else (such as `my-UIconfig.js`). After that revert the file to it's original state (which can be found in `gekko/web/baseUIconfig.js/`) prior to updating (or git will complain).
- Check the changelog (found in the [releases page](https://github.com/askmike/gekko/releases)) for breaking changes) regarding:
- (in case you changed the UIconfig) for changes in the UIconfig.
- (in case you were using non standard strategies) strategy API, to make sure your strategies will run in the new version.
- any other breaking changes specified inside the release log (such as required node and or browser versions).
## Updating to a new stable release
Run the following commands inside the Gekko directory:
git checkout stable
git pull
npm install --only=production
cd exchange
npm install --only=production
cd ..
## Updating the develop branch
The develop branch contains the most recent code as we are working on Gekko. In most scenarios this should considered less stable. But note that once a bug is found and fixed the fixes are applied here immediately while it takes the release of a new version to have these changes available in the stable branch.
git checkout develop
git pull
npm install --only=production
cd exchange
npm install --only=production
cd ..
### Compiling the frontend on the develop branch
If you are using the UI and it changed since the latest release you need to manually recompile it since (as of v0.6.2) Gekko only ships compiled frontends with new releases.
cd web/vue
npm install
npm run build
cd ../..
+44
View File
@@ -0,0 +1,44 @@
# Gekko's architecture
![Gekko architecture](https://wizb.it/gekko/static/architecture.jpg)
Every Gekko instance has two core components:
- A market
- A GekkoStream
Communication between those two components is handled by Node.JS' [Stream API](https://nodejs.org/api/stream.html). The Market implements a Readable Stream interface while the GekkoStream implements a Writeable Stream interface.
## A Market
All markets in Gekko eventually output `candle` data. Where these candles come from and how old they are does not matter to the GekkoStream they get piped into. On default Gekko looks for markets in the [`core/markets/` directory](https://github.com/askmike/gekko/tree/stable/core/markets). The top orange block in the picture is a BudFox market (the default semi-realtime market that gets live data from exchanges).
Example Markets that come included with Gekko are:
- **BudFox** (a realtime market): this market stays on indefinitely and outputs candles from the live markets in semi-realtime (cryptocurrency exchanges run 24/7).
- **backtest**: this market reads candles from a database and outputs them as fast as the GekkoStream is able to consume them (the GekkoStream will run TA strategies over these candles).
- **importer**: the importer market will fetch historical data from an exchange and pass on (to the GekkoStream who inserts them in a database).
## A GekkoStream
A GekkoStream is nothing more than a collection of [plugins](../commandline/plugins.md). Plugins are simple modules that can subscribe to events, and do something based on event data. The most basic event every GekkoStream has is the "candle" event, this event comes from the market.
However **plugins are allowed to broadcast their own events, which other plugins can subscribe to**. An example of this is the `tradingAdvisor` plugin. This plugin will implement a [strategy](../strategies/introduction.md) that will be fed candle data. As soon as the strategy suggests to take a certain position in the market ("I detect an uptrend, I advice to go **long**") it will broadcast an `advice` event. The `paperTrader` is a plugin that simulates trading using these advices, the `trader` is a plugin that creates real market orders based on these advices. You can decide to only turn the `paperTrader` on or to turn the `trader` on (you now have a live trading bot).
When you run a backtest using Gekko the following things happen:
- Gekko configures a `backtest` market.
- Gekko loads all configured plugins that are supported in the `backtest` mode* into a GekkoStream.
- Gekko pipes the market into the GekkoStream and voila!
\*Gekko refuses to load plugins that are unsupported in specific modes. During backtests you **never** want to enable the real trader to enter market orders. Because if you would the advice would be based on specific moments in the backtest, not on the current state of the market.
## Plugins & Adapters
Those two core components describe the majority of Gekko's flow. A lot "core functionality" like saving candles to disk are simply plugins that push all candles to a database.
## Separated architecture
The modular nature of Gekko makes it very dynamic and allows for rapidly creating new plugins. However there is an ugly side to this story:
The `tradingAdvisor` runs TA strategies against a market. The problem however is that most TA indicators need some history before they can give accurate results. If you want to use an EMA (exponential moving average), you need some history to base the initial average on. But because the tradingAdvisor doesn't know what market data is going to be made available later by the market, it needs to do some fetching itself and compare that to locally available market data (stored in the local database) to see if it can stitch the two sources.
+41
View File
@@ -0,0 +1,41 @@
# BudFox
**Similar to the [movie Wallstreet](https://en.wikipedia.org/wiki/Wall_Street_(1987_film)), Gekko delegates the dirty work of getting fresh data to Bud Fox. Bud Fox delivers the data to Gekko who uses this data to make investment decisions.**
Whenever Gekko works with realtime market data, it spawns a BudFox to fetch and transform the data for every market (exchange + asset + pair, for example: `bitstamp USD/BTC`). Bud Fox will keep on fetching data from the market in semi-realtime, turn historical trades into minutely candles (and make sure every minute of data has a candle).
BudFox exposes a stream of `candles` which are fed to Gekko.
## Advanced Usage
BudFox is a small part of Gekko's core that aggregates realtime market data from any supported exchange into a readable stream of candles. Example usage:
var config = {
exchange: 'Bitstamp',
currency: 'USD',
asset: 'BTC'
}
new BudFox(config)
.start()
// convert JS objects to JSON string
.pipe(new require('stringify-stream')())
// output to standard out
.pipe(process.stdout);
Outputs:
{"start":"2015-02-02T23:08:00.000Z","open":238.21,"high":239.35,"low":238.21,"close":238.66,"vwp":8743.778447997309,"volume":203.6969347,"trades":56}
{"start":"2015-02-02T23:09:00.000Z","open":239.03,"high":240,"low":238.21,"close":239.19,"vwp":8725.27119145289,"volume":323.66383462999994,"trades":72}
{"start":"2015-02-02T23:10:00.000Z","open":239.19,"high":239.8,"low":234.68,"close":235,"vwp":6664.509955946812,"volume":114.67727173,"trades":48}
{"start":"2015-02-02T23:11:00.000Z","open":237.77,"high":238.51,"low":235,"close":238.1,"vwp":3158.835462414369,"volume":41.47081054999999,"trades":28}
{"start":"2015-02-02T23:12:00.000Z","open":237,"high":238,"low":236.78,"close":237.9,"vwp":1634.5173557116634,"volume":70.58755061,"trades":22}
{"start":"2015-02-02T23:13:00.000Z","open":237.95,"high":238.49,"low":237.95,"close":238.49,"vwp":604.219141331534,"volume":12.196531389999999,"trades":7}
{"start":"2015-02-02T23:14:00.000Z","open":238.51,"high":241,"low":237.89,"close":241,"vwp":7610.305142999085,"volume":579.5321983399998,"trades":67}
{"start":"2015-02-02T23:15:00.000Z","open":238.12,"high":239.76,"low":238.12,"close":239.1,"vwp":1828.5872875471068,"volume":31.16232463,"trades":17}
{"start":"2015-02-02T23:16:00.000Z","open":239.1,"high":239.76,"low":239.1,"close":239.67,"vwp":1339.3753800771717,"volume":5.56431998,"trades":12}
{"start":"2015-02-02T23:17:00.000Z","open":239.27,"high":239.99,"low":239.25,"close":239.92,"vwp":1519.3392752690336,"volume":6.984999999999999,"trades":14}
{"start":"2015-02-02T23:18:00.000Z","open":239.92,"high":239.98,"low":238.98,"close":238.98,"vwp":4162.807256131301,"volume":21.17212333,"trades":29}
{"start":"2015-02-02T23:19:00.000Z","open":239,"high":239,"low":238.15,"close":238.33,"vwp":1627.2581467076204,"volume":31.682705360000003,"trades":15}
{"start":"2015-02-02T23:20:00.000Z","open":238.33,"high":239.95,"low":238.33,"close":239,"vwp":3648.661808492067,"volume":128.35564560999998,"trades":23}
// etc..
+359
View File
@@ -0,0 +1,359 @@
# Events
As described in the [architecture](./architecture.md) events play a key role in the complete system: they relay all information between separate components (like [plugins](./plugins.md)). This makes the codebase scalable, testable and it separates concerns.
if you run the Gekko UI events are relayed between core components as well as broadcasted (via the UI server) to the web UI. This means that all events broadcasted by any plugin automatically end up in the web UI.
Note that all events from Gekko come from a plugin (with the exception of the `candle` event, which comes from the market), and no plugin is required for Gekko to run, this means it might be possible that some events are never broadcasted since their originating plugin is not active. If a plugin wants to listen to an event that will never be broadcasted (because of a lack of another plugin) this will be warned in the console like so:
(WARN): Paper Trader wanted to listen to the tradingAdvisor, however the tradingAdvisor is disabled.
## List of events emitted by standard plugins
- [candle](#candle-event): Every time Gekko calculates a new one minute candle from the market.
- [stratWarmupCompleted](#stratWarmupCompleted-event): When the strategy is done warming up.
- [advice](#advice-event): Every time the trading strategy has a new trading signal.
- [stratUpdate](#stratUpdate-event): Every time the strategy has processed a new strat candle.
- [stratNotification](#stratNotification-event): Every time the strategy emit new strategy notification.
- [tradeInitiated](#tradeInitiated-event): Every time a trading plugin (either the live trader or the paper trader) is going to start a new trade (buy or sell).
- [tradeCompleted](#tradeCompleted-event): Every time a trading plugin (either the live trader or the paper trader) has completed a trade.
- [tradeAborted](#tradeAborted-event): Every time a trading plugin (either the live trader or the paper trader) has NOT acted on new advice (due to insufficient funds or a similar reason).
trader) has NOT acted on new advice (due to unsufficiant funds or a similar reason).
- [tradeErrored](#tradeErrored-event): Every time the live trader was unable to execute an initialized.
- [tradeCancelled](#tradeCancelled-event): Every time the live trader cancelled a not yet executed trade.
- [portfolioChange](#portfolioChange-event): Every time the content of the portfolio has changed.
- [portfolioValueChange](#portfolioValueChange-event): Every time value of the portfolio has changed.
- [performanceReport](#performanceReport-event): Every time the profit report was updated.
- [roundtrip](#roundtrip-event): Every time a new roundtrip has been completed.
- [triggerCreated](#triggerCreated-event): Every time a trader has created a new trigger.
- [triggerFired](#triggerFired-event): Every time a created trigger has fired.
- [triggerAborted](#triggerAborted-event): Every time a created trigger has been aborted due to new advice.
Beside those there are also two additional market events that are only emitted when Gekko is running in realtime mode (NOT during a backtest for performance reasons).
- [marketStart](#marketStart-event): Once, when the market just started.
- [marketUpdate](#marketUpdate-event): Whenever the market has fetched new raw market data.
### candle event
- What: An object containing a one minute candle from the market.
- When: In liquid markets roughly every minute.
- Subscribe: Your plugin can subscribe to this event by registering the `processCandle` method.
- Async: When subscribing to this event the second argument will be a callback which you are expected to call when done handling this event.
- Notes:
- Depending on the gekko configuration these candles might be historical on startup. If this is a concern for consumers, make sure to deal with this properly.
- In illiquid markets (of less than a trade per minute) Gekko will calculate these candles in batches and a few might come at the same time.
- These are always one minute candles, this is the lowest level of market data flowing through a gekko stream.
- Example:
{
start: [moment object of the start time of the candle],
open: [number, open of candle],
high: [number, high of candle],
low: [number, low of candle],
close: [number, close of candle],
vwp: [number, average weighted price of candle],
volume: [number, total volume volume],
trades: [number, amount of trades]
}
### stratWarmupCompleted event
- What: An object signaling that the strategy is now completely warmed up
and will start signaling advice.
- When: Once the strategy consumed more market data than defined by the required history.
- Subscribe: You can subscribe to this event by registering the `processWarmupCompleted` method.
- Notes:
- This event is triggered on init when the strategy does not require any history (and thus no warmup time).
- Example:
{
start: [moment object of the start time of the first candle after the warmup],
}
### stratCandle event
- What: An object describing an updated strat candle the strat has processed.
- When: when the strategy is initialized is started.
- Subscribe: You can subscribe to this event by registering the `processStratCandle` method.
- Notes:
- This is the candle that the strategy sees: if you configured the candleSize to 60 (minutes) this event will contain a 60 minute candle.
- Strat Candles are emitted while the strategy is still warming up (before the `stratWarmupCompleted` event).
- Example:
{
start: [moment object of the start time of the candle],
open: [number, open of candle],
high: [number, high of candle],
low: [number, low of candle],
close: [number, close of candle],
vwp: [number, average weighted price of candle],
volume: [number, total volume volume],
trades: [number, amount of trades]
}
### stratUpdate event
- What: An object describing updated state of the strategy based on a new strat candle.
- When: when the strategy has
- Subscribe: You can subscribe to this event by registering the `processStratUpdate` method.
- Notes:
- Strat updates are emitted while the strategy is still warming up (before the `stratWarmupCompleted` event).
- Example:
{
date: [moment object of the start time of the candle],
indicators: {
mymacd: [number, result of running this indicator over current candle]
}
}
### stratNotification event
- What: An object describing new notification from your strategy
- When: when the strategy emit using `this.notify()` function
- Subscribe: You can subscribe to this event by registering the `processStratNotification` method.
- Example:
{
date: [moment object of the start time of the candle],
content: [String content notification in strategy]
}
### advice event
- What: An advice from the strategy, the advice will either be LONG or SHORT.
- When: This depends on the strategy and the candleSize.
- Subscribe: You can subscribe to this event by registering the `processAdvice` method.
- Example:
{
recommendation: [position to take, either long or short],
date: [moment object of this advice],
id: [string identifying this unique trade],
trigger: {
type: [type of trigger, currently always "trailingStop"],
// optional parameters per type of trigger
}
}
### tradeInitiated event
- What: An object signaling that a new trade will be executed.
- When: At the same time as the advice event if the trader will try to trade.
- Subscribe: You can subscribe to this event by registering the `processTradeInitiated` method.
- Example:
{
id: [string identifying this unique trade],
adviceId: [number specifying the advice id this trade is based on],
action: [either "buy" or "sell"],
date: [moment object, exchange time trade completed at],
portfolio: [object containing amount in currency, asset and total balance],
balance: [number, total worth of portfolio]
}
### tradeAborted event
- What: An object signaling the fact that the trader will ignore the advice.
- When: At the same time as the advice event if the trader will NOT try to trade.
- Subscribe: You can subscribe to this event by registering the `processTradeAborted` method.
- Example:
{
id: [string identifying this unique trade],
adviceId: [number specifying the advice id this trade is based on],
action: [either "buy" or "sell"],
date: [moment object, exchange time trade completed at],
reason: [string explaining why the trade was aborted]
}
### tradeCancelled event
- What: An object signaling the fact that the a trade originally initiated was now cancelled.
- When: After a receiving a tradeInitiated event and than a advice event (without a tradeCompleted event between them).
- Subscribe: You can subscribe to this event by registering the `processTradeCanceled` method.
- Example:
{
id: [string identifying this unique trade],
adviceId: [number specifying the advice id this trade is based on],
date: [moment object, exchange time trade completed at]
}
### tradeErrored event
- What: An object singaling the fact that the a trade orginially initiated was now cancelled
- When: After a tradeInitiated event
- Subscribe: You can subscribe to this event by registering the `processTradeErrored` method.
- Example:
{
id: [string identifying this unique trade],
adviceId: [number specifying the advice id this trade is based on],
date: [moment object, exchange time trade completed at],
reason: [string explaining why the trade was aborted]
}
### tradeCompleted event
- What: Details of a completed trade.
- When: Some point in time after the tradeInitiated event.
- Subscribe: You can subscribe to this event by registering the `processTradeCompleted` method.
- Example:
{
id: [string identifying this unique trade],
adviceId: [number specifying the advice id this trade is based on],
action: [either "buy" or "sell"],
price: [number, average price that was sold at],
amount: [number, how much asset was trades (excluding "cost")],
cost: [number the amount in currency representing fee, slippage and other execution costs],
date: [moment object, exchange time trade completed at],
portfolio: [object containing amount in currency and asset],
balance: [number, total worth of portfolio],
feePercent: [the cost in fees],
effectivePrice: [executed price - fee percent, if effective price of buy is below that of sell you are ALWAYS in profit.]
}
### portfolioChange event
- What: An object containing new portfolio contents (amount of asset & currency).
- When: Some point in time after the advice event, at the same time as the tradeCompleted event.
- Subscribe: You can subscribe to this event by registering the `processPortfolioChange` method.
- Example:
{
currency: [number, portfolio amount of currency],
asset: [number, portfolio amount of asset],
}
### portfolioValueChange event
- What: An object containing the total portfolio worth (amount of asset & currency calculated in currency).
- When: Every time the value of the portfolio has changed, if the strategy is in a LONG position this will be every minute.
- Subscribe: You can subscribe to this event by registering the `processPortfolioValueChange` method.
- Example:
{
value: [number, portfolio amount of currency]
}
### performanceReport event
- What: An object containing a summary of the performance of the "tradebot" (advice signals + execution).
- When: Once every new candle.
- Subscribe: You can subscribe to this event by registering the `processPerformanceReport` method.
- Example:
{
startTime: Moment<'2017-03-25 19:41:00'>,
endTime: Moment<'2017-03-25 20:01:00'>,
timespan: 36000000,
market: -0.316304880517734,
balance: 1016.7200029226638,
profit: -26.789997197336106,
relativeProfit: -2.5672966425099304,
yearlyProfit: '-704041.12634599',
relativeYearlyProfit: '-67468.55576516',
startPrice: 945.80000002,
endPrice: 942.80838846,
trades: 10,
roundtrips: 5,
startBalance: 1043.5100001199999,
sharpe: -2.676305165560598
}
### roundtripInitiated event
- What: A summary of a started roundtrip.
- When: After every tradeCompleted with action `buy`.
- Subscribe: You can subscribe to this event by registering the `processRoundtripInitiated` method.
- Example:
{
id: [string identifying this roundtrip],
entryAt: Moment<'2017-03-25 19:41:00'>,
entryPrice: 10.21315498,
entryBalance: 98.19707799420277,
exitAt: Moment<'2017-03-25 19:41:00'>,
exitPrice: 10.22011632,
exitBalance: 97.9692176,
duration: 3600000,
pnl: -0.2278603942027786,
profit: -0.2320439659276161,
}
### roundtripUpdate event
- What: An updated summary of a currently open roundtrip.
- When: On every candle for as long as the bot is in a long position.
- Subscribe: You can subscribe to this event by registering the `processRoundtripUpdate` method.
- Example:
{
id: [string identifying this roundtrip],
at: Moment<'2017-03-25 19:41:00'>,
duration: 3600000,
uPnl: -0.2278603942027786,
uProfit: -0.2320439659276161,
}
### roundtrip event
- What: A summary of a completed roundtrip (buy + sell signal).
- When: After every roundtrip: a completed sell trade event that superceded a buy sell trade event.
- Subscribe: You can subscribe to this event by registering the `processRoundtrip` method.
- Example:
{
id: [string identifying this roundtrip],
entryAt: Moment<'2017-03-25 19:41:00'>,
entryPrice: 10.21315498,
entryBalance: 98.19707799420277,
exitAt: Moment<'2017-03-25 19:41:00'>,
exitPrice: 10.22011632,
exitBalance: 97.9692176,
duration: 3600000,
pnl: -0.2278603942027786,
profit: -0.2320439659276161,
}
### triggerCreated event
- What: A summary of a created trigger.
- When: After a buy advice that includes a stop.
- Subscribe: You can subscribe to this event by registering the `processTriggerCreated` method.
- Example:
{
id: [string identifying this trigger],
date: Moment<'2017-03-25 19:41:00'>,
type: type: "trailingStop",
properties: {
initialPrice: 100,
trail: 10
}
}
### triggerFired event
- What: A message indicating a created trigger has fired
- When: As soon as the trigger fired
- Subscribe: You can subscribe to this event by registering the `processTriggerFired` method.
- Example:
{
id: [string identifying this trigger],
date: Moment<'2017-03-25 19:41:00'>
}
### triggerAborted event
- What: A message indicating a created trigger has been aborted
- When: After an advice signal indicating a sell
- Subscribe: You can subscribe to this event by registering the `processTriggerAborted` method.
- Example:
{
id: [string identifying this trigger],
date: Moment<'2017-03-25 19:41:00'>
}
### marketStart event
- What: A moment object describing the first date of the market data.
- When: When the market is started.
- Subscribe: Your plugin can subscribe to this event by registering the `processMarketStart` method.
- Example:
[moment object describing the date of the first market data]
### marketUpdate event
- What: A moment object describing the point in time for up to which the market has market data.
- When: Every few seconds.
- Subscribe: Your plugin can subscribe to this event by registering the `processMarketUpdate` method.
- Example:
[moment object describing the date of the latest market data]
+57
View File
@@ -0,0 +1,57 @@
# Gekko UI
When you launch Gekko UI, you start a basic nodejs webserver with 3 components:
- It will serve frontend (HTML/CSS/JS) files for frontend written as a [vuejs app](https://vuejs.org/) (v2.5.16).
- It will will handle API requests as [koa](http://koajs.com/) (v1) routes, it will also start a websocket server used to broadcast messages in realtime (used for long lived processes Importing and Live Gekkos for example). The server API documentation can be found [here](./server_api.md).
## Gekko UI Frontend
The frontend is setup as a very basic vue app. Additionally the following libraries are used:
- [Reconnecting websocket](https://github.com/joewalnes/reconnecting-websocket)
- [Moment](http://momentjs.com/)
- [d3.js](https://d3js.org/)
- [toml](https://github.com/BinaryMuse/toml-node)
- [humanizeDuration](https://github.com/EvanHahn/HumanizeDuration.js)
The vue app itself uses the following libraries:
- [marked](https://github.com/chjj/marked)
- [pug](https://github.com/pugjs) (all html is either written in pug of markdown)
- [vue-router](https://github.com/vuejs/vue-router)
- [vuex](https://github.com/vuejs/vuex)
- [superagent](https://github.com/visionmedia/superagent) (cross browser ajax)
### Developing for the Gekko UI frontend
You first need to install all developer dependencies so the frontend app can be recompiled on your machine.
cd gekko/web/vue
npm install
After this you can launch a hot reload version of the app which will automatically recompile the frontend and reload your browser:
# path to webserver
cd gekko/web
# launch the server - we use this API
node server
# path to vue app
cd vue
npm run serve
Gekko UI is now served from port 8080, the webpack dev server will compile the vue app (in memory) and intercept all calls to the app itself (`/dist/js/app.xxx.js`) and serve the in memory app. It is important to note that this UI still talks to the API served from the `node server` command (on default http://localhost:3000/api).
If you have configured Gekko to run on non standards ports (using the UIconfig), you can have your config applied to the development environment by copying `gekko/web/vue/dist/UIconfig.js` to `gekko/web/vue/public/UIconfig.js`.
### Compiling the Gekko UI frontend
*Note: as part of the compilation process Gekko will reset the UIconfig in both `gekko/web/vue/dist/UIconfig.js` and `gekko/web/vue/public/UIconfig.js`. Only compile if you are ready to lose your personal changes.*
When you are done developing you can compile the app using these instructions:
# path to vue app
cd gekko/web/vue
npm run build
+37
View File
@@ -0,0 +1,37 @@
# Plugins
*This is a technical document explaining the role of Plugins in the Gekko codebase. For a non technical document about available plugins, see [here](../commandline/plugins.md).*
Within Gekko most functionality is encapsulated into "plugins". These are simple modules that process some data (from [Gekko events](./events.md)) and do something with it. For example emitting a new event or sending a message out to some external service like telegram, or doing a live trade at an exchange.
Whenever you run a Gekko (live trader, paper trader, backtester or importer) you are simply running a number of plugins and feeding them with market data. For a more detailed explanation, see the [architecture doc](./architecture.md).
For example, there is a plugin called the paperTrader which is responsible for simulating trades (used in [backtests](../features/backtesting.md) and [paper trading](../features/paper_trading.md)). It does this by listening to advice events coming from a strategy, and simulating trades whenever they fire (and firing trade events). Find a longer list of plugins that come with Gekko [here](../commandline/plugins.md).
- All plugins are javascript files that expose a constructor function (or ES6 class).
- All plugins are stored in `gekko/plugins`.
- All plugins are described in the file [`gekko/plugins.js`](https://github.com/askmike/gekko/blob/develop/plugins.js), this way Gekko knows how/when the plugin can be used (for example it does not make sense to run a telegram bot that will emit all trades in a backtest).
## Structure of a plugin
A plugin can be a very simple module that simply listens to some event:
// A plugin that will buy Champagne when we MOON
// example: doesn't actually work..
const alexa = require('alexa');
const MOON = 1000000;
const Plugin = function() {}
Plugin.prototype.processPortfolioValueChange = function(event) {
if(event.value > MOON) {
alexa.say('Alexa, buy the best Champagne!');
}
};
module.exports = Plugin;
Have a look at the [events doc](./events.md) for all events your plugin can subscribe to. For technical inspiration it's easiest to look at the code of Gekko's plugins (here [`gekko/plugins.js`](https://github.com/askmike/gekko/blob/develop/plugins.js)).
+795
View File
@@ -0,0 +1,795 @@
# Server API
The Gekko project has three major components:
- [Actual Gekko instance](./architecture.md)
- A nodejs server that:
- starts and manages gekkos
- broadcasts all updates from all gekkos and tracks their overall state
- has API calls to query and manage historical data (by importing more for example)
- [A web UI (vue frontend project)](./gekko_ui.md)
The nodejs server can also be used standalone as a webserver in combination with your own software (such as a new UI, a mobile app or a higher level backtester), see [other software](../extending/other_software.md) for examples).
The server exposes two different APIs: A websocket API to push gekko updates and a REST API for everything else.
When you run `node gekko --ui` it will automatically start a server. You can also do this manually by running:
cd gekko/web
node server
The server will now run on the host/port configured in `gekko/web/vue/public/UIConfig.js` (under api.host).
## REST API
### GET /api/info
Get version information of current running Gekko Server.
NOTE: The API does not have dedicated versioning, instead it uses the version of the complete Gekko project.
**response**
```
{ "version": "0.6.0" }
```
### GET /api/strategies
Get all strategies known to this Gekko. The value of the `params` key is a TOML string.
**response**
```
[
{
"name": "DEBUG_single-advice",
"params": ""
},
{
"name": "DEBUG_toggle-advice",
"params": ""
},
{
"name": "DEMA",
"params": "weight = 21\n\n[thresholds]\ndown = -0.025\nup = 0.025\n"
},
{
"name": "MACD",
"params": "short = 10\nlong = 21\nsignal = 9\n\n[thresholds]\ndown = -0.025\nup = 0.025\npersistence = 1"
},
// etc.
]
```
### GET /api/apiKeys
Returns a list of exchanges that this Gekko has API keys stored for.
NOTE: for security reasons the Gekko never exposes the API keys themselves.
**response**
```
["bitstamp","bitfinex"]
```
### GET /api/imports
Returns a list of currently running data imports.
**response**
```
[
{
"watch": {
"exchange": "poloniex",
"currency": "USDT",
"asset": "BTC"
},
"id": "765606096903592",
"latest": "2018-04-03T07:13:00Z",
"from": "2018-04-03 05:13",
"to": "2018-07-03 05:13",
"done": false
}
]
```
### GET /api/gekkos
Returns a list of currently running and archived Gekkos.
**response**
```
{
"live": {
"2018-07-03-13-14-papertrader-384222057313623": {
"mode": "realtime",
"config": {
// complete config that was passed when creating
},
"id": "2018-07-03-13-14-papertrader-384222057313623",
"type": "leech",
"logType": "papertrader",
"active": true,
"stopped": false,
"errored": false,
"errorMessage": false,
"events": {
"initial": {
"candle": {
"id": 419824,
"start": "2018-07-03T04:47:00.000Z",
"open": 6664.79999887,
"high": 6664.79999887,
"low": 6659.99999989,
"close": 6659.99999989,
"vwp": 6662.402395386147,
"volume": 0.001202,
"trades": 3
},
"portfolioChange": {
"asset": 1,
"currency": 100
},
"portfolioValueChange": {
"balance": 6759.99999989
}
},
"latest": {
"candle": {
"id": 419849,
"start": "2018-07-03T05:12:00.000Z",
"open": 6643.21466865,
"high": 6656.58532982,
"low": 6643.01,
"close": 6656,
"vwp": 6643.884436854498,
"volume": 1.9966113400000003,
"trades": 15
},
"portfolioChange": {
"asset": 1,
"currency": 100
},
"portfolioValueChange": {
"balance": 6756
}
}
},
"start": "2018-07-03T05:14:23.582Z",
"latestUpdate": "2018-07-03T05:14:24.090Z"
}
},
"archive": {}
}
```
### GET /api/exchanges
Returns a list of supported exchanges with meta information (such as supported features and tradable markets).
**response**
```
{
"name": "Bitstamp",
"slug": "bitstamp",
"currencies": [
"USD",
// and more
],
"assets": [
"BTC",
// and more
],
"maxTradesAge": 60,
"maxHistoryFetch": null,
"markets": [
{
"pair": [
"USD",
"EUR"
],
"minimalOrder": {
"amount": 5,
"unit": "currency"
},
"precision": 2
},
// and more
],
"requires": [
"key",
"secret",
"username"
],
"fetchTimespan": 60,
"tid": "tid",
"tradable": true
}
```
### POST /api/addApiKey
Adds an API key for an exchange account to Gekko. As of now only 1 API keypair can be added per exchange.
**request**
```
{
"exchange": "bitstamp",
"values": {
"key": "x",
"secret": "y"
}
}
```
**response**
```
{
"status": "ok"
}
```
### POST /api/removeApiKey
Removes an API key from Gekko.
**request**
```
{
"exchange": "bitstamp"
}
```
**response**
```
{
"status": "ok"
}
```
### POST /api/scan
Scans a daterange to find all datasets for a specific market.
**request**
```
{
"watch": {
exchange: "bitstamp",
"currency": "USD",
"asset": "BTC"
}
}
```
**response**
```
[
{
"to": 1464787560,
"from": 1464783960
},
{
"to": 1479115560,
"from": 1471112760
}
]
```
### POST /api/scansets
Scans the database for all datasets for all markets.
**request**
```
{}
```
**response**
```
{
"datasets": [
{
"exchange": "bitfinex",
"currency": "USD",
"asset": "BTC",
"ranges": [
{
"to": 1508551500,
"from": 1508493900
}
]
},
{
"exchange": "binance",
"currency": "USDT",
"asset": "BTC",
"ranges": [
{
"to": 1514351280,
"from": 1510632480
},
{
"to": 1522915680,
"from": 1522678080
}
]
},
],
"errors": [
{
"exchange": "poloniex",
"currency": "BTC",
"asset": "BTC"
}
]
}
```
### POST /api/backtest
Perform a backtest.
**request**
*(a valid gekko config object)*
Tweak the `config.backtestResultExporter.data` object to control what is included in the output. For example skip `stratCandles` if you only care about the final profit report. This way the server won't include megabytes of candle data in the output.
```
{
"watch": {
"exchange": "poloniex",
"currency": "USDT",
"asset": "ETH"
},
"paperTrader": {
"feeMaker": 0.25,
"feeTaker": 0.25,
"feeUsing": "maker",
"slippage": 0.05,
"simulationBalance": {
"asset": 1,
"currency": 100
},
"reportRoundtrips": true,
"enabled": true
},
"tradingAdvisor": {
"enabled": true,
"method": "MACD",
"candleSize": 60,
"historySize": 10
},
"MACD": {
"short": 10,
"long": 21,
"signal": 9,
"thresholds": {
"down": -0.025,
"up": 0.025,
"persistence": 1
}
},
"backtest": {
"daterange": {
"from": "2016-06-01T11:57:00Z",
"to": "2016-11-13T14:57:00Z"
}
},
"backtestResultExporter": {
"enabled": true,
"writeToDisk": false,
"data": {
"stratUpdates": false,
"roundtrips": true,
"stratCandles": true,
"stratCandleProps": [
"open"
],
"trades": true
}
},
"performanceAnalyzer": {
"riskFreeReturn": 2,
"enabled": true
}
}
```
**response**
```
{
"performanceReport": {
"startTime": "2018-04-02 14:08:00",
"endTime": "2018-04-05 04:08:00",
"timespan": "3 days",
"market": -2.159980297428632,
"startBalance": 7083.86,
"balance": 7424.849452897501,
"profit": 340.989452897501,
"relativeProfit": 4.813610840664566,
"yearlyProfit": 48210.518806418906,
"relativeYearlyProfit": 680.5684867631334,
"startPrice": 6983.86,
"endPrice": 6833.01,
"trades": 3,
"exposure": 0.3709677419354839,
"sharpe": null,
"downside": null,
"alpha": 343.14943319492966
},
"roundtrips": [
{
"id": 0,
"entryAt": 1522685280,
"entryPrice": 7019.99,
"entryBalance": 7119.6899337771,
"exitAt": 1522768080,
"exitPrice": 7365,
"exitBalance": 7447.19106625,
"duration": 82800000,
"pnl": 327.5011324729003,
"profit": 4.599935327508788
},
// and more
],
"stratCandles": [
{
"open": 6990.06,
"start": 1522678080
},
// and more
],
"trades": [
{
"id": "trade-1",
"adviceId": "advice-1",
"action": "buy",
"cost": 0.30000000000000027,
"amount": 1.01420229,
"price": 7019.99,
"portfolio": {
"asset": 1.08661475,
"currency": 0
},
"balance": 7119.6899337771,
"date": 1522685280
},
// and more
]
}
```
### POST /api/import
Start a data import.
**request**
*(a valid gekko config object)*
```
{
"watch": {
"exchange": "poloniex",
"currency": "USDT",
"asset": "BTC"
},
"importer": {
"daterange": {
"from": "2018-04-03 05:46",
"to": "2018-07-03 05:46"
}
},
"candleWriter": {
"enabled": true
}
}
```
**response**
NOTE: this only contains information regarding the started import, updates are pushed through the websocket.
```
{
"watch": {
"exchange": "poloniex",
"currency": "USDT",
"asset": "BTC"
},
"id": "7324830525419355",
"latest": "",
"from": "2018-04-03 05:46",
"to": "2018-07-03 05:46"
}
```
### POST /api/startGekko
Start a gekko instance
**request**
*(a valid gekko config object)*
In order to start a stratRunner, pass a config object that includes plugins required for a stratrunner (such as paperTrader, tradingAdvisor and performanceAnalyzer).
```
{
"watch": {
"exchange": "poloniex",
"currency": "USDT",
"asset": "BTC"
},
"candleWriter": {
"enabled": true,
},
"type": "market watcher",
"mode": "realtime"
}
```
**response**
NOTE: this only contains information regarding the started gekko, updates from are pushed through the websocket.
```
{
"mode": "realtime",
"config": {
// config that was passed in the request
},
"id": "2018-07-03-13-49-watcher-404457189518044",
"type": "watcher",
"logType": "watcher",
"active": true,
"stopped": false,
"errored": false,
"errorMessage": false,
"events": {
"initial": {},
"latest": {}
},
"start": "2018-07-03T05:49:06.685Z"
}
```
### POST /api/stopGekko
Stop a gekko instance
**request**
```
{
"id": "2018-07-03-13-49-watcher-404457189518044"
}
```
**response**
```
{
"status": "ok"
}
```
### POST /api/deleteGekko
Delete a stopped gekko instance from the archive.
**request**
```
{
"id": "2018-07-03-13-49-watcher-404457189518044"
}
```
**response**
```
{
"status": "ok"
}
```
### POST /api/getCandles
Load candles directly from the database.
**request**
```
{
"watch": {
"exchange": "poloniex",
"currency": "USDT",
"asset": "BTC"
},
"daterange": {
"to": "2018-07-03T05:53:00.000Z",
"from": "2018-07-03T05:40:00.000Z"
},
"candleSize": 1
}
```
**response**
```
[
{
"start": 1530596400,
"open": 6645.49999958,
"high": 6649.83970225,
"low": 6642,
"close": 6642,
"vwp": 6644.840723040122,
"volume": 0.007383000000000001,
"trades": 23
},
{
"start": 1530596460,
"open": 6649.69979936,
"high": 6649.69979936,
"low": 6642,
"close": 6648.89999912,
"vwp": 6645.926390922748,
"volume": 0.007383450000000001,
"trades": 21
},
// etc.
]
```
## Websocket API
A websocket server is started at the basepath of the API. Connecting to it means you'll receive update messages. Messages you send to the server via the websocket connection are completely ignored, to control the server use the REST API instead.
The possible messages are:
### import_update
Whenever there is an update regarding a running import.
```
{
type: 'import_update',
import_id: '7324830525419355',
updates: {
latest: '2018-07-03T05:49:06.685Z',
done: false
}
}
```
### import_error
Whenever there is a fatal error in a running import. After receiving this the import will not continue.
```
{
type: 'import_error',
import_id: '7324830525419355',
error: "Error string"
}
```
### gekko_new
Whenever a new Gekko has been started.
```
{
"type": "gekko_new",
"id": "2018-07-03-16-37-watcher-938815758693549",
"state": {
"mode": "realtime",
"config": {
// the complete config that was passed
},
"id": "2018-07-03-16-37-watcher-938815758693549",
"type": "watcher",
"logType": "watcher",
"active": true,
"stopped": false,
"errored": false,
"errorMessage": false,
"events": {
"initial": {},
"latest": {}
},
"start": "2018-07-03T08:37:51.965Z"
}
}
```
### gekko_event
Whenever a gekko instance has a new Gekko event. See the [gekko events doc](../events.md) for a list of all possible events and details.
```
{
"type": "gekko_event",
"id": "2018-07-03-16-37-watcher-938815758693549",
"event": {
"type": "candle",
"payload": {
"start": "2018-07-03T08:38:00.000Z",
"open": 6623.00000066,
"high": 6623.00000066,
"low": 6623.00000066,
"close": 6623.00000066,
"vwp": 6623.00000066,
"volume": 0,
"trades": 0
}
}
}
```
### gekko_stopped
Whenever a Gekko has been stopped, does not fire when the instance had a fatal error. For that see `gekko_error`.
```
{
"type": "gekko_stopped",
"id": "2018-07-03-16-37-watcher-938815758693549"
}
```
### gekko_error
Whenever a gekko received a fatal error and crashed.
```
{
"type": "gekko_error",
"id": "2018-07-03-16-37-watcher-938815758693549",
"error": "Error message"
}
```
### gekko_archived
Whenever the server does not consider the instance to be relevant anymore, fires after a gekko has been stopped or had a fatal error. After this event the gekko instance is placed in an in memory archive. It will stay here stale (as it won't be updated) until it's deleted.
```
{
"type": "gekko_stopped",
"id": "2018-07-03-16-37-watcher-938815758693549"
}
```
### gekko_deleted
Whenever an archived gekko instance got deleted.
```
{
"type": "gekko_stopped",
"id": "2018-07-03-16-37-watcher-938815758693549"
}
```
+80
View File
@@ -0,0 +1,80 @@
# About Gekko
Gekko is a **free and open source** Bitcoin TA trading and backtesting platform that connects to popular Bitcoin exchanges. It is written in javascript and runs on [nodejs](http://nodejs.org).
*Use Gekko at your own risk.*
![screen shot of gekko backtesting](https://user-images.githubusercontent.com/969743/35054500-fc705b46-fbac-11e7-9652-306c468505a3.png)
## The gist
Gekko is a tool that makes it very easy to automate your own trading strategies.
![gist of gekko](https://gekko.wizb.it/_static/gekko-gist.png)
You can either create your own trading strategy or start with the built-in example strategies. Once you have a strategy you can use Gekko to automatically run it in a few different ways:
- **Backtest**: You can start a simulation of the strategy over a historical data period and Gekko will tell you what would have happened (which trades would have been performed as well as overall performance and risk metrics).
- **Paper trader**: You can run the strategy in realtime simulate trading (trade with fake money) to see in realtime how profitable your strategy would have been.
- **Tradebot**: You can run the strategy in realtime and automatically execute orders based on the signals.
All the above modes can be run from the user interface, this interface will show charts and performance/risk statistics.
Here is a video that explains Gekko's core concepts:
[![youtube video explaining gekko](https://gekko.wizb.it/_static/yt-gist.jpg)](https://www.youtube.com/watch?v=PKIxZ-Qaphk)
## Strategies
Gekko comes with some [example strategies](../strategies/introduction.md) (which implement a single indicator). But with some basic javascript you can [create your own strategies](../strategies/creating_a_strategy.md). You can use over 130 indicators to create your perfect prediction model (using [Talib's indicators](../strategies/talib_indicators.md) or [Tulip's indicators](../strategies/tulip_indicators.md)). *Why don't you combine Bollinger Bands, CCI and MACD with a STOCHRSI indicator?*
## Automated Trading platform
Gekko can watch the realtime markets, automatically executing and evaluating your strategies in the process. Whilst doing this Gekko will store all market data it sees, this makes it possible to later simulate trading strategies against historical data to see whether they would have been profitable (backtesting).
## Limitations
Gekko is not built for HFT or anything related to being the fastest (like arbitrage) as well as some other things. Please see the [scope page](./scope.md) to read more about what you can and cannot do with Gekko.
## How does Gekko work?
![Gekko architecture](https://wizb.it/gekko/static/architecture.jpg)
Read more in the [architecture documentation](../internals/architecture.md).
## Credits
* The title is inspired by [Bateman](https://github.com/fearofcode/bateman).
* This project is inspired by the [GoxTradingBot](https://github.com/virtimus/GoxTradingBot/) Chrome plugin (which in turn is inspired by [Goomboo's journal](https://bitcointalk.org/index.php?topic=60501.0)).
## Final
If Gekko helped you in any way, you can always leave me a tip at (BTC) 13r1jyivitShUiv9FJvjLH7Nh1ZZptumwW
## Disclaimer
Gekko (nor anyone behind this project) DOES NOT give investment advice. All advice seen within Gekko is the result of running YOUR OWN strategies against the market. On top of that there might be bugs in the code - Gekko DOES NOT come with ANY warranty.
## License
The MIT License (MIT)
Copyright (c) 2014 Mike van Rossum <mike@mvr.me>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+25
View File
@@ -0,0 +1,25 @@
# Getting Help
Are you getting stuck installing or using Gekko? Are you struggling with understanding Gekko? Running into problems creating your own plugin or strategy? Do you want to discuss awesome things you want to do with Gekko? This page will explain what to do!
## Online community
If you have trouble with anything specific or you want to provide any type of feedback the online community is the place to be. You can find the community at:
1. [The online webforum](https://forum.gekko.wizb.it)
2. [The discord channel](https://discord.gg/26wMygt)
These communities are the place for things like:
- Solving installation problems
- Solving installation errors
- Helping set up Gekko on a server or embedded device
- Requesting/requesting new features and or changes such as:
- New exchanges to add
- New plugins to add
- General new features
- Getting clarity on what Gekko can do and how it works
## Technical discussion
The links above are always the first place to go to when discussing new features. But if you've found a clear bug or you want to **keep the complete discussion 100% technical (meaning completely code and architecture related)** you can use the [bug tracker on github](https://github.com/askmike/gekko/issues). Note that we are trying to keep all other discussions out of the bug tracker to keep the whole thing manageable :)
+12
View File
@@ -0,0 +1,12 @@
# Roadmap
Gekko is ever evolving and we are constantly working on new features and upgrades!
This is a small selection of things currently on the roadmap:
## Current TODO
- Improve stability of new event and backtest engine
- Port the old supported exchanges to Gekko Broker
- new UI, see [here](https://forum.gekko.wizb.it/thread-1429-post-58996.html)
- advanced orders from your strategy (Take Profit and Stop Loss)
+30
View File
@@ -0,0 +1,30 @@
# Scope
Gekko is a free and open source tool that is designed as a starters kit for automated trading on cryptocurrency markets. Gekko aims to have a low barrier entry to writing your own strategies (however a basic scripting knowledge in javascript is required for users who create their own strategies). This page will discuss the scope of some components of Gekko, explaining how things are done and why they are done a certain way.
## Market data
Gekko aggregates all market data into minutely candles (OHLC, VWP and amount of trades). This means Gekko only has to store candles on disk, which take up a predictable amount of space on your harddrive. The tradebot will use some additional market data (the orderbook) to execute orders efficiently, but this data is not visible anywhere else.
## Strategies
Strategies are simple scripts that handle new market data (OHLC candles) as well as calculated indicator results (strategies specify what indicators they want with which settings). Every time there is new data the strategy can determine to signal either LONG or SHORT. That's about it! This very simple design (candles + indicator values go in => signals come out) is quite powerful.
Unfortunately this simple design can sometimes be limiting, here are some limitations:
- Since strategies are only fed candles (and indicator values):
- Strategies cannot act on a smaller timeframe than 1 minute.
- Strategies cannot see any trades.
- Strategies cannot look at the orderbook.
- Strategies do not know what the current portfolio looks like.
- Strategies can only trigger a LONG or SHORT which signals to go "all in".
## Execution strategy
When you are using Gekko for a real tradebot Gekko will create orders at the exchange whenever your strategy signals an advice (long or short). If your strategy signal a long advice Gekko will try to buy as much "asset" as it can get with all your "currency" (if your strat is running on USD/BTC that would mean buying BTC with all your USD). As for creating the orders Gekko is conservative and stays on your side of the orderbook (this means you don not lose on the spread, slippage or taker fees). An example:
If your strategy signals a LONG signal and this is the current orderbook:
<img width="279" alt="screen shot 2017-08-26 at 23 26 22" src="https://user-images.githubusercontent.com/969743/29745564-0bb096a6-8ab6-11e7-8bdb-12a6c0274482.png">
Gekko will try to buy bitcoin by placing a limit order at a price of `4336.29` in the hope someone sells into the order. Every few seconds Gekko will readjust the order to stay on top of the orderbook. *Note that order simulation (in the paper trader and backtester) is handled differently, since the orderbook is not used in the simulation.*
+66
View File
@@ -0,0 +1,66 @@
## Supported exchanges
Gekko is able to directly communicate with the APIs of a number of exchanges. However communication with some exchanges is somewhat limited. Gekko makes the distinction between the following features:
- Monitoring: Gekko is able to retrieve live market data from the exchange. Gekko can store and run trading simulations over this data.
- Live Trading: Gekko is able to automatically execute orders (based on the signals of your strategy). This turns Gekko into a trading bot.
- Importing: Gekko is able to retrieve historical market data. This way you can easily get a month of market data over which you can [backtest][1] your strategy.
| Exchange | Monitoring | Live Trading | Importing | Notes |
| --------------------- |:----------:|:------------:|:---------:| ------------------------- |
| [Binance][24] | ✓ | ✓ | ✓ | |
| [Poloniex][2] | ✓ | ✓ | ✓ | |
| [GDAX][3] | ✓ | ✓ | ✓ | |
| [BTCC][4]* | ✓ | ✓ | ✓ | (=BTCChina) |
| [Bitstamp][5]* | ✓ | ✓ | ✕ | |
| [Kraken][6] | ✓ | ✓ | ✓ | |
| [Bitfinex][7] | ✓ | ✓ | ✓ | |
| [Bittrex][8] | ✓ | ✕ | ✕ | API problems ([#2310][26])|
| [coinfalcon][25] | ✓ | ✓ | ✓ | |
| [The Rock Trading][28]| ✓ | ✓ | ✓ | |
| [EXMO][27] | ✓ | ✓ | ✕ | |
| [wex.nz][9]* | ✓ | ✓ | ✕ | |
| [Gemini][10]* | ✓ | ✓ | ✕ | |
| [Okcoin.cn][11]* | ✓ | ✓ | ✕ | China, see [#352][20] |
| [Cex.io][12]* | ✓ | ✕ | ✕ | |
| [BTC Markets][13]* | ✓ | ✓ | ✕ | |
| [Luno][14] | ✓ | ✓ | ✓ | previously BitX |
| [lakeBTC][15]* | ✓ | ✕ | ✕ | |
| [meXBT][16]* | ✓ | ✕ | ✕ | see [here][21] |
| [zaif][17]* | ✓ | ✕ | ✕ | |
| [lakeBTC][18]* | ✓ | ✕ | ✕ | |
| [bx.in.th][19]* | ✓ | ✕ | ✕ | |
| [bitcoin.co.id][22]* | ✓ | ✓ | ✕ | |
| [Quadriga CX][23]* | x | x | ✕ | Exchange is down. | |
*Temporary disabled since 0.6! If you were planning on using this exchange please e-mail me (address at the bottom of this page).
[1]: ../features/backtesting.md
[2]: https://poloniex.com
[3]: https://gdax.com
[4]: https://btcc.com
[5]: https://bitstamp.com
[6]: https://kraken.com
[7]: https://bitfinex.com
[8]: https://bittrex.com
[9]: https://wex.nz
[10]: https://gemini.com
[11]: https://www.okcoin.cn
[12]: https://cex.io
[13]: https://btcmarkets.net
[14]: https://www.luno.com
[15]: https://lakebtc.com
[16]: https://mexbt.com
[17]: https://zaif.jp/trade_btc_jpy
[18]: https://lakebtc.com
[19]: https://bx.in.th
[20]: https://github.com/askmike/gekko/pull/352
[21]: https://github.com/askmike/gekko/issues/288#issuecomment-223810974
[22]: https://vip.bitcoin.co.id/
[23]: https://quadrigacx.com/
[24]: https://www.binance.com/?ref=11236330
[25]: https://coinfalcon.com/?ref=CFJSQBMXZZDS
[26]: https://github.com/askmike/gekko/pull/2310
[27]: https://exmo.com
[28]: https://www.therocktrading.com/
@@ -0,0 +1,8 @@
# Supporting the project
Gekko is free and open source software. We don't make any money by publishing it, keeping it up to date or providing support.
If Gekko helped you in any way (financially or otherwise) feel free to donate. If you want to see a specific feature implemented faster, feel free to [send an e-mail](mailto:[email protected]) to discuss.
- Bitcoin tip jar: 13r1jyivitShUiv9FJvjLH7Nh1ZZptumwW
- Ethereum tip jar: 0x46e9249ADc30F5bfc6632e1d0b4286496d071Be7
+199
View File
@@ -0,0 +1,199 @@
# Creating a strategy
*Have you made your own strategy? Gekko Plus is hosting an official Strategy contest: submit your strategy and have a change to win 0.1 BTC! Read more details on [Gekko Plus](https://app.gekkoplus.com/contest).*
Strategies are the core of Gekko's trading bot. They look at the market and decide what to do based on technical analysis indicators. A single strategy is limited to a single market on a single exchange.
Gekko currently comes with [a couple of strategies](./introduction.md) out of the box. Besides those you can also write your own strategy in javascript. If you want to understand how to create your own strategy you can watch this video or read the tech docs on this page.
[![youtube video on how to create gekko strategies](https://gekko.wizb.it/_static/create-strat-vid.jpg)](https://www.youtube.com/watch?v=6-74ZhrG0BE)
A strategy is a module with a few functions that get market data in the form of candles ([OHLC](https://en.wikipedia.org/wiki/Open-high-low-close_chart), volume, and the average weighted price) and output trading advice.
## Strategy boilerplate
// Let's create our own strategy
var strat = {};
// Prepare everything our strat needs
strat.init = function() {
// your code!
}
// What happens on every new candle?
strat.update = function(candle) {
// your code!
}
// For debugging purposes.
strat.log = function() {
// your code!
}
// Based on the newly calculated
// information, check if we should
// update or not.
strat.check = function(candle) {
// your code!
}
// Optional for executing code
// after completion of a backtest.
// This block will not execute in
// live use as a live gekko is
// never ending.
strat.end = function() {
// your code!
}
module.exports = strat;
# Strategy lifecycle methods
The above boilerplate contains four functions. These functions are executed by Gekko like so:
- When Gekko starts: run init.
- On each new candle:
- run [update](#update-function)
- once the strategy has completed warmup:
- run [log](#log-function)
- run [check](#check-function)
### init function
Executed when the trading strategy starts. Your strategy can initialize state and [register indicators](#Indicators).
### update function
This function executes on every new candle. You can access the latest candle as the first (and only) parameter (it's also stored in `this.candle`).
### log function
The log function is executed on every new candle when the `debug` flag is on (always off when running in the UI, as configured in [the config](../commandline/about_the_commandline.md) for CLI gekkos). Logging is used to log certain state from the strategy and can be used to debug your strategy to get more insights in why it took certain decisions.
### check function
Most strategies need to warmup before the trading strategy can be started. For example the strategy may be calculating a moving average for the first 3 candles, as such it must have at least 3 candles to output a number the strategy logic relies on. The check function is executed after the warmup period is over. The default required history is 0. You can set it like so in your init function:
this.requiredHistory = 5; // require 5 candles before giving advice
If you find out in the check function that you want to give new advice to the trader you can use the advice function:
this.advice({
direction: 'long', // or short
trigger: { // ignored when direction is not "long"
type: 'trailingStop',
trailPercentage: 5
// or:
// trailValue: 100
}
});
The trigger is optional, if the direction is long and the trigger is specified as a trailingStop this will request the trader to create a trail stop trigger.
### candle variable
The following list of candle variables will be available when writing strategies, they are part of the candle object which is given to your `update` and `check` functions (it's also accessable through `this.candle`).
- candle.close: the closing price of the candle
- candle.high: the highest price of the candle
- candle.low: the lowest price of the candle
- candle.volume: the trading volume of that candle
- candle.trades: number of trades in that candle
## Things to keep in mind
- You can activate your own strategy by setting `config.tradingAdvisor.strategy` to `custom` (or whatever you named your file inside the `gekko/strategies`) in the loaded config.
- Gekko will execute the `update` function for every new candle. A candle is the size in minutes configured at `config.tradingAdvisor.candleSize` in the loaded config.
- It is advised to set history `config.tradingAdvisor.historySize` the same as the requiredHistory as Gekko will use this property to create an initial batch of candles.
- Never rely on anything based on system time because each method can run on live markets as well as during backtesting. You can look at the `candle.start` property which is a `moment` object of the time the candles started.
## Strategy tools
To help you Gekko has a number of strategy tools.
### Indicators
Gekko supports a few indicators natively, in addition to the integration of indicators from the library [TA-lib](http://ta-lib.org/).
#### Example usage
If you want to use an indicator you can add it in the `init` function and Gekko will handle the updating for you on every candle (before the update and before the check call):
// add a native indicator
this.addIndicator('name', 'type', parameters);
or
// add a TA-lib indicator
this.addTalibIndicator('name', 'type', parameters);
or
// add a Tulip indicator
this.addTulipIndicator('name', 'type', parameters);
The first parameter is the name, the second is the indicator type you want and the third is an object with all indicator parameters. If you want an MACD indicator you can do it like so:
In your init function:
// add a native indicator
var parameters = {short: 10, long: 20, signal: 9};
this.addIndicator('mynativemacd', 'MACD', parameters);
// add a TA-lib indicator
var parameters = {optInFastPeriod: 10, optInSlowPeriod: 21, optInSignalPeriod: 9};
this.addTalibIndicator('mytalibmacd', 'macd', parameters);
// add a Tulip indicator
var parameters = {optInFastPeriod: 10, optInSlowPeriod: 21, optInSignalPeriod: 9};
this.addTulipIndicator('mytulipmacd', 'macd', parameters);
In your check or update function:
var result = this.indicators.mytalibmacd.result;
See the [TA-lib indicators](./talib_indicators.md) document for a list of all supported TA-lib indicators and their required parameters.
See the [Tulip indicators](./tulip_indicators.md) document for a list of all supported Tulip indicators and their required parameters.
### Strategy parameters
Adjust strategy execution by creating custom strategy parameters. This way the same strategy can execute strategies concurrently using different parameters for different markets. For example the MACD strategy has parameters concerning the underlying MACD indicator (such as values for the LONG and SHORT EMAs). Create custom configuration settings in the `config/strategies` directory:
// custom settings:
config.custom = {
my_custom_setting: 10,
};
Retrieve them in your strategy like this:
// anywhere in your code:
log.debug(this.settings.my_custom_setting); // Logs 10
___Note that the name of your configuration must be the same as the name of the strategy___
### External libraries
Gekko uses a few general purpose libraries internally. The API from those libraries are available to you as well. Most notable libraries are [lodash](http://lodash.com/) (similar as underscore) and [async](https://github.com/caolan/async).
You can load them like so:
// before any other code
var _ = require('lodash');
var async = require('async');
### Logging
Gekko has a small logger you can use (preferably in your log function):
// before any other code
var log = require('../core/log.js');
// in your log function
log.debug('hello world');
-----
Take a look at the existing methods, if you have questions feel free to create an issue. If you created your own awesome strategies and want to share it with the world feel free to contribute it to gekko.
+122
View File
@@ -0,0 +1,122 @@
# Gekko indicators
When [creating your own strategy](./creating_a_strategy.md) there are a few built in indicators you can use that ship with Gekko.
## Example
If you want to use the MACD indicator from Gekko, you need to register it in your strategy like so:
method.init = function() {
var settings = {
short: 10,
long: 21,
signal: 9
};
// add the indicator to the strategy
this.addIndicator('mymacd', 'MACD', settings);
}
method.check = function() {
// use indicator results
var macdiff = this.indicators.mymacd.result;
// do something with macdiff
}
## Indicators
Here is a list of all supported indicators, click on them to read more about what they are and how to implement them in Gekko:
- [EMA](#EMA)
- [PPO](#PPO)
- [CCI](#CCI)
- [DEMA](#DEMA)
- [LRC](#LRC)
- [MACD](#MACD)
- [RSI](#RSI)
- [SMA](#SMA)
- [TSI](#TSI)
- [UO](#UO)
### EMA
> **What is an 'Exponential Moving Average - EMA'**
> "An exponential moving average (EMA) is a type of moving average that is similar to a simple moving average, except that more weight is given to the latest data. It's also known as the exponentially weighted moving average. This type of moving average reacts faster to recent price changes than a simple moving average."
*[More info on investopedia](http://www.investopedia.com/terms/e/ema.asp).*
You can implement the EMA like so:
method.init = function() {
var weight = 10;
// add the indicator to the strategy
this.addIndicator('myema', 'EMA', weight);
}
method.check = function() {
// use indicator results
var ema = this.indicators.myema.result;
// do something with macdiff
}
### PPO
> **What is the 'Percentage Price Oscillator - PPO'**
> "The percentage price oscillator (PPO) is a technical momentum indicator showing the relationship between two moving averages."
*[More info on investopedia](https://www.investopedia.com/terms/p/ppo.asp).*
### CCI
> **What is the 'Commodity Channel Index - CCI'**
> "The Commodity Channel Index​ (CCI) is a momentum based technical trading tool used most often to help determine when an investment vehicle is reaching a condition of being overbought or oversold."
*[More info on investopedia](https://www.investopedia.com/terms/c/commoditychannelindex.asp).*
### DEMA
> **What is the 'Double Exponential Moving Average - DEMA'**
> "The DEMA is a fast-acting moving average that is more responsive to market changes than a traditional moving average. It was developed in an attempt to create a calculation that eliminated some of the lag associated with traditional moving averages."
*[More info on investopedia](https://www.investopedia.com/terms/d/double-exponential-moving-average.asp).*
### LRC
> **What is the 'Linear Regression Channel - LRC'**
> "This indicator plots a line that best fits the prices specified over a user-defined time period. The Linear Regression Curve is used mainly to identify trend direction and is sometimes used to generate buy and sell signals."
*[More info on Interactive Brokers](https://www.interactivebrokers.co.uk/en/software/tws/usersguidebook/technicalanalytics/linearregressioncurve.htm).*
### MACD
> **What is the 'Moving Average Convergence Divergence - MACD'**
> "Moving average convergence divergence (MACD) is a trend-following momentum indicator that shows the relationship between two moving averages of prices."
*[More info on investopedia](https://www.investopedia.com/terms/m/macd.asp).*
### RSI
> **What is the 'Relative Strength Index - RSI'**
> "Compares the magnitude of recent gains and losses over a specified time period to measure speed and change of price movements of a security. It is primarily used to attempt to identify overbought or oversold conditions in the trading of an asset."
*[More info on investopedia](https://www.investopedia.com/terms/r/rsi.asp).*
### SMA
> **What is the 'Simple Moving Average - SMA'**
> "A simple moving average (SMA) is an arithmetic moving average calculated by adding the closing price of the security for a number of time periods and then dividing this total by the number of time periods."
*[More info on investopedia](https://www.investopedia.com/terms/s/sma.asp).*
### TSI
> **What is the 'True Strength Index - TSI'**
> "A technical momentum indicator that helps traders determine overbought and oversold conditions of a security by incorporating the short-term purchasing momentum of the market with the lagging benefits of moving averages."
*[More info on investopedia](https://www.investopedia.com/terms/t/tsi.asp).*
### UO
> **What is the 'Ultimate Oscillator - UO'**
> "A technical indicator that uses the weighted average of three different time periods to reduce the volatility and false transaction signals that are associated with many other indicators that mainly rely on a single time period"
*[More info on investopedia](https://www.investopedia.com/terms/u/ultimateoscillator.asp).*
+193
View File
@@ -0,0 +1,193 @@
# Gekko Strategies
Gekko uses [technical analysis indicators](http://www.investopedia.com/articles/active-trading/102914/technical-analysis-strategies-beginners.asp) inside **strategies**.
This investment advice is going to be either **long** or **short**. Long indicates that Gekko the asset should be bought and short indicates that it should be sold.
If you are familiar with javascript you can easily create your own strategies. Here is a video explaining everything you need to know:
[![youtube video on how to create gekko strategies](https://gekko.wizb.it/_static/create-strat-vid.jpg)](https://www.youtube.com/watch?v=6-74ZhrG0BE)
Below you can find simple and exemplary strategies that come with Gekko. These strategies come with Gekko and serve as examples.
Gekko currently comes with the following example strategies:
- [DEMA](#DEMA)
- [MACD](#MACD)
- [PPO](#PPO)
- [RSI](#RSI)
- [StochRSI](#StochRSI)
- [CCI](#CCI)
- [talib-macd](#talib-macd)
- [tulip-macd](#tulip-macd)
### DEMA
This strategy uses `Exponential Moving Average crossovers` to determine the current trend the
market is in. Using this information it will suggest to ride the trend. Note that this is
not MACD because it just checks whether the longEMA and shortEMA are [threshold]% removed
from each other.
This strategy is fairly popular in bitcoin trading due to Bitcointalk user Goomboo. Read more about this strategy in [his topic](https://bitcointalk.org/index.php?topic=60501.0) or [here](http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:moving_averages).
You can configure the following parameters:
# EMA weight (α)
# the higher the weight, the more smooth (and delayed) the line
short = 10
long = 21
[thresholds]
down = -0.025
up = 0.025
- short is the short EMA that moves closer to the real market (including noise)
- long is the long EMA that lags behind the market more but is also more resistant to noise.
- the down threshold and the up threshold tell Gekko how big the difference in the lines needs to be for it to be considered a trend. If you set these to 0 each line cross would trigger new advice.
### MACD
The MACD is one of the most popular trend watching **indicators** in finance, it was created by Gerald Appel in the late 1970s. By using multiple price averages (EMAs) of different periods (one that follows the market more closely and one that lags behind, only catching bigger price swings). The indicator itself ouputs multiple numbers, when comparing them they can be interepted as signals that show when the trend of the price is changing.
The MACD **strategy** in Gekko is a simple strategy that implements the indicator. By comparing the difference between the EMAs from the signal the strategy triggers buy and sell signals. The strategy does come with additional logic:
- **thresholds**: a signal will be triggered as soon as the difference goes above or below a configurable threshold, making the strategy more flexible than simply checking if the difference is above or below zero. If you set these to 0 each line cross would trigger new advice.
- **persistance**: instead of trading as soon the difference is above or below the threshold, the strategy will wait a few candles to see if the difference keeps persisting. Only if it does the strategy will actually signal to Gekko to buy or sell. By setting persistance to 0 this behaviour is disabled.
- **short** is the short EMA that moves closer to the real market (including noise)
- **long** is the long EMA that lags behind the market more but is also more resistant to noise.
- **signal** is the EMA weight calculated over the difference from short/long.
Read more about it [here](http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:moving_average_convergence_divergence_macd).
You can configure the following parameters:
# EMA weight (α)
# the higher the weight, the more smooth (and delayed) the line
short = 10
long = 21
signal = 9
# the difference between the EMAs (to act as triggers)
[thresholds]
down = -0.025
up = 0.025
# How many candle intervals should a trend persist
# before we consider it real?
persistence = 1
### PPO
Very similar to MACD but also a little different, read more [here](http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:price_oscillators_ppo).
You can configure the following parameters:
# EMA weight (α)
# the higher the weight, the more smooth (and delayed) the line
short = 12
long = 26
signal = 9
# the difference between the EMAs (to act as triggers)
[thresholds]
down = -0.025
up = 0.025
# How many candle intervals should a trend persist
# before we consider it real?
persistence = 2
- short is the short EMA that moves closer to the real market (including noise)
- long is the long EMA that lags behind the market more but is also more resistant to noise.
- signal is the EMA weight calculated over the difference from short/long.
- the down threshold and the up threshold tell Gekko how big the difference in the lines needs to be for it to be considered a trend. If you set these to 0 each line cross would trigger new advice.
- persistence tells Gekko how long the thresholds needs to be met until Gekko considers the trend to be valid.
### RSI
The RSI indicator is and old but ever popular trend watching **indicator**, introduced in 1978 by J. Welles Wilder this simple indicator has never stopped to be a popular tool for traders. In its essence RSI follows a simple formula to measure the speed by which the price is changing. When the price keeps going up at an accelarating rate the market might be overbought and a reversal might come next.
The RSI **strategy** in Gekko is a simple strategy that implements the RSI indicator. By calculating the RSI as the market develops this strategy can trigger buy or sell signals based on the RSI going too high (overbought) or too low (oversold). The strategy does come with additional logic:
- **interval** is the amount of periods the RSI should use.
- **thresholds** determine what level of RSI would trigger an up or downtrend.
- **persistance**: instead of trading as soon the difference is above or below the threshold, the strategy will wait a few candles to see if the difference keeps persisting. Only if it does the strategy will actually signal to Gekko to buy or sell. By setting persistance to 0 this behaviour is disabled.
Read more about it [here](http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:relative_strength_index_rsi).
You can configure the following parameters:
interval = 14
[thresholds]
low = 30
high = 70
# How many candle intervals should a trend persist
# before we consider it real?
persistence = 2
### StochRSI
The StochRSI indicator uses an RSI indicator at its core and as such is similar to the RSI strategy that uses this indicator. The difference is that after the RSI is calculated a stochastic oscillator is calculated over the resulting RSI values. When a market is trending upwards for a long time the RSI values tend to go and stay high. The stochastic oscillator will compare the RSI values from the last period with eachother. This results in the StochRSI indicator therefor indicate how high or low the RSI values have been historically over the last n periods.
The StochRSI **strategy** in Gekko is a simple strategy that implements the StochRSI indicator. By calculating the StochRSI as the market develops this strategy can trigger buy or sell signals based on the signal going too high (overbought) or too low (oversold). The strategy does come with configurables:
- **interval**: This setting defines both the RSI interval used to calculate the RSI values as well as the historical period used by the stochastic oscillator to compare RSI values with.
- **persistance**: instead of trading as soon the difference is above or below the threshold, the strategy will wait a few candles to see if the difference keeps persisting. Only if it does the strategy will actually signal to Gekko to buy or sell. By setting persistance to 0 this behaviour is disabled.
- **thresholds**: The high and low thresholds are defined as numbers between 1 and 100. Different from StochRSI in other trading systems, this number indicates a percentage instead of a fraction of 1.
You can configure the following parameters:
interval = 3
[thresholds]
low = 20
high = 80
persistence = 3
### CCI
You can configure the following parameters:
# constant multiplier. 0.015 gets to around 70% fit
constant = 0.015
# history size, make same or smaller than history
history = 90
[thresholds]
up = 100
down = -100
persistence = 0
[TODO!]
### talib-macd
Similar to the default MACD strategy, this showcases how to add a TA-lib indicator to a strategy.
You can configure the following parameters:
[parameters]
optInFastPeriod = 10
optInSlowPeriod = 21
optInSignalPeriod = 9
[thresholds]
down = -0.025
up = 0.025
### tulip-macd
Similar to the default MACD strategy, this showcases how to add a Tulip indicator to a strategy.
You can configure the following parameters:
[parameters]
optInFastPeriod = 10
optInSlowPeriod = 21
optInSignalPeriod = 9
[thresholds]
down = -0.025
up = 0.025
[TODO!]
+609
View File
@@ -0,0 +1,609 @@
# TA-lib indicators
When writing [your own strategy](./creating_a_strategy.md) you can use all indicators offered by [the TA-lib library](http://ta-lib.org/function.html). Gekko will pass the correct market data to TA-lib and you only have to provide the `optIn` configurable parameters.
## Install
### Bash on Windows, OSX or Linux
Open your terminal. Then:
```
cd ~/gekko
npm install talib --no-save
```
## Example
If you want to use the MACD indicator from TA-lib, you need to register it in your strategy like so:
method.init = function() {
var customMACDSettings = {
optInFastPeriod: 10,
optInSlowPeriod: 21,
optInSignalPeriod: 9
}
// add the indicator to the strategy
this.addTalibIndicator('mymacd', 'macd', customMACDSettings);
}
method.check = function() {
// use indicator results
var result = this.talibIndicators.mymacd.result;
var macddiff = result['outMACD'] - result['outMACDSignal'];
// do something with macdiff
}
## TA-lib Indicators
Here is a list of all supported indicators, click on them to see the required parameters.
- [ACCBANDS](#accbands)
- [AD](#ad)
- [ADOSC](#adosc)
- [ADX](#adx)
- [ADXR](#adxr)
- [APO](#apo)
- [AROON](#aroon)
- [AROONOSC](#aroonosc)
- [ATR](#atr)
- [AVGPRICE](#avgprice)
- [BBANDS](#bbands)
- [BOP](#bop)
- [CCI](#cci)
- [CMO](#cmo)
- [DEMA](#dema)
- [DX](#dx)
- [EMA](#ema)
- [HT_DCPERIOD](#ht_dcperiod)
- [HT_DCPHASE](#ht_dcphase)
- [HT_PHASOR](#ht_phasor)
- [HT_SINE](#ht_sine)
- [HT_TRENDLINE](#ht_trendline)
- [HT_TRENDMODE](#ht_trendmode)
- [IMI](#imi)
- [KAMA](#kama)
- [LINEARREG](#linearreg)
- [LINEARREG_ANGLE](#linearreg_angle)
- [LINEARREG_INTERCEPT](#linearreg_intercept)
- [LINEARREG_SLOPE](#linearreg_slope)
- [MA](#ma)
- [MACD](#macd)
- [MACDEXT](#macdext)
- [MACDFIX](#macdfix)
- [MAMA](#mama)
- [MAVP](#mavp)
- [MAX](#max)
- [MAXINDEX](#maxindex)
- [MEDPRICE](#medprice)
- [MFI](#mfi)
- [MIDPOINT](#midpoint)
- [MIDPRICE](#midprice)
- [MIN](#min)
- [MININDEX](#minindex)
- [MINMAX](#minmax)
- [MINMAXINDEX](#minmaxindex)
- [MINUS_DI](#minus_di)
- [MINUS_DM](#minus_dm)
- [MOM](#mom)
- [NATR](#natr)
- [OBV](#obv)
- [PLUS_DI](#plus_di)
- [PLUS_DM](#plus_dm)
- [PPO](#ppo)
- [ROC](#roc)
- [ROCP](#rocp)
- [ROCR](#rocr)
- [ROCR100](#rocr100)
- [RSI](#rsi)
- [SAR](#sar)
- [SAREXT](#sarext)
- [SMA](#sma)
- [STDDEV](#stddev)
- [STOCH](#stoch)
- [STOCHF](#stochf)
- [STOCHRSI](#stochrsi)
- [T3](#t3)
- [TEMA](#tema)
- [TRANGE](#trange)
- [TRIMA](#trima)
- [TRIX](#trix)
- [TSF](#tsf)
- [TYPPRICE](#typprice)
- [ULTOSC](#ultosc)
- [VARIANCE](#variance)
- [WCLPRICE](#wclprice)
- [WILLR](#willr)
- [WMA](#wma)
## API
### accbands
Required parameters:
- optInTimePeriod
### ad
Required parameters:
- optInTimePeriod
### adosc
Required parameters:
- optInFastPeriod
- optInSlowPeriod
### adx
Required parameters:
- optInTimePeriod
### adxr
Required parameters:
- optInTimePeriod
### apo
Required parameters:
- optInFastPeriod
- optInSlowPeriod
- optInMAType
### aroon
Required parameters:
- optInTimePeriod
### aroonosc
Required parameters:
- optInTimePeriod
### atr
Required parameters:
- optInTimePeriod
### avgprice
Required parameters:
- optInTimePeriod
### bbands
Required parameters:
- optInTimePeriod
- optInNbDevUp
- optInNbDevDn
- optInMAType
### bop
This indicator does not require any parameters.
### cci
Required parameters:
- optInTimePeriod
### cmo
Required parameters:
- optInTimePeriod
### dema
Required parameters:
- optInTimePeriod
### dx
Required parameters:
- optInTimePeriod
### ema
Required parameters:
- optInTimePeriod
### ht_dcperiod
This indicator does not require any parameters.
### ht_dcphase
This indicator does not require any parameters.
### ht_phasor
This indicator does not require any parameters.
### ht_sine
This indicator does not require any parameters.
### ht_trendline
This indicator does not require any parameters.
### ht_trendmode
This indicator does not require any parameters.
### imi
Required parameters:
- optInTimePeriod
### kama
Required parameters:
- optInTimePeriod
### linearreg
Required parameters:
- optInTimePeriod
### linearreg_angle
Required parameters:
- optInTimePeriod
### linearreg_intercept
Required parameters:
- optInTimePeriod
### linearreg_slope
Required parameters:
- optInTimePeriod
### ma
Required parameters:
- optInTimePeriod
- optInMAType
### macd
Required parameters:
- optInFastPeriod
- optInSlowPeriod
- optInSignalPeriod
### macdext
Required parameters:
- optInFastPeriod
- optInFastMAType
- optInSlowPeriod
- optInSlowMAType
- optInSignalPeriod
- optInSignalMAType
### macdfix
Required parameters:
- SignalPeriod
### mama
Required parameters:
- optInFastLimit
- optInSlowLimit
### mavp
Required parameters:
- inPeriods
- optInMinPeriod
- optInMaxPeriod
- optInMAType
### max
Required parameters:
- optInTimePeriod
### maxindex
Required parameters:
- optInTimePeriod
### medprice
Required parameters:
- optInTimePeriod
### mfi
Required parameters:
- optInTimePeriod
### midpoint
Required parameters:
- optInTimePeriod
### midprice
Required parameters:
- optInTimePeriod
### min
Required parameters:
- optInTimePeriod
### minindex
Required parameters:
- optInTimePeriod
### minmax
Required parameters:
- optInTimePeriod
### minmaxindex
Required parameters:
- optInTimePeriod
### minus_di
Required parameters:
- optInTimePeriod
### minus_dm
Required parameters:
- optInTimePeriod
### mom
Required parameters:
- optInTimePeriod
### natr
Required parameters:
- optInTimePeriod
### obv
This indicator does not require any parameters.
### plus_di
Required parameters:
- optInTimePeriod
### plus_dm
Required parameters:
- optInTimePeriod
### ppo
Required parameters:
- optInFastPeriod
- optInSlowPeriod
- optInMAType
### roc
Required parameters:
- optInTimePeriod
### rocp
Required parameters:
- optInTimePeriod
### rocr
Required parameters:
- optInTimePeriod
### rocr100
Required parameters:
- optInTimePeriod
### rsi
Required parameters:
- optInTimePeriod
### sar
Required parameters:
- optInAcceleration
- optInMaximum
### sarext
Required parameters:
- optInStartValue
- optInOffsetOnReverse
- optInAccelerationInitLong
- optInAccelerationLong
- optInAccelerationMaxLong
- optInAccelerationInitShort
- optInAccelerationShort
- optInAccelerationMaxShort
### sma
Required parameters:
- optInTimePeriod
### stddev
Required parameters:
- optInTimePeriod
- optInNbDev
### stoch
Required parameters:
- optInFastK_Period
- optInSlowK_Period
- optInSlowK_MAType
- optInSlowD_Period
- optInSlowD_MAType
### stochf
Required parameters:
- optInFastK_Period
- optInFastD_Period
- optInFastD_MAType
### stochrsi
Required parameters:
- optInTimePeriod
- optInFastK_Period
- optInFastD_Period
- optInFastD_MAType
### t3
Required parameters:
- optInTimePeriod
- optInFastK_Period
- optInFastD_Period
- optInFastD_MAType
### tema
Required parameters:
- optInTimePeriod
### trange
Required parameters:
- optInTimePeriod
### trima
Required parameters:
- optInTimePeriod
### trix
Required parameters:
- optInTimePeriod
### tsf
Required parameters:
- optInTimePeriod
### typprice
Required parameters:
- optInTimePeriod
### ultosc
Required parameters:
- optInTimePeriod
### variance
Required parameters:
- optInTimePeriod
- optInNbDev
### wclprice
Required parameters:
- optInTimePeriod
### willr
Required parameters:
- optInTimePeriod
### wma
Required parameters:
- optInTimePeriod
+709
View File
@@ -0,0 +1,709 @@
# Tulip indicators
When writing [your own strategy](./creating_a_trading_method.md) you can use all indicators offered by [the Tulip Indicators library](https://tulipindicators.org/). Gekko will pass the correct market data to Tulip and you only have to provide the `optIn` configurable parameters.
## Install
### Bash on Windows, OSX or Linux
Open your terminal. Then:
```
cd ~/gekko
npm install tulind --no-save
```
## Example
If you want to use the MACD indicator from Tulip, you need to register it in your strategy like so:
method.init = function() {
var customMACDSettings = {
optInFastPeriod: 10,
optInSlowPeriod: 21,
optInSignalPeriod: 9
}
// add the indicator to the strategy
this.addTulipIndicator('mymacd', 'macd', customMACDSettings);
}
method.check = function() {
// use indicator results
var result = this.tulipIndicators.mymacd.result;
var macddiff = result['macd'] - result['macdSignal'];
// do something with macdiff
}
## Tulip Indicators
Here is a list of all supported indicators, click on them to see the required parameters.
- [AD](#ad)
- [ADOSC](#adosc)
- [ADX](#adx)
- [ADXR](#adxr)
- [AO](#ao)
- [APO](#apo)
- [AROON](#aroon)
- [AROONOSC](#aroonosc)
- [ATR](#atr)
- [AVGPRICE](#avgprice)
- [BBANDS](#bbands)
- [BOP](#bop)
- [CCI](#cci)
- [CMO](#cmo)
- [CVI](#cvi)
- [DEMA](#dema)
- [DI](#di)
- [DM](#dm)
- [DPO](#dpo)
- [DX](#dx)
- [EMA](#ema)
- [EMV](#emv)
- [FISHER](#fisher)
- [FOSC](#fosc)
- [HMA](#hma)
- [KAMA](#kama)
- [KVO](#kvo)
- [LINREG](#linreg)
- [LINREGINTERCEPT](#linregintercept)
- [LINREGSLOPE](#linregslope)
- [MARKETFI](#marketfi)
- [MASS](#mass)
- [MEDPRICE](#medprice)
- [MFI](#mfi)
- [MSW](#msw)
- [NATR](#natr)
- [NVI](#nvi)
- [OBV](#obv)
- [PPO](#ppo)
- [PSAR](#psar)
- [PVI](#pvi)
- [QSTICK](#qstick)
- [ROC](#roc)
- [ROCR](#rocr)
- [RSI](#rsi)
- [SMA](#sma)
- [STOCH](#stoch)
- [SUM](#sum)
- [TEMA](#tema)
- [TR](#tr)
- [TRIMA](#trima)
- [TRIX](#trix)
- [TSF](#tsf)
- [TYPPRICE](#typprice)
- [ULTOSC](#ultosc)
- [VHF](#vhf)
- [VIDYA](#vidya)
- [VOLATILITY](#volatility)
- [VOSC](#vosc)
- [VWMA](#vwma)
- [WAD](#wad)
- [WCPRICE](#wcprice)
- [WILDERS](#wilders)
- [WILLR](#willr)
- [WMA](#wma)
- [ZLEMA](#zlema)
## API
### ad
This indicator does not require any parameters.
### adosc
Required parameters:
- optInFastPeriod
- optInSlowPeriod
### adx
More information on the [**Average Directonal Movement Index**](https://en.wikipedia.org/wiki/Average_directional_movement_index)
Required parameters:
- optInTimePeriod
### adxr
The **Average Directional Movement Index Rating** is used as a risk indicator for a security in an [adx](#adx) system. It evaluates the risk (volatility) of a security by smoothing the amplitude readings of the trend function of the adx. It is calculated as follows
ADX plus the ADX (n-time periods ago) divided by 2
Higher readings conform to lower risk and lower readings conform to higher risk.
A investor wanting to lower the portfolio risk will therefore use securities with higher adxr ratings.
Required parameters:
- optInTimePeriod
### ao
More information about the [**Awesome Oscillator**](https://www.tradingview.com/wiki/Awesome_Oscillator_(AO))
This indicator does not require any parameters.
### apo
The **Absolute Price Oscillator** displays the difference between two exponential moving averages of a security's price and is expressed as an absolute value. It rates the trends strength in relation to the moving between the two moving averages with short-term momentum being the catalyst.
Required parameters:
- optInFastPeriod
- optInSlowPeriod
### aroon
More information about the [Aroon](https://www.tradingview.com/wiki/Aroon) Indicator.
Required parameters:
- optInTimePeriod
### aroonosc
The Aroon Oscillator belongs to the group of trend-following indicators and uses parts of the Aroon Indicator (namely "Aroon Up" and "Aroon Down") to indicate the strength of a current trend and the likelihood that it will continue. The Aroon Oscillator is calculated by subtracting Aroon Up from Aroon Down. Readings above zero indicate that an uptrend is present, while readings below zero indicate that a downtrend is present.
Required parameters:
- optInTimePeriod
### atr
More information about the [Average True Range](https://www.tradingview.com/wiki/Average_True_Range_(ATR))
Required parameters:
- optInTimePeriod
### avgprice
The average price indicator calculates the mean of the open, high, low, and close of a bar
open + high + low + close / 4
This indicator does not require any parameters.
### bbands
More information about [Bollinger Bands](https://www.tradingview.com/wiki/Bollinger_Bands_(BB))
Required parameters:
- optInTimePeriod
- optInNbStdDevs
### bop
The Balance of Power indicator measures the market strength of buyers against sellers by assessing the ability of each side to drive prices to an extreme level. The calculation is:
Balance of Power = (Close price – Open price) / (High price – Low price)
The resulting value can be smoothed by a moving average.
This indicator does not require any parameters.
### cci
More information about the [Commodity Channel Index](https://www.tradingview.com/wiki/Commodity_Channel_Index_(CCI))
Required parameters:
- optInTimePeriod
### cmo
The Chande Momentum Oscillator is a technical momentum indicator. The indicator is created by calculating the difference between the sum of all recent higher closes and the sum of all recent lower closes and then dividing the result by the sum of all price movement over a given time period. The result is multiplied by 100 to give the -100 to +100 range. The defined time period is usually 20 periods.
CMO = 100 * ((Sh - Sd)/ ( Sh + Sd ) )
Where:
Sh = Sum of the difference between the current close and previous close on up days for the specified period. Up days are days when the current close is greater than the previous close.
Sd = Sum of the absolute value of the difference between the current close and the previous close on down days for the specified period. Down days are days when the current close is less than the previous close.
Required parameters:
- optInTimePeriod
### cvi
More information about the [Chaikin Volatility Index](https://www.tradingview.com/wiki/Chaikin_Oscillator) also called the Chaikin Oscillator.
Required parameters:
- optInTimePeriod
### dema
More information about the [DEMA](https://en.wikipedia.org/wiki/Double_exponential_moving_average)
Required parameters:
- optInTimePeriod
### di
More information about the [Directional Indicator](https://en.wikipedia.org/wiki/Average_directional_movement_index)
Required parameters:
- optInTimePeriod
### dm
More information about the [Directional Movement Index](https://en.wikipedia.org/wiki/Average_directional_movement_index)
Required parameters:
- optInTimePeriod
### dpo
More information about the [Detrended Price Oscillator](https://en.wikipedia.org/wiki/Detrended_price_oscillator)
Required parameters:
- optInTimePeriod
### dx
More information about the [Directional Movement Index](https://en.wikipedia.org/wiki/Average_directional_movement_index)
Required parameters:
- optInTimePeriod
### ema
Exponential Moving Average (EMA) is similar to Simple Moving Average (SMA), measuring trend direction over a period of time. However, whereas SMA simply calculates an average of price data, EMA applies more weight to data that is more current. Because of its unique calculation, EMA will follow prices more closely than a corresponding SMA.
EMA = (K x (C - P)) + P
Where:
- C = Current Price
- P = Previous periods EMA (A SMA is used for the first periods calculations)
- K = Exponential smoothing constant
Required parameters:
- optInTimePeriod
### emv
More information about the [Ease of Movement](https://www.tradingview.com/wiki/Ease_of_Movement_(EOM))
This indicator does not require any parameters.
### fisher
The Fisher Transform is a technical indicator that converts prices into a Gaussian normal distribution. The indicator enables traders to create a nearly Gaussian probability density function by normalizing prices. That is, the transformation makes peak swings relatively rare events and unambiguously identifies price reversals on a chart.
Y = 0.5 * ln ((1+X)/(1-X))
Where:
- "ln" denotes the abbreviated form of the natural logarithm
- "X" denotes the transformation of price to a level between -1 and 1 for ease of calculation
Required parameters:
- optInTimePeriod
### fosc
The forecast oscillator attempts to predict price action by comparing the results of a linear regression trendline to the actual price for that day. Positive values of the oscillator occur when the forecast price is above the actual price and negative values when the forecast price is below. If prices are consistently below the forecast, then a downturn in prices is likely. Conversely, if prices are consistently above the forecast then an upturn in prices is likely.
Required parameters:
- optInTimePeriod
### hma
Basic forms of moving averages like the Simple Moving Average lag price. The Exponential and Weighted Moving Averages were developed to address this lag by placing more emphasis on more recent data. The Hull Moving Average in contrast is an extremely fast and smooth moving average, it almost eliminates lag altogether and manages to improve smoothing at the same time.
HMA= WMA(2*WMA(n/2) − WMA(n)),sqrt(n))
Required parameters:
- optInTimePeriod
### kama
The Kaufman adaptive moving average belongs to the group of "intelligent" indicators. It´s concept addresses the fact that noisy markets should have a lagging indicator and trending markets should have a leading indicator. So it adapts itself to lag in sideways markets and lead in trending markets.
KAMA(t) = KAMA(t-1) + sc(t) x (Price-KAMA(t-1))
Where:
- KAMA(t) is the new adaptive moving average value
- KAMA(t-1) is the previous adaptive moving average value
- Price is the current price
- sc(t) is the smoothing constant
Required parameters:
- optInTimePeriod
### kvo
The Klinger Volume Oscillator measures trends of money flows based upon volume. The KO is derived from three types of data: the high-low price range, volume, and accumulation/distribution. Price range is a measure of movement and the force behind that movement is volume. Accumulation is when the sum of today's [high]+[low]+[close] is greater than yesterday's. Distribution is when today's sum is less than the yesterday's. When the sums are equal, the existing trend is maintained.
Required parameters:
- optInFastPeriod
- optInSlowPeriod
### linreg
The Linear Regression is a smoothing functions that works by preforming linear least squares regression over a moving window. It then uses the linear model to predict the value for the current bar.
Required parameters:
- optInTimePeriod
### linregintercept
More information about the [Linear Regression Intercept](https://en.wikipedia.org/wiki/Simple_linear_regression)
Required parameters:
- optInTimePeriod
### linregslope
More information about the [Linear Regression Intercept](https://en.wikipedia.org/wiki/Simple_linear_regression)
Required parameters:
- optInTimePeriod
### macd
More information about the [MACD](https://www.tradingview.com/wiki/MACD_(Moving_Average_Convergence/Divergence))
Required parameters:
- optInFastPeriod
- optInSlowPeriod
- optInSignalPeriod
### marketfi
The Market Facilitation Index indicator combines price and volume in the analysis to establish the effectiveness of price movement by computing the price movement per volume unit. To calculate the Market Facilitation Index indicator the difference between the low and the high price are taken and divided by the volume.
This indicator does not require any parameters.
### mass
The Mass Index indicator is used for finding trend reversals, based on the premise that reversals are likely to happen when the price range widens. It does not have a directional bias. The calculation, which compares the previous trading ranges (highs minus lows), uses Exponential Moving Averages (EMA). If there is substantial movement, the Mass Index Indicator increases if there is insubstantial movement the Mass Index Indicator decreases.
Formula (usually a 9 period EMA is used)
Single EMA = (x)-period exponential moving average (EMA) of the high-low differential
Double EMA = (y)-period EMA of the (x)-period EMA of the high-low differential
EMA Ratio = Single EMA divided by Double EMA
Mass Index = 25-period sum of the EMA Ratio
Required parameters:
- optInTimePeriod
### medprice
The median price indicator calculates the mean of the high and low for a bar. Despite the name, it does not calculate an actual median value.
medprice(t) = (high(t) + low(t)) / 2
This indicator does not require any parameters.
### mfi
More information about the [MFI](https://www.tradingview.com/wiki/Money_Flow_(MFI))
Required parameters:
- optInTimePeriod
### msw
The Maximum Entropy Spectrum Analysis indicator is a unique way to accurately measure short-term cycles in a market. It utilizes two sine plots to illustrate if the market is in a cycle mode or in a trend mode. When the two plots resemble a sine wave the market is in cycling mode. When the plots start to wander the market is in a trend mode.
The MESA Sine Wave indicator is a leading indicator that will anticipate cycle mode turning points rather than waiting for confirmation as is seen with most other oscillators. The indicator has the additional advantage that trend mode whipsaw signals are minimized.
Required parameters:
- optIn
### natr
The Normalized Average True Range is a measure of volatility.
It is calculated as follows:
natr = (atr(t) / close(t)) * 100
Required parameters:
- optInTimePeriod
### nvi
More information about the [NVI](https://en.wikipedia.org/wiki/Negative_volume_index)
This indicator does not require any parameters.
### obv
More information about the [OBV](https://www.tradingview.com/wiki/On_Balance_Volume_(OBV))
This indicator does not require any parameters.
### ppo
More information about the [PPO](https://www.tradingview.com/wiki/Price_Oscillator_(PPO))
Required parameters:
- optInFastPeriod
- optInSlowPeriod
### psar
More information about the [Parabolic SAR](https://www.tradingview.com/wiki/Parabolic_SAR_(SAR))
Required parameters:
- optInAcceleration
- optInMaximum
### pvi
More information about the [PVI](https://en.wikipedia.org/wiki/Negative_volume_index)
This indicator does not require any parameters.
### qstick
The Qstick Indicator identifies trends on a chart. It is calculated by taking an 'n' period moving average of the difference between the open and closing prices. A Qstick value greater than zero means that the majority of the last 'n' days have been up, indicating that buying pressure has been increasing. In summary, the measure provides an approximation for a security’s EMA, opening price, closing price, and their difference, as well as these values SMA.
Required parameters:
- optInTimePeriod
### roc
More information about the [Rate of Change](https://www.tradingview.com/wiki/Rate_of_Change_(ROC))
Required parameters:
- optInTimePeriod
### rocr
Rate Of Change Ratio calculates the change between the current price and the price n bars ago.
Required parameters:
- optInTimePeriod
### rsi
More information about the [RSI](https://www.tradingview.com/wiki/Relative_Strength_Index_(RSI))
Required parameters:
- optInTimePeriod
### sma
More information about the [SMA](https://www.tradingview.com/wiki/Moving_Average)
Required parameters:
- optInTimePeriod
### stoch
More information about the [STOCH](https://www.tradingview.com/wiki/Stochastic_(STOCH))
Required parameters:
- optInFastKPeriod
- optInSlowKPeriod
- optInSlowDPeriod
### sum
The Sum Over Period indicator simply returns the sum of the last n bars.
Required parameters:
- optInTimePeriod
### tema
The Triple Exponential Moving Average is similar to the Exponential Moving Average or the Double Exponential Moving Average, but provides even less lag. Triple Exponential Moving Average is probably best viewed as an extension of Double Exponential Moving Average.
It can be expressed in terms of the Exponential Moving Average as follows:
tema = 3 * ema(in) - 3 * ema(ema(in)) + ema(ema(ema(in)))
Required parameters:
- optInTimePeriod
### tr
True range is a measure of volatility. It represents how much a security changed price on a given day.
True range for each day is the greatest of:
- Day's high minus day's low
- The absolute value of the day's high minus the previous day's close
- The absolute value of the day's low minus the previous day's close
This indicator does not require any parameters.
### trima
The Triangular Moving Average is similar to the Simple Moving Average but instead places more weight on middle portion of the smoothing period and less weight on the newest and oldest bars in the period.
It is calculated for each bar as the weighted arithmetic mean of the previous n bars. For example, the weights w for an n of 4 are: 1, 2, 2, 1. The weights w for a n of 7 are: 1, 2, 3, 4, 3, 2, 1. It's easy to see why it's called the Triangular Moving Average.
Required parameters:
- optInTimePeriod
### trix
More information about the [TRIX](https://www.tradingview.com/wiki/TRIX)
Required parameters:
- optInTimePeriod
### tsf
The Time Series Forecast indicator displays the statistical trend of a security's price over a specified time period. The trend is based on linear regression analysis. Rather than plotting a straight linear regression trendline, the Time Series Forecast plots the last point of multiple linear regression trendlines. The resulting TSF indicator is sometimes referred to as the "moving linear regression" indicator or the "regression oscillator."
Required parameters:
- optInTimePeriod
### typprice
The Typical Price calculates the arithmetic mean of the high, low, and close of a bar.
This indicator does not require any parameters.
### ultosc
More information about the [UO](https://www.tradingview.com/wiki/Ultimate_Oscillator_(UO))
Required parameters:
- optInTimePeriod1
- optInTimePeriod2
- optInTimePeriod3
### vhf
The Vertical Horizontal Filter determines whether prices are in a trending phase or a congestion phase. It is used to dertermine which other indicators are to be used in the current market trend. For example if the VHF suggests the market is in a range then a [mesa] could be used if the VHF suggests the market is in a range then one could use a [psar] to determine entry and exit points.
Required parameters:
- optInTimePeriod
### vidya
The Variable Index Dynamic Average indicator modifies the Exponential Moving Average by varying the smoothness based on recent volatility.
Required parameters:
- optInFastPeriod
- optInSlowPeriod
- optInAlpha
### volatility
The Annualized Historical Volatility indicator calculates the volatility over a moving window.
Required parameters:
- optInTimePeriod
### vosc
The Volume Oscillator identifies trends in volume using two moving averages of volume, one fast and one slow. The fast volume moving average is then subtracted from the slow moving average.
Required parameters:
- optInFastPeriod
- optInSlowPeriod
### vwma
The Volume Weighted Moving Average is simalair to a Simple Moving Average, but it weights each bar by its volume.
Required parameters:
- optInTimePeriod
### wad
Williams AD is a running sum of positive accumulation values (buying pressure) and negative distribution values (selling pressure), as determined by price's location within a given day's true range. The day's accumulation/distribution is then calculated by comparing today's closing price to yesterday's closing price.
To calculate the Williams' Accumulation/Distribution indicator, determine:
True Range High (TRH) = Yesterday's close or today's high whichever is greater
True Range Low (TRL) = Yesterday's close or today's low whichever is less
The Williams' Accumulation/Distribution indicator is a cumulative total of the daily values:
- Williams A/D = Today's A/D + Yesterday's Williams A/D
This indicator does not require any parameters.
### wcprice
The weighted close price indicator calculates the mean of the high, low, and close of a bar, but the close price is weighted to count for double.
This indicator does not require any parameters.
### wilders
The Welles Wilder Smoothing indicator is basically the same as an [EMA](#ema) and can be used in the same manner.
It uses a different calculation but can be easily calculated by simply converting EMA values as follows:
wilders = (ema + 1) / 2
Required parameters:
- optInTimePeriod
### willr
More information about the [Williams R](https://www.tradingview.com/wiki/Williams_%25R_(%25R))
Required parameters:
- optInTimePeriod
### wma
More information about the [WMA](https://en.wikipedia.org/wiki/Moving_average#Simple_moving_average)
Required parameters:
- optInTimePeriod
### zlema
Zero-Lag Exponential Moving Average modifies a Exponential Moving Average to greatly reduce lag.
Required parameters:
- optInTimePeriod