All Projects → khramkov → Backtrader Mql5 Api

khramkov / Backtrader Mql5 Api

Licence: gpl-3.0
Python Backtrader - Metaquotes MQL5 - API

Programming Languages

python
139335 projects - #7 most used programming language

Projects that are alternatives of or similar to Backtrader Mql5 Api

Bxbot
A simple Bitcoin trading bot written in Java.
Stars: ✭ 515 (+390.48%)
Mutual labels:  trading-api, trading
Kupi Terminal
Ccxt based, open source, customized, extendable trading platform that supports 130+ crypto exchanges.
Stars: ✭ 104 (-0.95%)
Mutual labels:  trading-api, trading
Python Poloniex
Poloniex API wrapper for Python 2.7 & 3
Stars: ✭ 557 (+430.48%)
Mutual labels:  trading-api, trading
open-trading-platform-API
The Open Trading Platform API is an independent module for managing API requests from the UI module
Stars: ✭ 17 (-83.81%)
Mutual labels:  trading, trading-api
Akka Trading
Scala Backtesting + Oanda REST API Trading Framework built on top of Akka/Spray
Stars: ✭ 40 (-61.9%)
Mutual labels:  trading-api, trading
Order-Book-Matching-Engine
Order Book Matching Engine for Stock Exchanges (1us latency for matching)
Stars: ✭ 112 (+6.67%)
Mutual labels:  trading, trading-api
Python Bittrex
Python bindings for bittrex
Stars: ✭ 601 (+472.38%)
Mutual labels:  trading-api, trading
EA31337-classes
📦📈 EA31337 framework (MQL library for writing trading Expert Advisors, indicators and scripts)
Stars: ✭ 103 (-1.9%)
Mutual labels:  trading, trading-api
Robin stocks
This is a library to use with Robinhood Financial App. It currently supports trading crypto-currencies, options, and stocks. In addition, it can be used to get real time ticker information, assess the performance of your portfolio, and can also get tax documents, total dividends paid, and more. More info at
Stars: ✭ 967 (+820.95%)
Mutual labels:  trading-api, trading
Tradinggym
Trading and Backtesting environment for training reinforcement learning agent or simple rule base algo.
Stars: ✭ 813 (+674.29%)
Mutual labels:  trading-api, trading
uniswap-python
🦄 The unofficial Python client for the Uniswap exchange.
Stars: ✭ 533 (+407.62%)
Mutual labels:  trading, trading-api
Poloniex
Poloniex python API client for humans
Stars: ✭ 71 (-32.38%)
Mutual labels:  trading-api, trading
open-trading-platform-UI
The Open Trading Platform UI is a front-end module for trading across 5 crypto currency exchanges allowing both spot and margin trading. The UI needs to be used with the API repo.
Stars: ✭ 54 (-48.57%)
Mutual labels:  trading, trading-api
korbit-python
Korbit API wrapper for Python
Stars: ✭ 17 (-83.81%)
Mutual labels:  trading, trading-api
Coinbase.Pro
📈 A .NET/C# implementation of the Coinbase Pro API.
Stars: ✭ 63 (-40%)
Mutual labels:  trading, trading-api
Kelp
Kelp is a free and open-source trading bot for the Stellar DEX and 100+ centralized exchanges
Stars: ✭ 580 (+452.38%)
Mutual labels:  trading-api, trading
ForEx
Using ML to create a ForEx trader to invest my personal finances to get rid of student debt
Stars: ✭ 17 (-83.81%)
Mutual labels:  trading, trading-api
xapi-node
xStation5 Trading API for NodeJS/JS
Stars: ✭ 36 (-65.71%)
Mutual labels:  trading, trading-api
Coinbase Pro Node
DEPRECATED — The official Node.js library for Coinbase Pro
Stars: ✭ 782 (+644.76%)
Mutual labels:  trading-api, trading
Alice blue
Official Python library for Alice Blue API trading
Stars: ✭ 60 (-42.86%)
Mutual labels:  trading-api, trading

Python Backtrader - Metaquotes MQL5 - API

Development state: first stable release.

Working in production on Debian 10.

Table of Contents

About the Project

This is the Backtrader part of the project. MQL5 side of this project is located here: MQL5 - JSON - API

In development:

  • Upload data on reconnect

Installation

  1. pip install backtrader
  2. pip install pyzmq
  3. Check if the ports are free to use. (default:15555,15556, 15557,15558)

Documentation

See MQL5 - JSON - API documentation for better understanding.

You can create market or pending order with the default backtrader command.

self.buy_order = self.buy(size=0.1, price=1.11, exectype=bt.Order.Limit)

