Beispiel #1
0
class BinanceAPI:

    def __init__(self, api_key, api_secret):
        API_KEY = api_key
        API_SECRET = api_secret

        self.client = Client(API_KEY, API_SECRET)


    def get_ticker(self, pair):
        try:
            value = self.client.get_ticker(symbol=pair)
            return value
        except Exception as e:
            print("Exception : " + str(e))


    def get_current_price(self, pair):
        try:
            ticker = self.client.get_symbol_ticker(symbol=pair)
            value = ticker["price"]
            return float(value)
        except Exception as e:
            print("Exception : " + str(e))


    def get_klines(self, pair, number):
        try:
            klines = pd.DataFrame(self.client.get_klines(symbol=pair, interval=Client.KLINE_INTERVAL_30MINUTE, limit=number),columns = ["OpenTime","Open","High","Low","Close","Volume","CloseTime","QuoteVolume","TradeCount","TakerVolume","TakerQuoteVolume","Ignore"])
            value = klines[["OpenTime","Close","High","Low","Volume","QuoteVolume","TakerVolume","TakerQuoteVolume","TradeCount"]].copy()
            value.loc[:, "OpenTime"] = pd.to_datetime(value["OpenTime"].apply(lambda x: datetime.fromtimestamp(int(x/1000))))
            value = value.set_index("OpenTime")
            return value
        except Exception as e:
            print("Exception : " + str(e))


    def get_historical_klines(self, pair, start, end):
        try:
            klines = pd.DataFrame(self.client.get_historical_klines(start_str = start,end_str = end,symbol=pair, interval=Client.KLINE_INTERVAL_30MINUTE, limit=500),columns = ["OpenTime","Open","High","Low","Close","Volume","CloseTime","QuoteVolume","TradeCount","TakerVolume","TakerQuoteVolume","Ignore"])
            value = klines[["OpenTime","Close","High","Low","Volume","QuoteVolume","TakerVolume","TakerQuoteVolume","TradeCount"]].copy()
            value.loc[:, "OpenTime"] = pd.to_datetime(value["OpenTime"].apply(lambda x: datetime.fromtimestamp(int(x/1000))))
            value = value.set_index("OpenTime")
            return value
        except Exception as e:
            print("Exception : " + str(e))


    def get_balance(self, symbol):
        try:
            value = self.client.get_asset_balance(asset=symbol)
            return value
        except Exception as e:
            print('Exception : {}'.format(e))

    def get_free_balance(self, symbol):
        try:
            value = self.client.get_asset_balance(asset=symbol)
            return float(value["free"])
        except Exception as e:
            print('Exception : {}'.format(e))


    def get_futures_balance(self, symbol):
        try:
            value = self.client.futures_account_balance()
            balance = [balance["balance"] for balance in value if balance["asset"] == symbol]
            return float(str(*balance))
        except Exception as e:
            print('Exception : {}'.format(e))
            


    def create_limit_order(self, symbol, price, quantity, side_str):
        try:
            if side_str == "BUY":
                side = self.client.SIDE_BUY
            elif side_str == "SELL":
                side = self.client.SIDE_SELL
            order = self.client.order_limit(
            symbol=symbol,
            side=side,
            timeInForce=self.client.TIME_IN_FORCE_IOC,
            price=price,
            quantity=quantity)
            print(order)
            print("buy order created.\nSymbol:{0:5}\nPrice:{1:5}\nQuantity:{2:5}",symbol,price,quantity)
        except Exception as e:
            print("Exception : " + str(e))


    def create_market_order(self, symbol, quantity, side_str):
        try:
            if side_str == "BUY":
                side = self.client.SIDE_BUY
            elif side_str == "SELL":
                side = self.client.SIDE_SELL
            order = self.client.order_market(
            symbol=symbol,
            side=side,
            quantity=quantity)
            print(order)
            print("buy order created.\nSymbol:{0:5}\nPrice:{1:5}\nQuantity:{2:5}",symbol,price,quantity)
        except Exception as e:
            print("Exception : " + str(e))


    def create_test_order(self, symbol, quantity, side_str):
        try:
            if side_str == "BUY":
                side = self.client.SIDE_BUY
            elif side_str == "SELL":
                side = self.client.SIDE_SELL
            order = self.client.create_test_order(
            symbol=symbol,
            side=side,
            type=self.client.ORDER_TYPE_MARKET,
            quantity=quantity)
            print(order)
            print("buy order created.\nSymbol:{0:5}\nQuantity:{1:5}".format(symbol,quantity))
        except Exception as e:
            print("Exception : " + str(e))



    def create_futures_order(self, symbol, quantity, side_str):
        try:
            if side_str == "BUY":
                side = self.client.SIDE_BUY
            elif side_str == "SELL":
                side = self.client.SIDE_SELL
            order = self.client.futures_create_order(
            symbol=symbol,
            side=side,
            type=self.client.ORDER_TYPE_MARKET,
            quantity=quantity)
            #print(order)
            print("buy order created.\nSymbol:{0:5}\nQuantity:{1:5}".format(symbol,quantity))
        except Exception as e:
            print("Exception : " + str(e))




    def get_base_asset(self, symbol):
        try:
            return self.client.get_symbol_info(symbol)["baseAsset"];
        except Exception as e:
            print("Exception : " + str(e))


    def get_quote_asset(self, symbol):
        try:
            return self.client.get_symbol_info(symbol)["quoteAsset"];
        except Exception as e:
            print("Exception : " + str(e))

    def get_all_tickers(self):
        try:
            return self.client.get_all_tickers();
        except Exception as e:
            print("Exception : " + str(e))

    def get_all_orders(self):
        try:
            return self.client.get_all_orders();
        except Exception as e:
            print("Exception : " + str(e))
