Example #1
0
def get_position(bybit, margin_rate):
    while True:
        try:
            pos = bybit.rest.inverse.private_position_list(symbol='BTCUSD')
            pos = pos.json()['result']
            break
        except Exception as e:
            message = 'Get pos failed.:' + str(e)
            discord_Notify(message)
            time.sleep(2)
            continue
    while True:
        try:
            tic = bybit.rest.inverse.public_tickers(symbol='BTCUSD')
            tic = tic.json()['result'][0]
            break
        except Exception as e:
            message = 'Get tic failed.:' + str(e)
            discord_Notify(message)
            time.sleep(2)
            continue
    side = str(pos['side'])
    size = int(pos['size'])
    price = float(tic['mark_price'])
    wallet_balance = float(pos['wallet_balance'])
    leverage = int(pos['leverage'])
    order_lot = int(price * wallet_balance * leverage * margin_rate + size)
    return side, size, order_lot
Example #2
0
def limit_order(bybit, side, order_lot, delta=5):
    while True:
        try:
            if side == "Sell":
                coef = 1
            if side == "Buy":
                coef = -1


#            bybit.rest.inverse.private_order_cancelall("BTCUSD")
            tic = bybit.rest.inverse.public_tickers("BTCUSD")
            tic = tic.json()['result']
            price = float(tic[0]["last_price"])
            res = bybit.rest.inverse.private_order_create(
                side=side,
                symbol='BTCUSD',
                price=str(price + delta * coef),
                order_type='Limit',
                qty=str(order_lot),
                time_in_force='PostOnly')
            res = res.json()
            break
        except Exception as e:
            print(e)
            message = side + ' order failed.'
            discord_Notify(message)
            time.sleep(5)
            continue
    if res['ret_msg'] != 'OK':
        message = side + ' order failed. msg:' + res['ret_msg']
    else:
        message = side + ' order completed. order_lot:' + str(
            order_lot) + " price: " + str(price)
    return message
Example #3
0
def prediction(df, feats, send=True):
    p = df["prediction_rule"].values[-1]
    #p = np.random.randn()
    if send:
        message = f"prediction : {p}"
        print(message)
        discord_Notify(message)


#     aaaaaaaaaaaaaaa
    p = p > 0.5
    return p
Example #4
0
def get_btc_ohlcv():
    print("get btc ohlcv...")
    dfs = []
    for k in range(4):
        t = int(
            (datetime.datetime.now() -
             datetime.timedelta(days=k * 365)).timestamp()) // 86400 * 86400
        f = int(
            (datetime.datetime.now() - datetime.timedelta(days=(k + 1) * 365)
             ).timestamp()) // 86400 * 86400
        MEX_UDF_URL = 'https://www.bitmex.com/api/udf/history'
        mex_param = {
            'symbol': 'XBTUSD',
            'resolution': '1D',
            'from': str(f),
            'to': str(t)
        }
        while True:
            try:
                res_mex = requests.get(MEX_UDF_URL, mex_param)
                res_mex.raise_for_status()
                break
            except Exception as e:
                message = 'Get xbt ohlcv failed.:' + str(e)
                discord_Notify(message)
                time.sleep(2)
                continue
        ohlcv = res_mex.json()
        data = pd.DataFrame(index=ohlcv['t'], columns=[])
        data['open'] = pd.DataFrame(ohlcv['o'], index=ohlcv['t'])
        data['high'] = pd.DataFrame(ohlcv['h'], index=ohlcv['t'])
        data['low'] = pd.DataFrame(ohlcv['l'], index=ohlcv['t'])
        data['close'] = pd.DataFrame(ohlcv['c'], index=ohlcv['t'])
        data['volume'] = pd.DataFrame(ohlcv['v'], index=ohlcv['t'])
        data = data.reset_index().rename(columns={"index": "time"})
        data["time"] = data["time"].apply(datetime.datetime.fromtimestamp)
        dfs.append(data)


