Coder Social home page Coder Social logo

naveenuppunda / kinetick Goto Github PK

View Code? Open in Web Editor NEW

This project forked from imvinaypatil/kinetick

0.0 0.0 0.0 860 KB

Framework for creating and running trading strategies. Blatantly stolen copy of qtpylib to make it work for Indian markets.

License: Apache License 2.0

Dockerfile 0.44% Python 99.56%

kinetick's Introduction

>_• Kinetick Trade Bot

**>_•**

.. image:: https://img.shields.io/github/checks-status/imvinaypatil/kinetick/main :target: https://github.com/imvinaypatil/kinetick :alt: Branch state

Python version

PyPi version

Chat on Discord

Kinetick is a framework for creating and running trading strategies without worrying about integration with broker and data streams (currently integrates with zerodha1). Kinetick is aimed to make systematic trading available for everyone.

Leave the heavy lifting to kinetick so that you can focus on building strategies.

Changelog »

📱 Screenshots

screen1 screen2 screen3

Features

  • A continuously-running Blotter that lets you capture market data even when your algos aren't running.
  • Tick, Bar and Trade data is stored in MongoDB for later analysis and backtesting.
  • Using pub/sub architecture using ØMQ (ZeroMQ) for communicating between the Algo and the Blotter allows for a single Blotter/multiple Algos running on the same machine.
  • Support for Order Book, Quote, Time, Tick or Volume based strategy resolutions.
  • Includes many common indicators that you can seamlessly use in your algorithm.
  • Market data events use asynchronous, non-blocking architecture.
  • Realtime alerts and order confirmation delivered to your mobile via Telegram bot (requires a Telegram bot token).
  • Full integration with TA-Lib via dedicated module (see example).
  • Ability to import any Python library (such as scikit-learn or TensorFlow) to use them in your algorithms.
  • Live charts powered by TradingView
  • RiskAssessor to manage and limit the risk even if strategy goes unexpected
  • Power packed batteries included
  • Deploy wherever Docker lives

Installation

Install using pip:

$ pip install kinetick

Quickstart

There are 5 main components in Kinetick:

  1. Bot - sends alert and signals with actions to perform.
  2. Blotter - handles market data retrieval and processing.
  3. Broker - sends and process orders/positions (abstracted layer).
  4. Algo - (sub-class of Broker) communicates with the Blotter to pass market data to your strategies, and process/positions orders via Broker.
  5. Lastly, Your Strategies, which are sub-classes of Algo, handle the trading logic/rules. This is where you'll write most of your code.

1. Get Market Data

To get started, you need to first create a Blotter script:

# blotter.py
from kinetick.blotter import Blotter

class MainBlotter(Blotter):
    pass # we just need the name

if __name__ == "__main__":
    blotter = MainBlotter()
    blotter.run()

Then run the Blotter from the command line:

$ python -m blotter

If your strategy needs order book / market depth data, add the --orderbook flag to the command:

$ python -m blotter --orderbook

2. Write your Algorithm

While the Blotter running in the background, write and execute your algorithm:

# strategy.py
from kinetick.algo import Algo

class CrossOver(Algo):

    def on_start(self):
        pass

    def on_fill(self, instrument, order):
        pass

    def on_quote(self, instrument):
        pass

    def on_orderbook(self, instrument):
        pass

    def on_tick(self, instrument):
        pass

    def on_bar(self, instrument):
        # get instrument history
        bars = instrument.get_bars(window=100)

        # or get all instruments history
        # bars = self.bars[-20:]

        # skip first 20 days to get full windows
        if len(bars) < 20:
            return

        # compute averages using internal rolling_mean
        bars['short_ma'] = bars['close'].rolling(window=10).mean()
        bars['long_ma']  = bars['close'].rolling(window=20).mean()

        # get current position data
        positions = instrument.get_positions()

        # trading logic - entry signal
        if bars['short_ma'].crossed_above(bars['long_ma'])[-1]:
            if not instrument.pending_orders and positions["position"] == 0:

                """ buy one contract.
                 WARNING: buy or order instrument methods will bypass bot and risk assessor.
                 Instead, It is advised to use create_position, open_position and close_position instrument methods
                 to route the order via bot and risk assessor. """
                instrument.buy(1)

                # record values for later analysis
                self.record(ma_cross=1)

        # trading logic - exit signal
        elif bars['short_ma'].crossed_below(bars['long_ma'])[-1]:
            if positions["position"] != 0:

                # exit / flatten position
                instrument.exit()

                # record values for later analysis
                self.record(ma_cross=-1)


if __name__ == "__main__":
    strategy = CrossOver(
        instruments = ['ACC', 'SBIN'], # scrip symbols
        resolution  = "1T", # Pandas resolution (use "K" for tick bars)
        tick_window = 20, # no. of ticks to keep
        bar_window  = 5, # no. of bars to keep
        preload     = "1D", # preload 1 day history when starting
        timezone    = "Asia/Calcutta" # convert all ticks/bars to this timezone
    )
    strategy.run()

To run your algo in a live environment, from the command line, type:

$ python -m strategy --logpath ~/orders

The resulting trades be saved in ~/orders/STRATEGY_YYYYMMDD.csv for later analysis.

3. Login to bot

While the Strategy running in the background:

Assuming you have added the telegram bot to your chat

  • /login <password> - password can be found in the strategy console.

commands

  • /report - get overview about trades
  • /help - get help
  • /reset-rms - resets RiskAssessor parameters to its initial values.

Configuration

Can be specified either as env variable or cmdline arg

option required? example default note
symbols symbols=./symbols.csv
LOGLEVEL LOGLEVEL=DEBUG INFO
zerodha_user yes - if live trading zerodha_user=ABCD
zerodha_password yes - if live trading zerodha_password=abcd
zerodha_pin yes - if live trading zerodha_pin=1234
BOT_TOKEN optional BOT_TOKEN=12323:asdcldf.. IF not provided then orders will bypass
initial_capital yes initial_capital=10000 1000 Max capital deployed
initial_margin yes initial_margin=1000 100 Not to be mistaken with broker margin. This is the max amount you can afford to loose
initial_margin yes initial_margin=1000 100 Not to be mistaken with broker margin. This is the max amount you can afford to loose
risk2reward yes risk2reward=1.2 1 Set risk2reward for your strategy. This will be used in determining qty to trade
risk_per_trade yes risk_per_trade=200 100 Risk you can afford with each trade
max_trades yes max_trades=2 1 Max allowed concurrent positions
dbport dbport=27017 27017
dbhost dbhost=localhost localhost
dbuser dbuser=user
dbpassword dbpassword=pass
dbname dbname=kinetick kinetick
orderbook orderbook=true false Enable orderbook stream
resolution resolution=1m 1 Min Bar interval

Docker Instructions

  1. Build blotter

    $ docker build -t kinetick:blotter -f blotter.Dockerfile .

  2. Build strategy

    $ docker build -t kinetick:strategy -f strategy.Dockerfile .

  3. Run with docker-compose

    $ docker compose up

Backtesting

$ python -m strategy --start "2021-03-06 00:15:00" --end "2021-03-10 00:15:00" --backtest

Note

To get started checkout the patented BuyLowSellHigh strategy in strategies/ directory.

🙏 Credits

Thanks to @ran aroussi for all his initial work with Qtpylib. Most of work here is derived from his library

Disclaimer

Kinetick is licensed under the Apache License, Version 2.0. A copy of which is included in LICENSE.txt.

All trademarks belong to the respective company and owners. Kinetick is not affiliated to any entity.


  1. Kinetick is not affiliated to zerodha.

kinetick's People

Contributors

imvinaypatil avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.