• Stars
    star
    242
  • Rank 161,177 (Top 4 %)
  • Language
    C
  • License
    BSD 3-Clause "New...
  • Created over 3 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Stock market Telegram bot

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.

Building on Raspberry Pi

The above steps should work, but you may also need this before compiling:

apt install libatomic-ops-dev

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

More Repositories

1

disque

Disque is a distributed message broker
C
7,969
star
2

kilo

A text editor in less than 1000 LOC with syntax highlight and search.
C
6,839
star
3

smallchat

A minimal programming example for a chat server
C
6,606
star
4

sds

Simple Dynamic Strings library for C
C
4,649
star
5

linenoise

A small self-contained alternative to readline and libedit
C
3,348
star
6

dump1090

Dump1090 is a simple Mode S decoder for RTLSDR devices
C
2,232
star
7

neural-redis

Neural networks module for Redis
C
2,218
star
8

lamernews

Lamer News -- an HN style social news site written in Ruby/Sinatra/Redis/JQuery
Ruby
1,357
star
9

hping

hping network tool
C
1,327
star
10

smaz

Small strings compression library
C
1,096
star
11

rax

A radix tree implementation in ANSI C
C
1,043
star
12

botlib

C Telegram bot framework
C
754
star
13

load81

SDL based Lua programming environment for kids similar to Codea
C
586
star
14

disque-module

Disque ported as Redis module
C
480
star
15

protoview

Flipper Zero app to display known and unknown signals
C
445
star
16

shapeme

Evolve images using simulated annealing
C
382
star
17

aocla

A small stack based, written to bring Advent of Code 2022 Day 13 puzzle to the extreme consequences
C
371
star
18

retwis

A Twitter-toy clone written in PHP and Redis, used in the early days to introduce Redis data types.
PHP
357
star
19

lua-cmsgpack

A self contained Lua MessagePack C implementation.
C
343
star
20

freakwan

A MicroPython driver for the SX1276 LoRa chip
C++
274
star
21

otree

a simple btree implementation with automatic space reclaiming
C
268
star
22

redis-sampler

Small program to understand the composition of your Redis data set
Ruby
260
star
23

redis-rb-cluster

Redis Cluster Ruby client based on redis-rb
Ruby
246
star
24

RESP3

RESP protocol V3 repository. Contains the specification, and other related resource
221
star
25

redlock-rb

Redlock Redis-based distributed locks implementation in Ruby
Ruby
197
star
26

lloogg

LLOOGG realtime web log analyzer
PHP
195
star
27

redis-timeseries

Ruby library for Redis backed time series.
Ruby
195
star
28

redis-tools

Abandoned project "Redis tools". What was relevant is now part of redis-cli & redis-benchmark
C
194
star
29

pngtostl

Turn PNG images into STL 3D models that will "develop" in front of a light source
C
157
star
30

iconping

Icon Ping - visual ping to 4.2.2.2
Objective-C
129
star
31

jsrt

Javascript ray tracing engine
118
star
32

adventofcode2022

A few Advent of Code puzzles (2022 edition) in C
C
102
star
33

redimension

Redis multi-dimensional query library
Ruby
98
star
34

gopher2redis

A Ruby script that translates a directory structure and its files into the Redis keys to be served via Redis Gopher protocol
Ruby
90
star
35

mc-benchmark

Memcache port of Redis benchmark
C
85
star
36

listpack

A serialization format and implementation for backward-traversable lists of strings.
C
79
star
37

Bigdis

Bigdis - a file-based KV store speaking the Redis protocol
Tcl
76
star
38

visitors

Visitors fast web log analyzer
C
76
star
39

book-examples

Redis The Definitive Guide book code examples
Ruby
51
star
40

flipper-asteroids

Asteroids for Flipper Zero
C
50
star
41

Gitan

Gitan is a very basic web interface to create and inspect bare git repositories
Ruby
45
star
42

aspark

ASCII sparklines for the Enterprise
C
41
star
43

Jim

Jim is a small footprint Tcl interpreter, with some changes to the original language but mostly compatible.
40
star
44

nolate

NO LAme TEmplate System for Ruby
Ruby
40
star
45

recidiv

minimal continuous integration framework written in Tcl (used for Redis CI)
Tcl
38
star
46

tclircd

An IRC server I wrote in 2004 for fun, using the Tcl language.
Tcl
37
star
47

partitions

Partitions.tcl is a Tcl program to simulate partitions between physical hosts
Tcl
36
star
48

connect4-montecarlo

Simple connect 4 AI using Monte Carlo method
C
31
star
49

talk32

C program to talk via serial to MicroPython powered ESP32 boards
C
28
star
50

failed-3d-prints-bot

A Telegram bot that detects failed prints and send you an image of your printer
C
22
star
51

iqmeteo

Meteo widget for the Garmin Vivoactive HR powered by Yahoo Weather API
Shell
21
star
52

siphash

A modification of SipHash reference implementation to make it more practical for Redis usage
C
20
star
53

redisdotphp

Legacy Redis PHP client lib. A best-effort support repository.
18
star
54

yaku-ns

a DNS server I wrote 10 years ago. Here for historical reasons
C
18
star
55

strabo

Turns HGT elevation maps into 2D images or 3D models
C
18
star
56

nn-2003

2003 Neural Networks experiments -- when it was not mainstream ;-)
C
17
star
57

zx2040

RP2040 ZX Spectrum emulator
C
15
star
58

crack-checksum

Find checksum (crc8, xor, add) parameters in a set of messages.
C
13
star
59

hiredis

WARNING: hiredis repository moved to http://github.com/redis/hiredis. Just my private fork.
13
star
60

dict-scan-fuzz-tester

Fuzz testing for the SCAN underlying algorithm
C
11
star
61

Siboom

A simple markup system for writing books drafts
Ruby
10
star
62

sbignum

Old code about C library for big numbers plus Tcl bindings
C
9
star
63

codakido

Redirects to Load81 project
8
star
64

redis-cp-rewrite-sim

Redis/Raft snapshotting rewriting simulation
C
8
star
65

cache-mem-tester

Test memory efficiency of Redis / Memcached against values with a given size distribution.
Ruby
7
star
66

rascan

A prototype for a multi processes port scanner I wrote in 1998. Here only to archive it for myself.
C
6
star
67

LLM-FTC-sampling

First token cutoff sampling inference example
Python
6
star
68

t-watch-s3-micropython

Minimal MicroPython programming example for the Lilygo T-WATCH S3
Python
4
star
69

bma423-pure-mp

Pure MicroPython BMA423 accelerometer driver
Python
4
star
70

simple-language-model

Code for the video on feed-forward language model
Python
4
star
71

gif-pure-tcl

Pure TCL GIF generator
Tcl
4
star
72

bme680-pure-mp

Pure MicroPython Bosch BME680 sensor driver
Python
3
star
73

uc8151_micropython

UC8151 / IL0373 MicroPython e-paper display driver with support for greyscales and fast updates
Python
2
star
74

vl53l0x-nb

Fork of MicroPython driver for vl53l0x TOF sensor to add non-blocking mode.
Python
1
star
75

micropython-ft6x06

Simple driver for FT6x06 capacitive touch sensor in pure Python
Python
1
star