Beispiel #2
0
class Trader():
    """
    Purpose is to trade live on the Binance Crypto Exchange

    Attributes
    -----------
    symbol: str
    client: Client object - From binance.py
    capital: float - represents how much money is in account
    leverage: float - how many multiples of your money you want to trade
    tf: int - timeframe
    df: pd.DataFrame - data that will be analyzed.
    Methods
    ----------
    load_account
    set_leverage
    set_timeframe
    get_position
    get_necessary_data
    set_asset
    make_row
    load_existing_asset
    start_trading

    Please look at each method for descriptions
    """
    def __init__(self):
        self.start = False
        self.client = None
        self.capital = None
        self.leverage = 1 / 1000
        self.tf = None
        self.symbol = None
        self.loader = _DataLoader()
        self.df = None

    def check_status(self) -> bool:
        """
        Reads a txt file to see whether user wants trading to be on or off
        :return boolean of True or False. True means trading is on, and false means it is off.
        """
        local_path = os.path.dirname(
            os.path.dirname(
                os.path.abspath("__file__"))) + r"\local\trade_status.txt"
        status = pd.read_csv(local_path).set_index('index')
        self.start = bool(status.loc[0, 'status'])

    def load_account(self, additional_balance: int = 20000) -> str:
        """
        Sign in to account using API_KEY and using Binance API
        """
        local_path = os.path.dirname(
            os.path.dirname(
                os.path.abspath("__file__"))) + r"\local\binance_api.txt"
        info = pd.read_csv(local_path).set_index('Name')
        API_KEY = info.loc["API_KEY", "Key"]
        SECRET = info.loc["SECRET", "Key"]
        self.client = Client(API_KEY, SECRET)
        # Initializing how much money I have on the exchange. Sample 20000 has been added.
        self.capital = int(
            float(self.client.futures_account_balance()[0]
                  ['balance'])) + additional_balance
        return "Welcome Haseab"

    def set_leverage(self, leverage: float) -> float:
        """Sets the current leverage of the account: should normally be 1. And 0.001 for testing purposes"""
        self.leverage = leverage
        return self.leverage

    def set_timeframe(self, tf: int) -> int:
        """Sets the timeframe of the trading data"""
        self.tf = tf
        return self.tf

    def get_necessary_data(self, symbol: str, tf: int,
                           max_candles_needed: int) -> pd.DataFrame:
        """
        Gets the minimum necessary data to trade this asset. Only a symbol and timeframe need to be inputted

        Note: This method is used as a way to tackle the 1000 candle limit that is currently on the Binance API.
        A discrete set of ~1000 group candles will be determined, and then the data will be extracted from each,
        using the _get_binance_futures_candles method, and then all of them will be merged together.

        Parameters:
        symbol: str             - Symbol of price ticker   Ex. "BTCUSDT", "ETHUSDT"
        tf: int                 - Timeframe wanted   Ex. 1, 3, 5, 77, 100
        max_candles_needed: int - Maximum candles needed in the desired timeframe     Ex. 231, 770, 1440

        :return pd.DataFrame of candlestick data

        """
        now = time.time()
        df = pd.DataFrame()
        ranges = Helper.determine_candle_positions(max_candles_needed, tf)

        # Grabbing each set of about 1000 candles and appending them one after the other
        for i in range(len(ranges)):
            try:
                df = df.append(
                    self.loader._get_binance_futures_candles(
                        symbol, int(ranges[i]), int(ranges[i + 1]), now))
            except IndexError:
                pass
        return df.drop_duplicates()

    def _update_data(
        self,
        diff: int,
        symbol: str,
    ) -> None:
        """
        Used to update the trading data with the exchange data so that it is real time

        Parameters:
        -----------
        diff: a number that explains how many minutes of disparity there is between current data and live data.

        :return dataframe with the most up-to-date data.
        """
        # Calculating how many minutes to fetch from API
        minutes = math.floor(diff) + 1

        # Getting minute candlestick data. Number of minute candlesticks represented by "minutes" variable
        last_price = self.loader._get_binance_futures_candles(symbol, minutes)
        # Adding a legible Datetime column and using the timestamp data to obtain datetime data
        last_price['Datetime'] = [
            datetime.fromtimestamp(i / 1000) for i in last_price.index
        ]
        last_price = last_price[[
            "Datetime", "Open", "High", "Low", "Close", "Volume"
        ]]

        # Abstracting minute data into appropriate tf
        last_price = self.loader._timeframe_setter(last_price, self.tf, 0)

        # Updating original data with new data.
        self.df = self.df.append(last_price).drop_duplicates()

    def get_position(self, symbol: str) -> float:
        """
        Gets the total amount of current position for a given symbol
        Parameters:
        ------------
        symbol: str
            Ex. "BTCUSDT"
                "ETHUSDT"

        Returns float
            Ex. If a 1.000 BTC position is open, it will return 1.0
        """
        return float([
            i["positionAmt"]
            for i in self.client.futures_position_information()
            if i['symbol'] == symbol
        ][0])

    def set_asset(self, symbol: str, tf: int) -> str:
        """
        Set Symbol of the ticker and load the necessary data with the given timeframe to trade it

        Parameters:
        ------------
        symbol: str     Ex. "BTCUSDT", "ETHUSDT"

        :return str response
        """
        self.symbol = symbol
        max_candles_needed = 231

        # For Binance API purposes, 240 min needs to be inputted as "4h" on binance when fetching data
        map_tf = {
            1: "1m",
            3: "3m",
            5: "5m",
            15: "15m",
            30: "30m",
            60: "1h",
            120: "2h",
            240: "4h",
            360: "6h",
            480: "8h"
        }

        start_time = int((time.time() - self.tf * 235 * 60) * 1000)

        if tf in [1, 3, 5, 15, 30, 60, 120, 240, 360,
                  480]:  # Note: 12H, 1D, 3D, 1W, 1M are also recognized

            # Fetching data from Binance if it matches the eligible timeframe, as it will be faster
            df = Helper.into_dataframe(
                self.client.futures_klines(symbol=symbol,
                                           interval=map_tf[tf],
                                           startTime=start_time))
            df.drop(df.tail(1).index, inplace=True)

        else:
            # If it doesn't match Binance available timeframes, it must be transformed after fetching 1m data.
            df = self.get_necessary_data(symbol, tf, max_candles_needed)
            df = self.loader._timeframe_setter(df, tf)

        # Adding Datetime column for readability of the timestamp. Also more formatting done
        df['Datetime'] = [datetime.fromtimestamp(i / 1000) for i in df.index]
        df = df[["Datetime", "Open", "High", "Low", "Close", "Volume"]]
        df[["Open", "High", "Low", "Close",
            "Volume"]] = df[["Open", "High", "Low", "Close",
                             "Volume"]].astype(float)

        self.df = df

        return f"Symbol changed to {self.symbol}"

    def make_row(
            self,
            high=[],
            low=[],
            volume=[],
            count: int = 0,
            open_price: float = None,
            open_date: str = None
    ) -> (pd.DataFrame, list, list, list, list, list):
        """
        Helper function used to update the last row of a dataframe, using all of the data in the previous "last row" as input.
        This is used to update the price of the candlestick live, with the incomplete current candle constantly updating.

        Parameters:
        -----------
        high:       list        Ex. [23348, 23350, 23335, 23330, 23339]
        low:        list        Ex. [23300, 23345, 23335, 23320, 23300]
        volume:     list        Ex. [47, 31, 110, 117, 2, 55]
        count:      int         Ex. 1,2,3
        open_price: float       Ex. 23342
        open_date:  str         Ex. "2020-08-04 17:33:02"

        Returns tuple -> (pd.DataFrame, list, list, list, list, list)
        """
        # row variable gets a pd.DataFrame of size 1.
        row = self.loader._get_binance_futures_candles("BTCUSDT",
                                                       1).reset_index()
        timestamp = row.loc[0, "Timestamp"]
        close = float(row.loc[0, "Close"])
        high.append(float(row.loc[0, "High"]))
        low.append(float(row.loc[0, "Low"]))
        volume.append(float(row.loc[0, "Volume"]))

        # Initial values of a candle that only get set on the first iteration.
        if count == 0:
            open_price = row.loc[0, "Open"]
            open_date = timestamp

        # Adding to previous candlestick data of the last row by updating the row.
        dfrow = pd.DataFrame([[
            open_date,
            datetime.fromtimestamp(open_date / 1000), open_price,
            max(high),
            min(low), close,
            sum(volume)
        ]],
                             columns=[
                                 "Timestamp", "Datetime", "Open", "High",
                                 "Low", "Close", "Volume"
                             ])

        dfrow[["Open", "High", "Low", "Close",
               "Volume"]] = dfrow[["Open", "High", "Low", "Close",
                                   "Volume"]].astype(float)
        dfrow = dfrow.set_index("Timestamp")

        return dfrow, high, low, volume, open_price, open_date

    def load__existing_asset(self, df: pd.DataFrame) -> pd.DataFrame:
        """Sets the trading data to an already existing dataframe, passed in as an argument"""
        self.df = df
        return self.df

    def start_trading(self,
                      strategy: FabStrategy,
                      executor,
                      tf: int,
                      sensitivity=0,
                      debug=False) -> str:
        """
        Starts the process of trading live. Each minute, the last row of the data is updated and Rule #2 is checked,
        otherwise, it waits till the end of the timeframe where it gets the latest data before it checks the rest of the rules.
        If it does see something following the rules, it will buy/short, given the initial parameters it has. (e.g. leverage, quantity)
        This process continues indefinetly, unless interrupted.

        Returns None.
        """
        count, open_price = 0, 0
        open_date = None
        high, low, volume = [], [], []

        # Loading data into strategy, and creating moving averages.
        strategy.load_data(self.df)
        strategy.create_objects()

        # Checking to see whether trading is on or off. If it is off then it will not enter while loop.
        self.check_status()

        while self.start != False:
            diff = Helper.calculate_minute_disparity(self.df, tf)
            if round(time.time() % 60, 1) == 0 and diff <= tf:

                # Getting the most up-to-date row of the <tf>-min candlestick
                dfrow, high, low, volume, open_price, open_date = self.make_row(
                    high, low, volume, count, open_price, open_date)

                if debug == True:
                    print(dfrow)
                    print(f"{tf - diff} minutes left")

                # Updating moving averages
                strategy.load_data(self.df.append(dfrow))
                strategy.create_objects()

                # Checking only Rule 2, because it needs a minute by minute check.
                # Second condition is making sure that there is no existing position
                if strategy.rule_2_buy_enter(
                        -1, sensitivity) and self.get_position(
                            self.symbol) == 0:
                    trade_info = executor.enter_market(self.symbol, "BUY", 2)
                elif strategy.rule_2_short_enter(
                        -1, sensitivity) and self.get_position(
                            self.symbol) == 0:
                    trade_info = executor.enter_market(self.symbol, "SELL", 2)

                # Saves CPU usage, waits 5 seconds before the next minute
                time.sleep(50)

                count += 1

            elif diff > tf:
                # Updating data using Binance API instead of appending the completed final row from the while loop
                self._update_data(math.floor(diff), "BTCUSDT")

                # Updating Moving averages
                strategy.load_data(self.df)
                strategy.create_objects()

                # Checks for the rest of the rules
                if strategy.rule_2_short_stop(-1) and self.get_position(self.symbol) < 0 and \
                        executor.live_trade_history.last_trade().rule == 2:
                    trade_info = executor.exit_market(
                        self.symbol, 2, self.get_position(self.symbol))
                elif strategy.rule_2_buy_stop(-1) and self.get_position(self.symbol) > 0 and \
                        executor.live_trade_history.last_trade().rule == 2:
                    trade_info = executor.exit_market(
                        self.symbol, 2, self.get_position(self.symbol))
                elif strategy.rule_1_buy_enter(-1) and self.get_position(
                        self.symbol) == 0:
                    trade_info = executor.enter_market(self.symbol, "BUY", 1)
                elif strategy.rule_1_buy_exit(-1) and self.get_position(
                        self.symbol) > 0:
                    trade_info = executor.exit_market(
                        self.symbol, 1, self.get_position(self.symbol))
                elif strategy.rule_1_short_enter(-1) and self.get_position(
                        self.symbol) == 0:
                    trade_info = executor.enter_market(self.symbol, "SELL", 1)
                elif strategy.rule_1_short_exit(-1) and self.get_position(
                        self.symbol) < 0:
                    trade_info = executor.exit_market(
                        self.symbol, 1, self.get_position(self.symbol))
                elif strategy.rule_3_buy_enter(-1) and self.get_position(
                        self.symbol) == 0:
                    trade_info = executor.enter_market(self.symbol, "BUY", 3)
                elif strategy.rule_3_short_enter(-1) and self.get_position(
                        self.symbol) == 0:
                    trade_info = executor.enter_market(self.symbol, "SELL", 3)

                    # Resetting candlesticks
                high, low, volume = [], [], []
                count = 0
                time.sleep(1)

                if debug == True:
                    print(diff)
                    print("next")
            self.check_status()

        return "Trading Stopped"
