Stock market Telegram bot

Related tags

Miscellaneous stonky
Overview

Stonky Telegram Bot README

Stonky is a Telegram bot that provides access to financial informations. It is backed by the publicly available Yahoo Finance HTTP API, it is written in C and is released under the BSD license.

Installation

  1. Create your bot using the Telegram @BotFather.
  2. After obtaining your bot API key, store it into a file called apikey.txt inside the bot working directory. Alternatively you can use the --apikey command line argument to provide your Telegram API key.
  3. Build Stonky: you need libcurl and libsqlite installed. Just type make.
  4. Run Stonky with ./stonky. There is also a debug mode if you run it using the --debug option (add --debug multiple times for even more verbose messages). For a more moderate output use --verbose. Try stonky --help for the full list of command line options.
  5. Add the bot to your Telegram channel.
  6. IMPORTANT: The bot must be an administrator of the channel in order to read all the messages that are sent in such channel.

By default the bot will create an SQLite database in the working directory. If you want to specify another path for your SQLite db, use the --dbfile command line option.

Usage

To use the bot, send messages in a Telegram channel where the bot is an administrator, otherwise directly address the bot via a private message. All the Stonky commands start with the "$" character.

$AAPL           -- Reply with an update about AAPL price.
$AAPL 1y        -- Reply with an ASCII art graph of AAPL price during
                   the past year. Valid intervals are: 1d|5d|1m|6m|1y|5y
$AAPL mc        -- Reply with the result of a Montecarlo simulation on
                   the 52 weeks price of the specified stock. You can
                   say "montecarlo" instead of "mc" if you want.

The $AAPL mc command supports a period and range option, in case you want to perform experiments with a fixed amount of days of distance between buying and selling, or if you want to change the default 365 days range of analysis.

$AAPL mc period 10 range 200

$AAPL vol       -- Perform a volatility analysis on the stock. The
                   command analyzes the number of days the stock gained
                   and lost separately, reporting the maximum and
                   average profit and loss in a single day.

$AAPL trend     -- Perform a Montecarlo analysis in different ranges
                   and all with fixed give days period between selling
                   and buying, to show how the stock is doing over
                   time.

Lists support

The bot supports the concept of "list of stocks", you can add stocks to a list, then query the list to have all the prices with a single message:

$mylist: +VMW +AAPL +T -KO  -- Modify the list adding/removing stocks.
$mylist:                    -- Ask day change of stocks in a given list.
$mylist::                   -- Ask details of stocks in a given list.
$mylist: ?                  -- Just show the stocks in the list without
                               any additional info. This works without
                               contacting the Yahoo API at all.
$$ ls                       -- Show all the defined lists

Portfolio support

Every list can be used as a portfolio for paper trading (or just to reflect your real portfolio of stocks). For every stock it is possible to buy or sell stocks, optionally specifying the amount and price. For instance to add 50 AAPL stocks bought at an average price of 130.57 write:

$myportfolio: buy AAPL [email protected]

If just the quantity is specified, the current stock price will be used:

$myportfolio: buy AAPL 50

If only the stock name is specified, just a single stock is bought, using the current market price:

$myportfolio: buy AAPL

The bot tracks the average price of your purchases, this is an example of a chat with the bot:

me>  $myportfolio: buy AAPL 50@120
bot> Now you have 50 AAPL stocks at an average price of 120.00
me>  $myportfolio: buy AAPL [email protected]
bot> Now you have 80 AAPL stocks at an average price of 103.28

You can see the list of stocks in your portfolio writing $listname?. For example:

me>  $myportfolio?
bot> AAPL  | 80  | +2567.60 (+31.08%) 💚💚💚

The bot will put a green <3 for every 10% gain, a red one for every 10% loss.

Finally you can sell stocks:

me>  $myportfolio: sell AAPL 10
bot> You are left with 70 AAPL stocks at an average price of 103.28
me>  $myportfolio: sell AAPL
bot> You no longer own AAPL stocks

As you can see, selling without specifying the quantity will just sell all the stocks.

Profit and losses

Stonky remembers all the sell operations performed for a given portfolio. When you sell stocks, you can tell stonky the price at which you sold. This way it will calculate the profit & loss. Example:

me> $newportfolio: buy AAPL 10
bot> Now you have 10 AAPL stocks at an average price of 133.19
me> $newportfolio: buy TSLA 10
bot> Now you have 10 TSLA stocks at an average price of 796.22
me> $newportfolio: sell AAPL [email protected]
bot> You are left with 5 AAPL stocks at an average price of 133.19

Now with the "??" suffix, you can see the history of your sells:

me> $newportfolio??
bot> AAPL   : 5 sold at 710.55$ (P/L +44.60 +6.70% 🍀), 20 seconds ago
     Total portfolio performance: +44.60 USD

Both with the $list? and $list?? forms, you can specify a glob-style pattern in order to show just a subset of matching stocks, like in:

$portfolio?? AAPL

or

$portfolio?? [ab]*

To get a recap of all the available commands, just send an $HELP message to the bot.

Other features

Not all the features may be listed in the readme. Send $HELP to the bot for more information about what it is able to do.

Background analysis of stocks

If the file marketdata/symbols.txt exists in the bot working directory, and contains a list of stock symbols (it is included in the default distribution, so the file exists unless you remove it intentionally), the bot starts continuously analyzing the listed stocks, one per second, looking for stocks that performed in specific ways.

Such stocks are put into lists that are handled by the bot itself. You can see the stocks in this list by writing simply:

$tothemoon:

In the channels where the bot is admin or directly to the bot itself as a private message.

The bot handles the following lists:

  • The tothemoon list contains stocks that performed poorly in the past, but now for some reason are showing to have a massive momentum.
  • The penny list, like tothemoon but for stocks worth less than 15$.
  • The evenbetter list contains stocks that are very strong performers in the past, and now are performing even better.
  • The unstoppable list contains stocks that have generally good parameters and gained value in every of the last 10 days of trading.

Output examples

$AAPL 1y

AAPL 1y | min 57.31 max 136.91
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣾⠀⠀⡀⡀⣀⣴⣿⣾⣿
⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⣾⣿⣶⣿⣿⣿⣿⣿⣿⣿⣿
⠀⠀⠀⠀⠀⠀⠀⣠⣶⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
⣦⣄⠀⢀⣠⣶⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿

$AAPL mc

Buying and selling 'AAPL' at random days during 
the past year would result in 35.53% average gain/loss. 
1000 experiments with an average interval of 83.76 days.

$AAPL

Apple Inc. (AAPL) price is 136.91$ (+0.11%) |
pre-market: 136.66$ (-0.18%)

$AAPL vol

AAPL volatility report:
Reported profits 134 times (53.17%)
Reported loss    118 times (46.83%)
Average profit   2.18%
Average loss     -1.97%
Max     profit   11.98%
Max     loss     -12.86%
Data from last 253 days (adjusted) range.

Bot administration

If you are developing this bot adding features, like I'm doing right now, every time a new feature is added to ssh to the remote server, recompile it and execute it again can be boring. You also need to do that if you are just a normal user and want to update the bot with the new features from time to time. For this reason the bot has a $$ quit <password> feature that let the administrator of the bot to quit it remotely.

To set the admin password use --adminpass option, otherwise the command is not recognized at all. Once you do that, you can start the bot, remotely, under a screen or tmux session, with:

while [ 1 ]; do make; ./stonky; sleep 5; done

Every time the bot quits, it recompiles itself and restarts. The sleep is important since if there is a problem, you don't want to burn all your server CPU in a busy loop.

Caching Yahoo API queries on SQLite

Using the --cache command line option, it is possible to tell the bot to store Yahoo queries about historical data (so not Yahoo queries about the current price of the stock, which must be always updated) in the SQLite database. This allows the "auto lists" feature of the bot to run much faster, and is useful for development purposes. This way you can change the parameters of the tothemoon and other autolists, and check what is the result on the selected stocks. Note that this feature will take more or les 650 MB of disk space, used by your SQLite database.

You can also use --noevict in addition to --cache if you want to use stale data you have in your cache. This is useful for testing.

The cache can be flushed using:

