def task_current_futures():
    engine.dispose()

    while app.running:
        try:
            spot_order = None

            best_position = [
                row for row in model_service.get_current_ratios()
            ][0]

            print("Abro posiciĆ³n", best_position)

            spot_symbol = best_position['spot_symbol']
            buy_per_contract = best_position['buy_per_contract']
            tick_size = best_position['tick_size']

            quantity_to_buy = buy_per_contract * SPOT_BUY_OVERBUY_MARGIN * MIN_NUMBER_OF_CONTRACTS
            quantity_to_buy = utils.get_quantity_rounded(
                quantity_to_buy, tick_size)

            spot_order = binance_client.order_market_buy(
                symbol=spot_symbol, quantity=quantity_to_buy)

            model_service.save_spot_order(best_position, spot_order)

        except Exception as ex:
            print("Error al crear posicion")
            print(best_position, spot_order)
            print(ex)
            traceback.print_stack()
Example #2
0
def task_operation_spot_buy():
    while app.running:
        try:
            best_position = None
            spot_order = None

            best_positions = [
                row for row in model_service.get_current_ratios_to_open()
            ]

            if len(best_positions):
                best_position = best_positions[0]

                spot_symbol = best_position['spot_symbol']
                buy_per_contract = best_position['buy_per_contract']
                tick_size = best_position['tick_size']
                contract_qty = best_position['contract_qty']
                future_balance = best_position['future_balance']

                quantity_to_buy = buy_per_contract * SPOT_BUY_OVERBUY_MARGIN * contract_qty - future_balance
                quantity_to_buy = utils.get_quantity_rounded(
                    quantity_to_buy, tick_size)

                resetSpotBalance("USDT")

                spot_order = binance_client.order_market_buy(
                    symbol=spot_symbol, quantity=quantity_to_buy)

                save_operation_buy_spot(best_position, spot_order)

        except Exception as ex:
            print("Error comprar spot")
            print(best_position, spot_order)
            print(ex)
            traceback.print_stack()
Example #3
0
def get_pending_transfers():
    pending_transfers = []

    with Session(engine) as session, session.begin():
        future_operations = session.query(model.Operation). \
            join(model.Operation.future_relation). \
            join(model.Future.balance). \
            filter(model.Operation.kind == 'CLOSE'). \
            filter(model.Operation.state == 'FUTURE_BUY'). \
            filter(model.FutureBalance.outdated == False). \
            all()

        if len(future_operations):
            for future_operarion in future_operations:
                transfer = {
                    'operation_id':
                    future_operarion.id,
                    'type':
                    'CMFUTURE_MAIN',
                    'asset':
                    future_operarion.future_relation.base_asset,
                    'amount':
                    utils.get_quantity_rounded(
                        future_operarion.future_relation.balance.
                        cross_wallet_balance,
                        future_operarion.spot_relation.tick_size),
                    'next_state':
                    'FUTURE_TRANSFER'
                }

                pending_transfers.append(transfer)
        else:
            spot_orders = session.query(model.SpotOrder). \
                join(model.SpotOrder.operation). \
                join(model.SpotOrder.spot). \
                filter(model.Operation.state == 'SPOT_BUY'). \
                filter(model.SpotOrder.status == 'FILLED'). \
                all()

            # OPEN_POSITION_TRANSFER_TYPE = 'MAIN_CMFUTURE'
            # CLOSE_POSITION_TRANSFER_TYPE = 'CMFUTURE_MAIN'

            for spot_order in spot_orders:
                transfer = {
                    'operation_id': spot_order.operation_id,
                    'type': 'MAIN_CMFUTURE',
                    'asset': spot_order.spot.base_asset,
                    'amount': spot_order.executed_qty,
                    'next_state': 'SPOT_TRANSFER'
                }

                pending_transfers.append(transfer)

    return pending_transfers