Beispiel #3
0
class BinanceWrapperAPI(WrapperAPI):

    # (n) means that parameter is necessary

    def __init__(self, pair, target, precision):
        self.pair = pair
        self.precision = precision
        self.target = target
        self.client = Client(keys.binance_api_key, keys.binance_api_secret)

    def get_my_balance_coin(self, coin):
        balances = self.client.futures_account_balance()
        balance = find(lambda v: v['asset'] == coin, balances)
        return float(balance['withdrawAvailable']) if balance else 0

    def get_mycoin(self):
        return self.get_my_balance_coin('USDT')

    def get_position_targ(self) -> Tuple[float, bool]:
        risks = self.client.futures_position_information(symbol=self.target)
        position = find(lambda v: v['symbol'] == self.pair, risks)
        amt = float(position['positionAmt'])
        return abs(amt), amt >= 0

    def get_balance_interest(self):
        amount, _ = self.get_position_targ()
        return amount

    def buy_order(self, amount: float):
        return self.post_order_market("BUY", amount)

    def sell_order(self, amount: float):
        return self.post_order_market("SELL", amount)

    def post_order_market(self, side: str, quantity: float):
        try:
            res = self.client.futures_create_order(
                symbol=self.pair,
                side=side,
                type="MARKET",
                # positionSide=pside,
                quantity=roundt(quantity, self.precision))
            return [True, res['orderId']]
        except BinanceAPIException as e:
            raise (e)
            return [False, e]

    def get_open_orders(self):
        return self.client.get_open_orders(symbol=self.pair)

    def get_position(self) -> Literal["none", "long", "shor"]:
        amount, posi = self.get_position_targ()
        if amount == 0:
            return 'none'
        return "long" if posi else "shor"

    def get_ask(self):
        return float(self.client.get_ticker(symbol=self.pair)['askPrice'])

    def get_bid(self):
        return float(self.client.get_ticker(symbol=self.pair)['bidPrice'])

    def get_order_status(self, id) -> Literal["COMP", "NEW", "EXPIRE"]:
        try:
            res = self.client.futures_get_order(symbol=self.pair, orderId=id)
            if res['status'] == "FILLED":
                return "COMP"
            # other: CANCELED, PARTIALLY_FILLED
            return "NEW"

        except BinanceAPIException as e:
            return "EXPIRE"