$$ flush-cache
Comments
  • make the json path work for both direct messages and channel posts

    make the json path work for both direct messages and channel posts

    per https://github.com/antirez/stonky/issues/4

    the json struct seems to have changed between the direct message and a channel post

    (36) bmcqueen-mn2:stonky.was bmcqueen$ cat chan_post.json | jq .result[0].channel_post.text
    "$dldld"
    (36) bmcqueen-mn2:stonky.was bmcqueen$ cat dm_post.json | jq .result[0].message.text
    "$helpq"
    (36) bmcqueen-mn2:stonky.was bmcqueen$ 
    
    opened by xmcqueen 6
  • Telegram API's json response differs between a DM and a watched channel

    Telegram API's json response differs between a DM and a watched channel

    For a direct message to the bot, the message in the json payload is in a field called "message", but for a message posted to a watched channel, the message in the json payload is in a field called "channel_post". See the jq expressions below.

    #chan_post.json is the json payload returned when a channel post is detected 
    (36) bmcqueen-mn2:stonky bmcqueen$ cat chan_post.json  | jq .result[0].channel_post.text
    "$dldld"
    
    #dm_post.json is the json payload returned when a direct message to the bot is detected
    (36) bmcqueen-mn2:stonky bmcqueen$ cat dm_post.json | jq .result[0].message.text
    "$helpq"
    (36) bmcqueen-mn2:stonky bmcqueen$ 
    
    

    PR incoming

    opened by xmcqueen 2
  • Error compiling on raspberry 3B

    Error compiling on raspberry 3B

    Hello!

    I'm really enjoying the project! I tried to compile the stonky on Pi3 B and had some problems:

    Hardware/OS:

    Raspberry Pi 3 Model B Rev 1.2
    PRETTY_NAME="Raspbian GNU/Linux 10 (buster)"
    NAME="Raspbian GNU/Linux"
    VERSION_ID="10"
    VERSION="10 (buster)"
    armv7l 
    

    Error

    cc -g -ggdb -O2 -Wall -W -std=c11 \
    	canvas.c cJSON.c sds.c stonky.c \
    	-o stonky -lpthread -lcurl -lsqlite3
    /usr/bin/ld: /tmp/cc9jGxHR.o: in function `fortuneThread':
    /home/stonky/stonky/stonky.c:3058: undefined reference to `__atomic_load_8'
    /usr/bin/ld: /home/stonky/stonky/stonky.c:3059: undefined reference to `__atomic_load_8'
    /usr/bin/ld: /tmp/cc9jGxHR.o: in function `cvThread':
    /home/stonky/stonky/stonky.c:2874: undefined reference to `__atomic_store_8'
    /usr/bin/ld: /tmp/cc9jGxHR.o: in function `botHandleShowPortfolioRequest':
    /home/stonky/stonky/stonky.c:2250: undefined reference to `__atomic_load_8'
    /usr/bin/ld: /home/stonky/stonky/stonky.c:2251: undefined reference to `__atomic_load_8'
    /usr/bin/ld: /tmp/cc9jGxHR.o: in function `botHandleShowProfitLossRequest':
    /home/stonky/stonky/stonky.c:2402: undefined reference to `__atomic_load_8'
    /usr/bin/ld: /tmp/cc9jGxHR.o: in function `botUpdateActiveChannels':
    /home/stonky/stonky/stonky.c:2586: undefined reference to `__atomic_load_8'
    /usr/bin/ld: /home/stonky/stonky/stonky.c:2589: undefined reference to `__atomic_store_8'
    /usr/bin/ld: /home/stonky/stonky/stonky.c:2594: undefined reference to `__atomic_store_8'
    /usr/bin/ld: /home/stonky/stonky/stonky.c:2595: undefined reference to `__atomic_store_8'
    /usr/bin/ld: /tmp/cc9jGxHR.o: in function `broadcastBigMovers':
    /home/stonky/stonky/stonky.c:2957: undefined reference to `__atomic_load_8'
    collect2: error: ld returned 1 exit status
    make: *** [Makefile:4: stonky] Error 1```
    

    Possible solution

    I managed to solve the problem by installing:

    apt install libatomic-ops-dev
    

    And adding the flag to the compilation:

    -latomic
    

    Thanks!

    opened by thiago-scherrer 1
  • Fix warnings: Add _default_source for portablity and default chartInterval

    Fix warnings: Add _default_source for portablity and default chartInterval

    Hi @antirez Following PR fixes GCC warnings for all the implicit declaration and uninitialized ptrs.

    • Add #define _BSD_SOURCE and #define _DEFAULT_SOURCE for extensions portablity.
    • botHandleChartRequest: Defaults api_range and api_internal to 1d and 5m respectively.
    opened by flouthoc 1
  • Fatal Error No such file or directory

    Fatal Error No such file or directory

    I have cloned the code and when i try to run make command i'm getting below error

    cc -g -ggdb -O2 -Wall -W -std=c11
    canvas.c cJSON.c sds.c stonky.c
    -o stonky -lpthread -lcurl -lsqlite3 stonky.c:46:10: fatal error: curl/curl.h: No such file or directory #include <curl/curl.h> ^~~~~~~~~~~~~ compilation terminated. Makefile:4: recipe for target 'stonky' failed make: *** [stonky] Error 1

    opened by FuncGuy 0
Owner
Salvatore Sanfilippo
Computer programmer based in Sicily, Italy. I mostly write OSS software. Born 1977. Not a puritan.
Salvatore Sanfilippo
🍌 C++ Telegram Bot API library

?? banana - thin wrapper over Telegram Bot API written in C++17. Key Features Simple API Single interface for both blocking, non-blocking and even cor

