Exemple #1
0
def on_candle_close(closes_arr: np.ndarray) -> None:
    """Outputs the closing prices array to the console (for debugging
    purposes), and appends the most recent closing price to a trading data CSV.
    If sufficient data has been collected then a there is the possiblity of
    making a trade, in which case consider_trade will be called.

    Parameters
    ----------
    closes_arr : np.ndarray
        Numpy array of closing prices

    Returns
    -------
    None
    """

    print("\nClosing prices:", closes_arr, "\n")

    if len(closes_arr) >= 2:

        # Updating the trailing stop loss if necessary
        if cur_trading_sess.in_long_position:
            cur_trading_sess.max_price_since_buy = max(
                cur_trading_sess.max_price_since_buy, closes_arr[-1])

        trade_executed = consider_trade(closes_arr)

        col_names = ["datetime_collected", "datetime", "price", "trade_made"]
        row = [
            START_DATETIME, cur_trading_sess.prev_ts,
            cur_trading_sess.prev_price, trade_executed
        ]

        append_data(f"../Trading CSVs/{TRADE_SYMBOL}_data.csv", col_names, row)
Exemple #2
0
def track(yesterday: bool = False):
    """Run whole tracking sequence."""
    print(Colors.BLUE + '   TRACK  ' + Colors.NORMAL + '\n')
    if yesterday:
        print(Colors.YELLOW + 'Tracking for yesterday:\n' + Colors.NORMAL)
    try:
        tod_accomplishments = get_completed_tasks_in_tod()
        entry_dic = user_entry(tod_accomplishments)
    except FileNotFoundError:
        entry_dic = user_entry()
    entry = format_entry(entry_dic, yesterday)
    clear_screen()
    append_data(entry, os.getenv('TRACK_FP'))
    print('Entry recorded.')
Exemple #3
0
def order(symbol: str, side: str, order_type: str, quantity: float,
          closes_arr: np.ndarray) -> bool:
    """Attempts to send the order specified to Binance. If this was successful,
    details of the trade are saved to the trades log CSV, as well as account
    balances and other useful information.

    Parameters
    ----------
    symbol : str
        The symbol (ticker) for the asset to be traded
    side : str
        The side to be traded (representing buying or selling)
    order type : str
        The type of order to be made, e.g. market order
    quantity : float
        The quantity of the aforementioned symbol to be traded
    closes_arr : np.ndarray
        Numpy array of closing prices

    Returns
    -------
    order_was_successful : bool
        Boolean set to true if the order was completed successfully, otherwise
        false.
    """
    order_was_successful = False

    # Using a number of try-except statements, as there are a number of issues
    # that can occur when trying to execute an order, which are otherwise
    # handled by the websocket without displaying any feedback.
    try:
        print("Sending order")
        order = client.create_order(symbol=symbol,
                                    side=side,
                                    type=order_type,
                                    quantity=quantity)
        print("Order successful:", order, "\n\n")

        order_was_successful = True

        # Fetching executed price and quantity, for logs
        try:
            actual_price = order['fills'][0]['price']
            actual_quantity = order['fills'][0]['qty']
            commission = order['fills'][0]['commission']
        except Exception as e:
            actual_price = ""
            actual_quantity = ""
            commission = ""
            print("Error getting order details:", e)

        # Fetching balances of both assets traded, for logs
        try:
            balance_1 = float(client.get_asset_balance(asset=ASSET_1)['free'])
            usd_price_1 = float(
                client.get_avg_price(symbol=f'{ASSET_1}USDT')['price'])
            balance_2 = float(client.get_asset_balance(asset=ASSET_2)['free'])
            if ASSET_1 == "USDT":
                usd_price_2 = 1
            else:
                usd_price_2 = float(
                    client.get_avg_price(symbol=f'{ASSET_1}USDT')['price'])
            balance_usd = balance_1 * usd_price_1 + balance_2 * usd_price_2
        except Exception as e:
            balance_1 = ""
            balance_2 = ""
            balance_usd = ""
            print("Error getting balances:", e)

        col_names = [
            "collection_started_datetime", "order_placed_datetime", "ticker",
            "side", "order_type", "quantity_attempted", "expected_price",
            "actual_price", "actual_quantity", "commission",
            f"{ASSET_1}_balance", f"{ASSET_2}_balance", "total_balance_usd"
        ]
        row = [
            START_DATETIME,
            datetime.now(), symbol, side, order_type, quantity, closes_arr[-1],
            actual_price, actual_quantity, commission, balance_1, balance_2,
            balance_usd
        ]
        append_data(f"../Trading CSVs/{TRADE_SYMBOL}_trades_log.csv",
                    col_names, row)

    except Exception as e:
        print("Order failed:", e, "\n")

    return order_was_successful
Exemple #4
0
def add_to_journal():
    date = datetime.now().strftime("%Y%m%d %H:%M")
    additional = create_formatted_long_journal(set_long_journal())
    append_data(f"\n---\n{date} Note\n\n{additional}", os.getenv('TRACK_FP'))
    print("Note added.")