Beispiel #4
0
sys.path.insert(0, r'/usr/local/WB/dashboard')
import Settings

main_path_data = os.path.expanduser('/usr/local/WB/data/')
warnings.filterwarnings("ignore")

api_key = Settings.API_KEY
api_secret = Settings.API_SECRET
# testnet = True
bclient = Client(api_key=api_key, api_secret=api_secret)

"""
CHECK FUTURE BALANCE
"""
my_bal = bclient.futures_account_balance()

for i in my_bal:
    print(i["asset"], " : ", i["balance"])


"""
CHANGE SYMBOL marginType (ISOLATED)
"""

# rep = bclient.futures_change_margin_type(symbol='SUSHIUSDT', marginType="ISOLATED")
# print(rep)


"""
CHECK FUTURE ACCOUNT
Beispiel #5
0
class Orders:
    def __init__(self,
                 SYMBOL,
                 LEWAR,
                 PYRAMID_MAX,
                 ORDER_SIZE,
                 is_it_for_real=False):
        self.SYMBOL = SYMBOL
        self.LEWAR = LEWAR
        self.PYRAMID_MAX = PYRAMID_MAX
        self.ORDER_SIZE = ORDER_SIZE

        self.side = {"LONG": 'BUY', "SHORT": 'SELL'}
        self.side_reversed = {
            "SHORT": 'BUY',
            "LONG": 'SELL',
            "BUY": 'SELL',
            "SELL": 'BUY'
        }

        if is_it_for_real:
            with open("api_keys.txt") as d:
                api_keys = d.readlines()
                api_keys[0] = api_keys[0].strip()
            self.client = Client(api_keys[0], api_keys[1])

        self.zagranie_list = []

        try:
            client.futures_change_margin_type(symbol=self.SYMBOL + 'USDT',
                                              marginType="ISOLATED")
        except:
            pass

        self.client.futures_change_leverage(symbol=self.SYMBOL + 'USDT',
                                            leverage=self.LEWAR)

    def update(self):
        l = len(self.zagranie_list)
        for i, zagranie in enumerate(self.zagranie_list[::-1]):
            zagranie.update()
            if zagranie.state == 'closed':
                zagranie.close()
                del zagranie_list[l - 1 - i]

    def order_size(self, price, balance):
        #return 0.6**pyramid*ORDER_SIZE*balance*LEWAR/price
        return self.ORDER_SIZE * balance * self.LEWAR / price

    def get_balance(self):
        a = self.client.futures_account_balance()
        for e in a:
            if e['asset'] == 'USDT':
                return float(e['withdrawAvailable'])

    def positionInfo(self):
        a = self.client.futures_position_information()
        for e in a:
            if e['symbol'] == self.SYMBOL + 'USDT':
                return e

    def create_order(self, side, price=None, TARGET_CHANGE=True):
        print(f"Opening {side}")

        if len(self.zagranie_list) >= self.PYRAMID_MAX:
            print("Pyramid max reached")
            return None

        balance = self.get_balance()

        if price:
            order = self.client.futures_create_order(
                symbol=self.SYMBOL + 'USDT',
                side=self.side[side],
                type='LIMIT',
                timeInForce=TIME_IN_FORCE_GTC,
                quantity=self.order_size(price, balance),
                price=price,
                newOrderRespType="RESULT")
        else:
            order = self.client.futures_create_order(
                symbol=SYMBOL + 'USDT',
                side=self.side[side],
                type='MARKET',
                quantity=self.order_size(
                    self.price, balance),  #JAKIS DOMYSLMY PRICE TRZRBA DAC
                newOrderRespType="RESULT")

        if TARGET_CHANGE:
            if side == "LONG":
                oco_limit_price = self.price * (1 + TARGET_CHANGE)
                oco_stop_price = self.price * (1 - TARGET_CHANGE)
            elif side == "SHORT":
                oco_limit_price = self.price * (1 - TARGET_CHANGE)
                oco_stop_price = self.price * (1 + TARGET_CHANGE)

        zagranie = Zagranie(self, side, order['orderId'], oco_limit_price,
                            oco_stop_price)

        self.zagranie_list.append(zagranie)

        return order['orderId']

    def close(self, side):
        print(f"Closing {side}")

        l = len(self.zagranie_list)
        for i, zagranie in enumerate(self.zagranie_list[::-1]):
            if zagranie.side == side:
                zagranie.close()
                del zagranie_list[l - 1 - i]
Beispiel #6
0
def main():

    arg = docopt(__doc__, version=version)
    api_key = getenv('BINANCE_FUTURES_API')
    sec_key = getenv('BINANCE_FUTURES_SEC')
    if not api_key and not sec_key:
        print('please set these environment variables:\n'\
              '    BINANCE_FUTURES_API\n'\
              '    BINANCE_FUTURES_SEC', file=stderr)
        return 1
    if not api_key:
        print('environment variable not found: BINANCE_FUTURES_API',
              file=stderr)
        return 1
    if not sec_key:
        print('environment variable not found: BINANCE_FUTURES_SEC',
              file=stderr)
        return 1
    client = Client(api_key, sec_key)
    sides = {
        'buy': Client.SIDE_BUY,
        'long': Client.SIDE_BUY,
        'sell': Client.SIDE_SELL,
        'short': Client.SIDE_SELL,
    }
    types = {
        'limit': Client.ORDER_TYPE_LIMIT,
        'market': Client.ORDER_TYPE_MARKET
    }
    tifs = {
        'gtc': Client.TIME_IN_FORCE_GTC,
        'ioc': Client.TIME_IN_FORCE_IOC,
        'fok': Client.TIME_IN_FORCE_FOK
    }

    if arg['--verbose']:
        print(arg, file=stderr)
    else:
        sys.tracebacklimit = 0

    if arg['--help']:
        print(__doc__, file=stderr)
        return 0

    elif arg['status']:
        return client.get_system_status()['status']

    elif arg['balance']:
        if arg['futures']:
            print(dumps(client.futures_account_balance()))
        elif arg['spot']:
            print(dumps(client.get_account()['balances']))
        elif arg['coin']:
            print(dumps(client.futures_coin_account_balance()))
        return 0

    elif arg['show']:
        if arg['spot']:
            if arg['orders']:
                # if arg['--all']:
                #     print(dumps(client.get_all_orders()))
                # else:
                print(dumps(client.get_open_orders()))

    elif arg['order']:
        symbol = arg['<symbol>'].upper()
        if arg['futures'] and not symbol.endswith('USDT'):
            symbol += 'USDT'
        if arg['cancel']:
            if arg['futures']:
                print(
                    client.futures_cancel_order(symbol=symbol,
                                                orderid=arg['<orderid>'],
                                                timestamp=timemilli()))
            elif arg['spot']:
                print('not implemented', file=stderr)
        else:  # create order
            tif = tifs[arg['--tif']]
            if arg['<side>'].strip().lower() in sides:
                side = sides[arg['<side>'].strip().lower()]
            else:  # side is wrong
                print('error: side should be either "buy|long" or "sell|short"'\
                      ' not', arg['side'], file=stderr)
            quantity = float(arg['<quantity>'])
            if arg['--limit']:
                if arg['--limit']:
                    price = float(arg['--limit'])
                    type_ = types['limit']
                    if arg['--test']:
                        print(
                            client.create_test_order(symbol=symbol,
                                                     side=side,
                                                     quantity=quantity,
                                                     price=price,
                                                     timeInForce=tif,
                                                     type=type_))
                    else:  # actually send the order
                        if arg['futures']:
                            print(
                                client.futures_create_order(
                                    symbol=symbol,
                                    side=side,
                                    quantity=quantity,
                                    price=price,
                                    timeInForce=tif,
                                    reduceOnly=arg['--reduce-only'],
                                    timestamp=timemilli(),
                                    type=type_))
                        elif arg['spot']:
                            print(
                                client.create_order(symbol=symbol,
                                                    side=side,
                                                    quantity=quantity,
                                                    price=price,
                                                    timeInForce=tif,
                                                    type=type_))
                else:  # limit given but price not
                    print('please provide --limit \033[33m<price>\033[0m.')
            elif arg['--market']:
                type_ = types['market']
                if arg['--test']:
                    print(
                        client.create_test_order(symbol=symbol,
                                                 side=side,
                                                 quantity=quantity,
                                                 type=type_))
                else:  # actually send the order
                    if arg['futures']:
                        print(
                            client.futures_create_order(
                                symbol=symbol,
                                side=side,
                                quantity=quantity,
                                timestamp=timemilli(),
                                reduceOnly=arg['--reduce-only'],
                                type=type_))
                    elif arg['spot']:
                        print(
                            client.create_order(symbol=symbol,
                                                side=side,
                                                quantity=quantity,
                                                price=price,
                                                type=type_))
            else:  # limit or market not given
                print('please provide either '\
                      '\033[33m --limit <price>\033[0m '\
                      'or \033[33m--market\033[0m', file=stderr)

    else:  # no arguments given
        print(__doc__, file=stderr)
        return 1
date = datetime.date.today()
#binance keys
apikey = "APIKEY"
secretkey = "SECRETKEY"
#nicehash keys and declarations
niceapikey = 'NICEHASHPUBLICKEY'
nicesecretkey = 'NICEHASHPRIVATEKEY'

host = 'https://api2.nicehash.com'

private_api = nicehash.private_api(host, '', niceapikey, nicesecretkey, True)
btcbalance = private_api.get_accounts_for_currency('BTC')['totalBalance']

global fbalance
client = Client(apikey, secretkey)
fbalance = client.futures_account_balance()[0]['balance']
#use historical trade data, write to sheet and calculate average pNl per trade, maybe median? some kind of averadgeing. weighted average? 

def req(client,priv):
    global row
    global date
    global fbalance
    #requests price
    r = requ.get('https://api.coindesk.com/v1/bpi/currentprice.json', auth=('user','pass'))
    i = json.loads(r.text)
    price = i['bpi']['USD']['rate_float']
    fbalance = client.futures_account_balance()[0]['balance']

    #gets values of high and low    
    d = sheet.values().get(spreadsheetId=SPREADSHEET_ID,range=f'A{row}').execute()
    hl = sheet.values().get(spreadsheetId=SPREADSHEET_ID,range=f'E{row}:F{row}').execute()
if abs(float(position["positionAmt"])) < 0.001:
    holding = 0
    holdingBTC = 0
    lastbuy = 0
    lastsell = 0
elif float(position['liquidationPrice']) < float(position['entryPrice']):
    holding = 1
    holdingBTC = float(position['positionAmt'])
    lastbuy = float(position['entryPrice'])
    lastsell = 0
else:
    holding = -1
    holdingBTC = float(position['positionAmt']) * -1
    lastbuy = 0
    lastsell = float(position['entryPrice'])
holdingUSDT = float(client.futures_account_balance()[0]["balance"])
equity = holdingUSDT / 85.0 * 100
print(f"Started program at {datetime.today()}")
if holding == 0:
    print("No position")
elif holding == 1:
    print(f"Long {holdingBTC} BTC")
elif holding == -1:
    print(f"Short {holdingBTC} BTC")
print(" ")

short_MA_duration = tuning.short_MA_duration
long_MA_duration = tuning.long_MA_duration
long_enter_s = tuning.long_enter_s
long_exit_s = tuning.long_exit_s
short_enter_s = tuning.short_enter_s
import os

from binance.client import Client

# init
api_key = os.environ.get('binance_api')
api_secret = os.environ.get('binance_secret')

client = Client(api_key, api_secret)

## main

# get balances for all assets & some account information
print(client.get_account())

# get balance for a specific asset only (BTC)
print(client.get_asset_balance(asset='BTC'))

# get balances for futures account
print(client.futures_account_balance())

# get balances for margin account
# will raise an exception if margin account is not activated
#print(client.get_margin_account())
Beispiel #10
0
class BinanceAPI:
    def __init__(self, api_key, api_secret):
        API_KEY = api_key
        API_SECRET = api_secret

        self.client = Client(API_KEY, API_SECRET)

    def get_ticker(self, pair):
        try:
            value = self.client.get_ticker(symbol=pair)
            return value
        except Exception as e:
            print("Exception : " + str(e))

    def get_current_price(self, pair):
        try:
            ticker = self.client.get_symbol_ticker(symbol=pair)
            value = ticker["price"]
            return float(value)
        except Exception as e:
            print("Exception : " + str(e))

    def get_klines(self, pair, number):
        try:
            klines = pd.DataFrame(
                self.client.get_klines(symbol=pair,
                                       interval=Client.KLINE_INTERVAL_30MINUTE,
                                       limit=number),
                columns=[
                    "OpenTime", "Open", "High", "Low", "Close", "Volume",
                    "CloseTime", "QuoteVolume", "TradeCount", "TakerVolume",
                    "TakerQuoteVolume", "Ignore"
                ])
            value = klines[[
                "OpenTime", "Close", "High", "Low", "Volume", "QuoteVolume",
                "TakerVolume", "TakerQuoteVolume", "TradeCount"
            ]].copy()
            value.loc[:, "OpenTime"] = pd.to_datetime(value["OpenTime"].apply(
                lambda x: datetime.fromtimestamp(int(x / 1000))))
            value = value.set_index("OpenTime")
            return value
        except Exception as e:
            print("Exception : " + str(e))

    def get_historical_klines(self, pair, start, end):
        try:
            klines = pd.DataFrame(self.client.get_historical_klines(
                start_str=start,
                end_str=end,
                symbol=pair,
                interval=Client.KLINE_INTERVAL_30MINUTE,
                limit=500),
                                  columns=[
                                      "OpenTime", "Open", "High", "Low",
                                      "Close", "Volume", "CloseTime",
                                      "QuoteVolume", "TradeCount",
                                      "TakerVolume", "TakerQuoteVolume",
                                      "Ignore"
                                  ])
            value = klines[[
                "OpenTime", "Close", "High", "Low", "Volume", "QuoteVolume",
                "TakerVolume", "TakerQuoteVolume", "TradeCount"
            ]].copy()
            value.loc[:, "OpenTime"] = pd.to_datetime(value["OpenTime"].apply(
                lambda x: datetime.fromtimestamp(int(x / 1000))))
            value = value.set_index("OpenTime")
            return value
        except Exception as e:
            print("Exception : " + str(e))

    def get_balance(self, symbol):
        try:
            value = self.client.get_asset_balance(asset=symbol)
            return value
        except Exception as e:
            print('Exception : {}'.format(e))

    def get_free_balance(self, symbol):
        try:
            value = self.client.get_asset_balance(asset=symbol)
            return float(value["free"])
        except Exception as e:
            print('Exception : {}'.format(e))

    def get_futures_balance(self, symbol):
        try:
            value = self.client.futures_account_balance()
            balance = [
                balance["balance"] for balance in value
                if balance["asset"] == symbol
            ]
            return float(str(*balance))
        except Exception as e:
            print('Exception : {}'.format(e))

    def create_limit_order(self, symbol, price, quantity, side_str):
        try:
            if side_str == "BUY":
                side = self.client.SIDE_BUY
            elif side_str == "SELL":
                side = self.client.SIDE_SELL
            order = self.client.order_limit(
                symbol=symbol,
                side=side,
                timeInForce=self.client.TIME_IN_FORCE_IOC,
                price=price,
                quantity=quantity)
            print(order)
            print(
                "buy order created.\nSymbol:{0:5}\nPrice:{1:5}\nQuantity:{2:5}",
                symbol, price, quantity)
        except Exception as e:
            print("Exception : " + str(e))

    def create_market_order(self, symbol, quantity, side_str):
        try:
            if side_str == "BUY":
                side = self.client.SIDE_BUY
            elif side_str == "SELL":
                side = self.client.SIDE_SELL
            order = self.client.order_market(symbol=symbol,
                                             side=side,
                                             quantity=quantity)
            print(order)
            print(
                "buy order created.\nSymbol:{0:5}\nPrice:{1:5}\nQuantity:{2:5}",
                symbol, price, quantity)
        except Exception as e:
            print("Exception : " + str(e))

    def create_test_order(self, symbol, quantity, side_str):
        try:
            if side_str == "BUY":
                side = self.client.SIDE_BUY
            elif side_str == "SELL":
                side = self.client.SIDE_SELL
            order = self.client.create_test_order(
                symbol=symbol,
                side=side,
                type=self.client.ORDER_TYPE_MARKET,
                quantity=quantity)
            print(order)
            print("buy order created.\nSymbol:{0:5}\nQuantity:{1:5}".format(
                symbol, quantity))
        except Exception as e:
            print("Exception : " + str(e))

    def create_futures_order(self, symbol, quantity, side_str):
        try:
            if side_str == "BUY":
                side = self.client.SIDE_BUY
            elif side_str == "SELL":
                side = self.client.SIDE_SELL
            order = self.client.futures_create_order(
                symbol=symbol,
                side=side,
                type=self.client.ORDER_TYPE_MARKET,
                quantity=quantity)
            #print(order)
            print("order created.\nSymbol:{0:5}\nQuantity:{1:5}".format(
                symbol, quantity))
        except Exception as e:
            print("Exception : " + str(e))

    def create_futures_stoploss_order(self, symbol, quantity, side_str, price):
        if side_str == "BUY":
            side = self.client.SIDE_BUY
        elif side_str == "SELL":
            side = self.client.SIDE_SELL
        order = self.client.futures_create_order(symbol=symbol,
                                                 stopPrice=price,
                                                 side=side,
                                                 type="STOP_MARKET",
                                                 quantity=quantity)
        #print(order)
        #print("order created.\nSymbol:{0:5}\nQuantity:{1:5}".format(symbol,quantity))

    def cancel_futures_orders(self, symbol):
        for i in range(0, 50):
            try:
                self.client.futures_cancel_all_open_orders(symbol=symbol)
            except Exception as e:
                print("Exception : " + str(e))
                continue
            break

    def get_open_futures_orders(self, symbol):
        try:
            result = self.client.futures_get_open_orders(symbol=symbol)
            return result
        except Exception as e:
            print("Exception : " + str(e))

    def get_base_asset(self, symbol):
        try:
            return self.client.get_symbol_info(symbol)["baseAsset"]
        except Exception as e:
            print("Exception : " + str(e))

    def get_quote_asset(self, symbol):
        try:
            return self.client.get_symbol_info(symbol)["quoteAsset"]
        except Exception as e:
            print("Exception : " + str(e))

    def get_all_tickers(self):
        try:
            return self.client.get_all_tickers()
        except Exception as e:
            print("Exception : " + str(e))

    def get_all_orders(self):
        try:
            return self.client.get_all_orders()
        except Exception as e:
            print("Exception : " + str(e))

    def get_trades_data(self, symbol, start, end):
        try:
            data = []
            value = self.client.get_aggregate_trades(symbol=symbol,
                                                     startTime=start,
                                                     endTime=end)
            value_max = [-float('inf'), -float('inf')]
            value_min = [float('inf'), float('inf')]
            #price = self.client.get_historical_klines(start_str = start, end_str = start + 60000, symbol=symbol, interval=Client.KLINE_INTERVAL_1MINUTE, limit=1)[0][1]
            for i in value:
                if len(data) == const.IMG_LENGTH:
                    break
                data.append(
                    [float(i["p"]),
                     float(i["q"]), 0.3 if i["m"] else 0.6])
            if len(data) < const.IMG_LENGTH:
                data += [[0.0, 0.0, 0.0]] * (const.IMG_LENGTH - len(data))
            data = data[:const.IMG_LENGTH]
            data = pd.DataFrame(data)
            data = (data - data.min()) / (data.max() - data.min())
            data = (data - data.mean()) / data.std()
            data = (data - data.min()) / (data.max() - data.min())
            return data.values.tolist()
        except Exception as e:
            print("Exception : " + str(e))
            data = []
            data += [[0.0, 0.0, 0.0]] * (const.IMG_LENGTH)
            return data