Alexander 30 Nov 22, 2022
Stock exchange simulator made in Swing using Java with logic backend in C++ giving it faster load time and better data control

StockSimulator Stock exchange simulator made in Swing using Java with logic backend in C++ giving it faster load time and better data control Features

Dušan Todorović 0 Mar 1, 2022
Send messages to a LED Matrix display through Telegram. Inspired by a tweet from Smarter Every Day

Send messages to a LED Matrix display through Telegram. Inspired by a tweet from Smarter Every Day

Brian Lough 23 Oct 8, 2022
Experimental telegram client based on official Android sources

Catogram Experimental telegram client based on official Android sources Catogram features: Message translator TGX Style of context menu VKUI Icons and

null 188 Dec 17, 2022
Telegram messenger for Android

Telegram is a messaging app with a focus on speed and security. It’s superfast, simple and free. This repo contains the official source code for Telegram App for Android.

Dao Hong Vinh 10 Nov 22, 2022
Custom kernel for sweet based on Delta, builds hosted on @sweet_epsilon on Telegram (GH releases are outdated)

Linux kernel ============ This file was moved to Documentation/admin-guide/README.rst Please notice that there are several guides for kernel develop

Udit Karode 14 Mar 29, 2022
WIP / DIN-rail compatible WiFi security camera with additional features (doorbell detection, magnetic / reed switch door & PIR sensor...) that sends you alerts on Telegram if someone unauthorised breaks into your house.

WIP / DIN-rail compatible WiFi security camera with additional features (doorbell detection, magnetic / reed switch door & PIR sensor...) that sends you alerts on Telegram if someone unauthorised breaks into your house.

François Leparoux 2 Dec 18, 2021
Telegram Desktop messaging app

Telegram Desktop – Official Messenger This is the complete source code and the build instructions for the alpha version of the official desktop client

Telegram Desktop 20.7k Dec 30, 2022
An unofficial Qt-based client for Telegram messenger.

Kutegram Supported platforms Windows XP and higher (maybe even lower?) Linux Symbian 9.2-9.4 Symbian^3 Maemo 5 Fremantle MeeGo Harmattan Current featu

Kutegram 9 Oct 20, 2022
Optimized, fast and unsafe Uniswap sniping bot for buying new listings.

Optimized, fast and unsafe Uniswap sniping bot for buying new listings. Table of content How does it work? Pregeneration Used libraries Project struct

Sebastian Szczepański 159 Dec 21, 2022
A simple growtopia bot!

CPPBot By DrOreo002 Fixed by Lucy Usage It should be easy to build this, but apparently visual studio wouldn't allow you to. Because sometimes thing c

inf 9 Oct 20, 2021
A 3-D Printed Bot which can talk, cheer, dance and manage your day-to-day schedule.

cheerup A 3-D Printed Bot which can talk, cheer, dance and manage your day-to-day schedule. In childhood many of us have watched this show "SpongeBob

Aniket Dhole 4 Sep 5, 2021
Tetris bot

Lemon Tea Guildline versus tetris bot How to build Notices Lemon Tea makes use of standard library header <bit> available in C++20, so make sure your

null 5 Aug 18, 2022
A Bouncing Seal Discord Bot's Source Code.

A Bouncing Seal It's a fun bot with leveling and funny bouncing seal videos. Information Invite Support Server How to run locally You need DPP, follow

SirObsidian 4 Sep 10, 2021
alie, simplified Discord bot, that's it. As fast and stable as possible.

alie alie, simplified Discord bot, that's it. As fast and stable as possible. Requirements Linux-compatible OS (aka Linux distribution) A C compiler w

mecura 8 Nov 15, 2021
A D++ Discord Bot template for Visual Studio 2019 (x64 and x86)

D++ Windows Bot Template A D++ Discord Bot template for Visual Studio 2019 (x64 and x86, release and debug). The result of this tutorial. This templat

brainbox.cc 28 Dec 24, 2022
Bot for participation to the Lux AI Challenge

Lux AI Challenge This repository is a cleaned version of the official LUX AI Challenge kit that can be found here: https://github.com/Lux-AI-Challenge

AB Normals 2 Dec 6, 2021
Real Time, High performance BOT detection and protection

REAL-TIME BOT PROTECTION CHALLENGE IronFox https://innovera.ir IronFox is a real-time and high performance bot protection, that using Nginx as a reve

Khalegh Salehi 3 Jun 5, 2022
Bot for the Cee.Studio server

cee-bot Bot for the Cee.Studio server. Getting Started Open config.json and match the cee_bot field to your server primitives Head to listeners/ and f

cee.studio 0 Sep 12, 2022