#         data = data[:len(data)-1]
    data = pd.concat(dfs, axis=0)
    data.rename
    data = data.sort_values(by="time").reset_index(drop=True)
    data = data[:-1]
    return data
Example #5
0
def limit_multi_order(bybit, side, now_size, order_lot):
    while True:
        try:
            #            bybit.rest.inverse.private_order_cancelall("BTCUSD")

            #             deltas = [5] + [delta * 2 ** (k) for k in range(num)]
            deltas = [5, 100, 250]
            if side == "Sell":
                coef = 1
            if side == "Buy":
                coef = -1
            print(deltas)
            for i, delta in enumerate(deltas):
                tic = bybit.rest.inverse.public_tickers("BTCUSD")
                tic = tic.json()['result']
                price = float(tic[0]["last_price"])
                if i == 0:
                    lot = now_size + order_lot
                else:
                    lot = order_lot
                print(delta, price, lot, side)
                res = bybit.rest.inverse.private_order_create(
                    side=side,
                    symbol='BTCUSD',
                    price=str(price + delta * coef),
                    order_type='Limit',
                    qty=str(lot),
                    time_in_force='GoodTillCancel')
                res = res.json()
                time.sleep(5)
            break
        except Exception as e:
            print(e)
            message = side + ' order failed.'
            discord_Notify(message)
            time.sleep(5)
            continue
    if res['ret_msg'] != 'OK':
        message = side + ' order failed. msg:' + res['ret_msg']
        discord_Notify(message)
    else:
        message = side + ' order completed. order_lot:' + str(
            order_lot) + " price: " + str(price)
        discord_Notify(message)
    return message
Example #6
0
def limit_order_perf(bybit, pred, margin_rate):
    delta = 0.5
    while True:
        time.sleep(60)
        side, size, order_lot = get_position(bybit, margin_rate)
        bybit.rest.inverse.private_order_cancelall("BTCUSD")  ## cancel
        if pred > 0:
            ## Buy
            if side != 'Buy':
                message = limit_order(bybit, 'Buy', order_lot, delta=delta)
            else:
                message = 'No change. Side:' + str(side) + ' lot:' + str(size)
                discord_Notify(message)
                break
        else:
            ## Sell
            if side != 'Sell':
                message = limit_order(bybit, 'Sell', order_lot, delta=delta)
            else:
                message = 'No change. Side:' + str(side) + ' lot:' + str(size)
                discord_Notify(message)
                break
        discord_Notify(message)
Example #7
0
def market_order(bybit, side, order_lot):
    while True:
        try:
            res = bybit.rest.inverse.private_order_create(
                side=side,
                symbol='BTCUSD',
                order_type='Market',
                qty=order_lot,
                time_in_force='GoodTillCancel')
            res = res.json()
            break
        except Exception as e:
            print(e)
            message = side + ' order failed.'
            discord_Notify(message)
            time.sleep(5)
            continue
    if res['ret_msg'] != 'OK':
        message = side + ' order failed. msg:' + res['ret_msg']
        discord_Notify(message)
    else:
        message = side + ' order completed. order_lot:' + str(order_lot)
        discord_Notify(message)
    return message
Example #8
0
import json
import time
import datetime
import requests
import pybybit
import numpy as np
import pandas as pd

from sklearn.linear_model import LinearRegression, Ridge
import importlib

from config import get_config
from logic_funcs import feature_engineering, get_model, logic
from data_get_funcs import get_btc_ohlcv, get_depth, get_data
from bybit_funcs import get_position, market_order, limit_order, limit_multi_order
from utils import discord_Notify

import argparse
from distutils.util import strtobool

config = get_config()
discord_url = config['discord_url']
apis = [config['api'], config['secret']]
bybit = pybybit.API(*apis, testnet=config['testnet'])
discord_Notify(f"start!!! {datetime.datetime.now()}")