Bitmex orderbooks saving + (neural) trading signal generator + backtesting etc.
The closely related ideas are also exposed in "One Way to Trading over Orderbook Analisys" article on Medium. Read the article for better understanding.
pip install -r requirements.txt
Just run code below with your API-key credentials to BitMEX. On every update of market 100-depth order book is writing to disk. Bid-ask spread is in the middle of order book. New trading day starts with new file.
from BitmexOrderBookSaver import *
api_key = ''
api_secret = ''
save_folder = ''
bitmex = BitmexOrderBookSaver(api_key, api_secret, save_folder)
print('Retrieving orderbooks market data. Press any key to stop')
input()
bitmex.exit()
from OrderBookContainer import *
folder=''
input_files = [f for f in os.listdir(folder) if os.path.isfile(os.path.join(folder, f))]
for in_file in input_files:
obc = OrderBookContainer(os.path.join(folder, in_file))
obc.create_training_dataset()
As a result the script will create Datasets subfolder with *.ds files.
My goal is just to show that neural networks work without price movement analysis but only on current market timestamp (== order book) analysis.
So, network gets only order book volumes as input and generates floating point value as output. Really, there are no prices in input data!
The code below will create three-layered feed-forward sequential network. I use Keras framework.
I use sigmoid activation function for all layers except for last one where softmax is used. The first layer consists of 100 neurons, one for each line in order book. The last layer must contain of 2 neurons because of two variants are possible - BUY and SELL.
import TurexNetwork
nwk = TurexNetwork.TurexNetwork()
nwk.create_model((100, 50, 2))
datasets_folder=''
nwk.train(datasets_folder)
nwk.save_model('full_path_to_file.h5')
You can generate trading signal with possible values of [BUY, SELL, WAIT] with order book analysis only. On every orderbook you get from exchange or read from file signal can be generated with code below. threshold is floating point value in range [0, 1]. The less the value the more signals you get.
from Generators import sample_generator_n
nwk = TurexNetwork.TurexNetwork()
nwk.load_model('model_from_code_above.h5')
signal = sample_generator_n(nwk, orderbook.volumes, threshold)
from Generators import sample_generator
signal = sample_generator(orderbook.volumes, threshold)
The mean of threshold is described above.
import TurexNetwork
import Generators
from OrderBookContainer import *
obc = OrderBookContainer('path_to_file')
nwk = TurexNetwork.TurexNetwork()
nwk.load_model('path_to_file.h5')
threshold = 0.0
trades = obc.backtest_n(Generators.sample_neural_generator, nwk, threshold)
#trades = obc.backtest(Generators.sample_generator, threshold)
for trade in trades:
print(trade)