Example #4
0
def open_position(position_dict: Dict):
    spot_order = None
    spot_order_update = None
    spot_trade = None
    transfer = None
    future_order = None
    future_order_update = None
    future_trade = None

    try:
        spot_symbol = position_dict['spot_symbol']
        future_symbol = position_dict['future_symbol']
        buy_per_contract = position_dict['buy_per_contract']
        tick_size = position_dict['tick_size']
        base_asset = position_dict['base_asset']
        contract_qty = position_dict['contract_qty']

        quantity_to_buy = buy_per_contract * config.SPOT_BUY_OVERBUY_MARGIN * contract_qty
        quantity_to_buy = utils.get_quantity_rounded(quantity_to_buy, tick_size)

        spot_order = binance_client.order_market_buy(symbol=spot_symbol, quantity=quantity_to_buy)

        spot_order_id = spot_order['orderId']

        spot_trade = binance_service.get_spot_trade(spot_symbol, spot_order_id, quantity_to_buy)

        # check real ammount to transfer based on trades
        transfer = binance_client.universal_transfer(type=OPEN_POSITION_TRANSFER_TYPE, asset=base_asset, amount=quantity_to_buy)

        future_order = binance_client.futures_coin_create_order(symbol=future_symbol, side="SELL", type="MARKET", quantity=MIN_NUMBER_OF_CONTRACTS)

        future_order_id = future_order['orderId']

        spot_order_update = binance_service.get_spot_order(spot_symbol, spot_order_id)

        future_order_update = binance_service.get_future_order(future_symbol, future_order_id)

        future_trade = binance_service.get_future_trade(future_symbol, future_order_id, MIN_NUMBER_OF_CONTRACTS)

    except Exception as ex:
        print(ex)
        traceback.print_exc()

    return {
        'position': position_dict,
        'spot_order': spot_order,
        'spot_order_update': spot_order_update,
        'spot_trade': spot_trade,
        'transfer': transfer,
        'future_order': future_order,
        'future_order_update': future_order_update,
        'future_trade': future_trade,
    }
Example #5
0
def get_operations_to_sell_spots():
    results = []

    with Session(engine) as session, session.begin():
        operations = session.query(model.Operation).\
            join(model.Operation.transfer).\
            filter(model.Operation.state == 'FUTURE_TRANSFER').all()

        for operation in operations:
            results.append({
                'operation_id':
                operation.id,
                'spot_symbol':
                operation.spot,
                'qty':
                utils.get_quantity_rounded(operation.transfer.amount,
                                           operation.spot_relation.tick_size)
            })

    return results
Example #6
0
def close_position(position_dict: Dict, verify_steps = False):
    spot_order = None
    spot_order_update = None
    spot_trade = None
    transfer = None
    future_order = None
    future_order_update = None
    future_trade = None

    try:
        spot_symbol = position_dict['spot_symbol']
        future_symbol = position_dict['future_symbol']
        tick_size = position_dict['tick_size']
        base_asset = position_dict['base_asset']
        contract_qty = position_dict['contract_qty']
        transfer_amount = position_dict['transfer_amount']

        sell_future_base_qty = position_dict['future_base_qty']
        sell_future_commission = position_dict['future_commission']



        if verify_steps == True:
            position_id = position_dict['position_id']

            future_order_id = 1

            future_order_update = binance_service.get_future_order(future_symbol, future_order_id)
        else:
            future_order = binance_client.futures_coin_create_order(symbol=future_symbol, side="BUY", type="MARKET",
                                                                    quantity=contract_qty)

        future_order_id = future_order['orderId']

        future_trade = binance_service.get_future_trade(future_symbol, future_order_id, contract_qty)

        buy_future_base_qty = sum([float(ft['baseQty']) for ft in future_trade])
        buy_future_commission = sum([float(ft['commission']) for ft in future_trade])

        quantity_to_sell = transfer_amount - sell_future_base_qty - sell_future_commission + buy_future_base_qty - buy_future_commission
        quantity_to_sell = utils.get_quantity_rounded(quantity_to_sell, tick_size)

        transfer = binance_client.universal_transfer(type=CLOSE_POSITION_TRANSFER_TYPE, asset=base_asset, amount=quantity_to_sell)

        spot_order = binance_client.order_market_sell(symbol=spot_symbol, quantity=quantity_to_sell)

        spot_order_id = spot_order['orderId']

        spot_trade = binance_service.get_spot_trade(spot_symbol, spot_order_id, quantity_to_sell)

        spot_order_update = binance_service.get_spot_order(spot_symbol, spot_order_id)

        future_order_update = binance_service.get_future_order(future_symbol, future_order_id)

    except Exception as ex:
        print(ex)
        traceback.print_exc()

    return {
        'position': position_dict,
        'spot_order': spot_order,
        'spot_order_update': spot_order_update,
        'spot_trade': spot_trade,
        'transfer': transfer,
        'future_order': future_order,
        'future_order_update': future_order_update,
        'future_trade': future_trade,
    }
Example #7
0
        'operation_id': operation_id,
        **future_order_update
    })

    for trade in (future_trade or []):
        model_service.save_future_trade({
            'future_order_id': future_order_id,
            **trade
        })


if __name__ == '__main__':
    transfer_amount = 0.483

    future_trade = binance_service.get_future_trade("DOTUSD_210625", 518223677, 2)

    print(future_trade)

    realized_pnl_sum = sum([float(ft['realizedPnl']) for ft in future_trade])

    quantity_to_sell = transfer_amount + realized_pnl_sum

    quantity_to_sell = utils.get_quantity_rounded(quantity_to_sell, 0.001)

    print(quantity_to_sell)

    quantity_to_sell = utils.get_quantity_rounded(0.48566470999999994, 0.001)

    print(quantity_to_sell)