If you want to cancel it.

self.cancel(self.buy_order)

When you use bracket orders, one order with stops will be created on the MQL5 side.

self.buy_order = self.buy_bracket(limitprice=1.13, stopprice=1.10, size=0.1, exectype=bt.Order.Market)

If you want to cancel bracket orders, you shold cancel only the first one.

self.cancel(self.buy_order[0])

Usage

Live trading example

import backtrader as bt
from backtradermt5.mt5store import MTraderStore
from datetime import datetime, timedelta


class SmaCross(bt.SignalStrategy):

    def __init__(self):
        self.buy_order = None
        self.live_data = False

    def next(self):
        if self.buy_order is None:
            self.buy_order = self.buy_bracket(limitprice=1.13, stopprice=1.10, size=0.1, exectype=bt.Order.Market)

        if self.live_data:
            cash = self.broker.getcash()

		 # Cancel order
		 if self.buy_order is not None:
			  self.cancel(self.buy_order[0])

        else:
            # Avoid checking the balance during a backfill. Otherwise, it will
            # Slow things down.
            cash = 'NA'

        for data in self.datas:
            print(f'{data.datetime.datetime()} - {data._name} | Cash {cash} | O: {data.open[0]} H: {data.high[0]} L: {data.low[0]} C: {data.close[0]} V:{data.volume[0]}')

    def notify_data(self, data, status, *args, **kwargs):
        dn = data._name
        dt = datetime.now()
        msg = f'Data Status: {data._getstatusname(status)}'
        print(dt, dn, msg)
        if data._getstatusname(status) == 'LIVE':
            self.live_data = True
        else:
            self.live_data = False

cerebro = bt.Cerebro()
cerebro.addstrategy(SmaCross)

store = MTraderStore()

# comment next 2 lines to use backbroker for backtesting with MTraderStore
broker = store.getbroker(use_positions=True)
cerebro.setbroker(broker)

start_date = datetime.now() - timedelta(minutes=500)

data = store.getdata(dataname='EURUSD', timeframe=bt.TimeFrame.Ticks,
                     fromdate=start_date) #, useask=True, historical=True)
                     # the parameter "useask" will request the ask price insetad if the default bid price

cerebro.resampledata(data,
                     timeframe=bt.TimeFrame.Seconds,
                     compression=30
                     )

cerebro.run(stdstats=False)
cerebro.plot(style='candlestick', volume=False)

Download CSV data

You can instruct MT5 to download historical data as a CSV file. Files will be saved into the local Metatrader 5 Terminal installation folder:

[MT5 Terminal]/MQL/Files/Data

The example below downloads data for the past 6 months as tick data.

from datetime import datetime, timedelta
from backtradermql5.mt5store import MTraderStore
import backtrader as bt

store = MTraderStore(host='192.168.1.20') # Metatrader 5 running on a diffenet host

start_date = datetime.now() - timedelta(months=6)

cerebro = bt.Cerebro()
data2 = store.getdata(dataname='EURUSD',
                      timeframe=bt.TimeFrame.Ticks,
                      fromdate=start_date
                      )

cerebro.run(stdstats=False)

Using MT5 Indicators and plotting to MT5 charts

MT5 Indicators

You can use any MT5 indicator directly from Backtrader via the MTraderIndicator class.

    def __init__(self, store):
        self.mt5macd = getMTraderIndicator(
            # MTraderStorestore instance
            store,
            # Data feed to run the indicator calculations on
            self.datas[0],
            # Set accessor(s) for the indicator output
            ("macd", "signal",),
            # MT5 inidicator name
            indicator="Examples/MACD",
            # Indicator parameters.
            # Any omitted values will use the defaults as defind by the indicator
            params=[12, 26, 9, "PRICE_CLOSE"],
        )()

    def next(self):
        print(f"MT5 indicator Examples/MACD: {self.mt5macd.signal[0]} {self.mt5macd.macd[0]}")

For a fully working and commented example of a Strategy refer to example.py.

Plotting indicators to MT5 charts

This is an experimental feature and a work in progress! It WILL plot wrong data at this time.

You can open and draw directly to a chart in MT5 via the MTraderChart class.

    def __init__(self, store):
        self.bb = btind.BollingerBands(self.data)
        chart = MTraderChart(self.datas[0], realtime=False)
        indi0 = ChartIndicator(idx=0, shortname="Bollinger Bands")
        indi0.addline(
                bb.top,
                style={
                    "linelabel": "Top",
                    "color": "clrBlue",
                },
        )
        chart.addindicator(indi0)

For a fully working and commented example of a Strategy refer to example.py.

License

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE for more information.


Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].