aboutsummaryrefslogtreecommitdiff
path: root/main.py
blob: ab523bec068fa4c00e08de16a1bf54ea7ef378ae (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import configargparse
import dbs
import os
import sys

import market
import portfolio

__all__ = ["make_order", "get_user_market"]

def make_order(market, value, currency, action="acquire",
        close_if_possible=False, base_currency="BTC", follow=True,
        compute_value="average"):
    """
    Make an order on market
    "market": The market on which to place the order
    "value": The value in *base_currency* to acquire,
             or in *currency* to dispose.
             use negative for margin trade.
    "action": "acquire" or "dispose".
                "acquire" will buy long or sell short,
                "dispose" will sell long or buy short.
    "currency": The currency to acquire or dispose
    "base_currency": The base currency. The value is expressed in that
                     currency (default: BTC)
    "follow": Whether to follow the order once run (default: True)
    "close_if_possible": Whether to try to close the position at the end
                         of the trade, i.e. reach exactly 0 at the end
                         (only meaningful in "dispose"). May have
                         unwanted effects if the end value of the
                         currency is not 0.
    "compute_value": Compute value to place the order
    """
    market.report.log_stage("make_order_begin")
    market.balances.fetch_balances(tag="make_order_begin")
    if action == "acquire":
        trade = portfolio.Trade(
                portfolio.Amount(base_currency, 0),
                portfolio.Amount(base_currency, value),
                currency, market)
    else:
        amount = portfolio.Amount(currency, value)
        trade = portfolio.Trade(
                amount.in_currency(base_currency, market, compute_value=compute_value),
                portfolio.Amount(base_currency, 0),
                currency, market)
    market.trades.all.append(trade)
    order = trade.prepare_order(
            close_if_possible=close_if_possible,
            compute_value=compute_value)
    market.report.log_orders([order], None, compute_value)
    market.trades.run_orders()
    if follow:
        market.follow_orders()
        market.balances.fetch_balances(tag="make_order_end")
    else:
        market.report.log_stage("make_order_end_not_followed")
        return order
    market.report.log_stage("make_order_end")

def get_user_market(config_path, user_id, debug=False):
    args = ["--config", config_path]
    if debug:
        args.append("--debug")
    args = parse_args(args)
    parse_config(args)
    market_id, market_config, user_id = list(fetch_markets(str(user_id)))[0]
    return market.Market.from_config(market_config, args, user_id=user_id)

def fetch_markets(user):
    cursor = dbs.psql.cursor()

    if user is None:
        cursor.execute("SELECT id,config,user_id FROM market_configs WHERE status='enabled'")
    else:
        cursor.execute("SELECT id,config,user_id FROM market_configs WHERE status='enabled' AND user_id = %s", [user])

    for row in cursor:
        yield row

def parse_config(args):
    if args.db_host is not None:
        dbs.connect_psql(args)

    if args.redis_host is not None:
        dbs.connect_redis(args)

    report_path = args.report_path

    if report_path is not None and not \
            os.path.exists(report_path):
        os.makedirs(report_path)

def parse_args(argv):
    parser = configargparse.ArgumentParser(
            description="Run the trade bot.")

    parser.add_argument("-c", "--config",
            default="config.ini",
            required=False, is_config_file=True,
            help="Config file to load (default: config.ini)")
    parser.add_argument("--before",
            default=False, action='store_const', const=True,
            help="Run the steps before the cryptoportfolio update")
    parser.add_argument("--after",
            default=False, action='store_const', const=True,
            help="Run the steps after the cryptoportfolio update")
    parser.add_argument("--quiet",
            default=False, action='store_const', const=True,
            help="Don't print messages")
    parser.add_argument("--debug",
            default=False, action='store_const', const=True,
            help="Run in debug mode")
    parser.add_argument("--user",
            default=None, required=False, help="Only run for that user")
    parser.add_argument("--action",
            action='append',
            help="Do a different action than trading (add several times to chain)")
    parser.add_argument("--parallel", action='store_true', default=True, dest="parallel")
    parser.add_argument("--no-parallel", action='store_false', dest="parallel")
    parser.add_argument("--report-db", action='store_true', default=True, dest="report_db",
            help="Store report to database (default)")
    parser.add_argument("--no-report-db", action='store_false', dest="report_db",
            help="Don't store report to database")
    parser.add_argument("--report-redis", action='store_true', default=False, dest="report_redis",
            help="Store report to redis")
    parser.add_argument("--no-report-redis", action='store_false', dest="report_redis",
            help="Don't store report to redis (default)")
    parser.add_argument("--report-path", required=False,
            help="Where to store the reports (default: absent, don't store)")
    parser.add_argument("--no-report-path", action='store_const', dest='report_path', const=None,
            help="Don't store the report to file (default)")
    parser.add_argument("--db-host", default="localhost",
            help="Host access to database (default: localhost)")
    parser.add_argument("--db-port", default=5432,
            help="Port access to database (default: 5432)")
    parser.add_argument("--db-user", default="cryptoportfolio",
            help="User access to database (default: cryptoportfolio)")
    parser.add_argument("--db-password", default="cryptoportfolio",
            help="Password access to database (default: cryptoportfolio)")
    parser.add_argument("--db-database", default="cryptoportfolio",
            help="Database access to database (default: cryptoportfolio)")
    parser.add_argument("--redis-host", default="localhost",
            help="Host access to database (default: localhost). Use path for socket")
    parser.add_argument("--redis-port", default=6379,
            help="Port access to redis (default: 6379)")
    parser.add_argument("--redis-database", default=0,
            help="Redis database to use (default: 0)")

    parsed = parser.parse_args(argv)
    if parsed.action is None:
        parsed.action = ["sell_all"]
    return parsed

def process(market_config, market_id, user_id, args):
    try:
        market.Market\
                .from_config(market_config, args, market_id=market_id,
                        user_id=user_id)\
                .process(args.action, before=args.before, after=args.after)
    except Exception as e:
        print("{}: {}".format(e.__class__.__name__, e))

def main(argv):
    args = parse_args(argv)

    parse_config(args)

    market.Portfolio.report.set_verbose(not args.quiet)

    if args.parallel:
        import threading
        market.Portfolio.start_worker()

        threads = []
        def process_(*args):
            thread = threading.Thread(target=process, args=args)
            thread.start()
            threads.append(thread)
    else:
        process_ = process

    for market_id, market_config, user_id in fetch_markets(args.user):
        process_(market_config, market_id, user_id, args)

    if args.parallel:
        for thread in threads:
            thread.join()
        market.Portfolio.stop_worker()

if __name__ == '__main__': # pragma: no cover
    main(sys.argv[1:])