Package: kinetick
>_•Kinetick Trade BotKinetick is a framework for creating and running trading strategies without worrying
about integration with broker and data streams (currently integrates with zerodha[*]).
Kinetick is aimed to make systematic trading available for everyone.Leave the heavy lifting to kinetick and you focus on building strategies.WARNINGThis project is still in its early stages, please be cautious when dealing with real money.Changelog »📱 ScreenshotsFeaturesA 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 aTelegram bottoken).Full integration withTA-Libvia dedicated module (see example).Ability to import any Python library (such asscikit-learnorTensorFlow) to use them in your algorithms.Live charts powered by TradingViewRiskAssessorto manage and limit the risk even if strategy goes unexpectedPower packed batteries includedDeploy whereverDockerlivesInstallationInstall usingpip:$pipinstallkinetickTelegram bot must be configured in order to take TOTP input for zerodha loginuse/zlogin <totp>command to login to zerodhaQuickstartThere are 5 main components in Kinetick:Bot- sends alert and signals with actions to perform.Blotter- handles market data retrieval and processing.Broker- sends and process orders/positions (abstracted layer).Algo- (sub-class ofBroker) communicates with theBlotterto pass market data to your strategies, and process/positions orders viaBroker.Lastly,Your Strategies, which are sub-classes ofAlgo, handle the trading logic/rules. This is where you’ll write most of your code.1. Get Market DataTo get started, you need to first create a Blotter script:# blotter.pyfromkinetick.blotterimportBlotterclassMainBlotter(Blotter):pass# we just need the nameif__name__=="__main__":blotter=MainBlotter()blotter.run()Then run the Blotter from the command line:$python-mblotterIf your strategy needs order book / market depth data, add the--orderbookflag to the command:$python-mblotter--orderbook2. Write your AlgorithmWhile the Blotter running in the background, write and execute your algorithm:# strategy.pyfromkinetick.algoimportAlgoclassCrossOver(Algo):defon_start(self):passdefon_fill(self,instrument,order):passdefon_quote(self,instrument):passdefon_orderbook(self,instrument):passdefon_tick(self,instrument):passdefon_bar(self,instrument):# get instrument historybars=instrument.get_bars(window=100)# or get all instruments history# bars = self.bars[-20:]# skip first 20 days to get full windowsiflen(bars)<20:return# compute averages using internal rolling_meanbars['short_ma']=bars['close'].rolling(window=10).mean()bars['long_ma']=bars['close'].rolling(window=20).mean()# get current position datapositions=instrument.get_positions()# trading logic - entry signalifbars['short_ma'].crossed_above(bars['long_ma'])[-1]:ifnotinstrument.pending_ordersandpositions["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 analysisself.record(ma_cross=1)# trading logic - exit signalelifbars['short_ma'].crossed_below(bars['long_ma'])[-1]:ifpositions["position"]!=0:# exit / flatten positioninstrument.exit()# record values for later analysisself.record(ma_cross=-1)if__name__=="__main__":strategy=CrossOver(instruments=['ACC','SBIN'],# scrip symbolsresolution="1T",# Pandas resolution (use "K" for tick bars)tick_window=20,# no. of ticks to keepbar_window=5,# no. of bars to keeppreload="1D",# preload 1 day history when startingtimezone="Asia/Calcutta"# convert all ticks/bars to this timezone)strategy.run()To run your algo in aliveenvironment, from the command line, type:$python-mstrategy--logpath~/ordersThe resulting trades be saved in~/orders/STRATEGY_YYYYMMDD.csvfor later analysis.3. Login to botWhile 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. This step is required if you have not provided your telegram chat id as an env var/zlogin <totp>Command to login to zerodha using totpcommands/report- get overview about trades/help- get help/resetrms- resets RiskAssessor parameters to its initial values.ConfigurationCan be specified either as env variable or cmdline argParameterRequired?ExampleDefaultDescriptionsymbolssymbols=./symbols.csvLOGLEVELLOGLEVEL=DEBUGINFOzerodha_useryes - if live tradingzerodha_user=ABCDzerodha_passwordyes - if live tradingzerodha_password=abcdzerodha_pinyes - if live tradingzerodha_pin=1234BOT_TOKENoptionalBOT_TOKEN=12323:asdcldf..IF not provided then orders will bypassinitial_capitalyesinitial_capital=100001000Max capital deployedinitial_marginyesinitial_margin=1000100Not to be mistaken with broker margin. This is the max amount you can afford to looserisk2rewardyesrisk2reward=1.21Set risk2reward for your strategy. This will be used in determining qty to traderisk_per_tradeyesrisk_per_trade=200100Risk you can afford with each trademax_tradesyesmax_trades=21Max allowed concurrent positionsdbportdbport=2701727017dbhostdbhost=localhostlocalhostdbuserdbuser=userdbpassworddbpassword=passdbnamedbname=kinetickkinetickorderbookorderbook=truefalseEnable orderbook streamresolutionresolution=1m1Min Bar intervalpreload_positionsNopreload_positions=30DLoads only overnight positions.Available options: 1D - 1 Day, 1W - 1 Week, 1H - 1 HourCHAT_IDNoCHAT_ID=12345default chat user id to which trade notifications are sent requiring no loginDocker InstructionsBuild blotter$ docker build-tkinetick:blotter-fblotter.Dockerfile .Build strategy$ docker build-tkinetick:strategy-fstrategy.Dockerfile .Run with docker-compose$ docker compose upBacktesting$python-mstrategy--start"2021-03-06 00:15:00"--end"2021-03-10 00:15:00"--backtest--backfillNoteTo get started checkout the patented BuyLowSellHigh strategy instrategies/directory.🙏 CreditsThanks to @ran aroussi for all his initial work with Qtpylib.
Most of work here is derived from his libraryDisclaimerKinetick is licensed under theApache 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.[*]Kinetick is not affiliated to zerodha.