Beispiel #1
0
    def open_trade(self, ohlcv: OHLCV) -> None:
        """
        Method opens a trade for pair in ohlcv

        :param ohlcv: last OHLCV model (candle)
        :type ohlcv: OHLCV model
        :return: None
        :rtype: None
        """
        if self.budget <= 0:
            print("[INFO] Budget is running low, cannot buy")
            return

        date = datetime.fromtimestamp(ohlcv.time / 1000)
        open_trades = len(self.open_trades)
        available_spaces = self.max_open_trades - open_trades
        amount = ((100 / available_spaces) / 100) * self.budget
        self.budget-=amount
        new_trade = Trade()
        new_trade.pair = ohlcv.pair
        new_trade.open = ohlcv.close
        new_trade.current = ohlcv.close
        new_trade.status = "open"
        new_trade.amount = (amount / ohlcv.close)
        new_trade.opened_at = date
        self.open_trades.append(new_trade)
Beispiel #2
0
    def test_add(self):
        product = Product()
        product.title = "title"
        product.descr = "desc"
        product.type = ProductType.MATERIAL
        product.updated_at = product.inserted_at = util.utcnow()
        self.db.add(product)

        trade = Trade()
        trade.trade_id = self.gen_uid()
        trade.timeout = "1d"
        trade.fee = 0.01
        trade.status = TradeStatus.PENDING
        trade.channel = ChannelType.WAP
        trade.show_url = "url"
        trade.updated_at = trade.inserted_at = util.utcnow()
        trade.product = product

        self.db.add(trade)
        self.db.commit()
        self.assertTrue(True)
Beispiel #3
0
    def get(self):
        trade_id = self.valid("trade_id")
        title = self.valid("title")
        fee = self.valid("fee", force_type=float,
                         validator=RangeValidator(0.01, 100000000).validate)
        show_url = self.valid("show_url")
        # Minutes as the calculating unit.
        timeout = self.valid("timeout", force_type=int)

        # Optional arguments
        descr = self.valid("descr", required=False)
        type_ = self.valid("type", required=False) or ProductType.MATERIAL

        if self.errors:
            reason=self.errors.values()[0]
            raise HTTPError(422, "Validation Failed", reason=reason)

        # Validate `trade_id` unique.
        is_unique = TradeMgr.is_unique(self.db, trade_id)
        logging.info("trade id:{} is_unique:{}".format(trade_id, is_unique))
        if not is_unique:
          reason = "Trade ID is not unique"
          raise HTTPError(422, "Validation Failed", reason=reason)

        timeout = "{}m".format(str(timeout))

        notify_url = self.notify_host + URL_WAP_PAY_NOTIFY
        alipay = AliWapPay(notify_url=notify_url,
                           app_id=config.ali_app_id,
                           private_key_path=config.private_key_path,
                           sign_type= config.ali_sign_type,
                           seller_id=config.ali_seller_id
                           )

        # Create trade URL query string.
        product_info = {"title": title, "type": type_, "descr": descr}
        callback_url = self.host + URL_WAP_PAY_CALLBACK
        trade_qs = alipay.create_trade(trade_id,
                                       fee,
                                       timeout,
                                       callback_url,
                                       product_info
                                       )

        utcnow = util.utcnow()
        product = Product(title=title,
                          descr=descr,
                          type=type_,
                          updated_at=utcnow,
                          inserted_at=utcnow
                          )
        trade = Trade(trade_id=trade_id,
                      fee=fee,
                      status=TradeStatus.PENDING,
                      channel=ChannelType.WAP,
                      show_url=show_url,
                      inserted_at=utcnow,
                      updated_at=utcnow,
                      timeout=timeout,
                      product=product
                      )

        self.db.add_all([product, trade])
        self.db.commit()
        self.finish(config.ali_gateway + "?" + trade_qs)
Beispiel #4
0
from models.trade import Trade

list_trades = [
    Trade(
        name_of_asset="AAPL",
        asset_price=50,
        qty_purchased=1,
        total_trade_value=50,
        transaction_type="buy",
        stock_id=1,
        user_id=1,
        asset_type='stocks'
    ),
    Trade(
        name_of_asset="AAPL",
        asset_price=50,
        qty_purchased=3,
        total_trade_value=150,
        transaction_type="buy",
        stock_id=1,
        user_id=1,
        asset_type='stocks'
    ),
    Trade(
        name_of_asset="GOOG",
        asset_price=100,
        qty_purchased=1,
        total_trade_value=100,
        transaction_type="buy",
        stock_id=2,
        user_id=1,
Beispiel #5
0

if __name__ == '__main__':
    args = get_args()
    # Only set the GPU to be used visible, and so just specify cuda:0 as the device
    os.environ["CUDA_VISIBLE_DEVICES"] = args['cuda']
    device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
    iprint('Using device = {}'.format(device))

    (train_dataloader, dev_dataloader, test_dataloader, test_special, vocabs,
     slots_dict, max_word) = get_all_data(args=args,
                                          training=True,
                                          batch_size=args['batch'])

    model = Trade(args=args,
                  device=device,
                  slots_dict=slots_dict,
                  vocabs=vocabs)
    model = model.to(device=device)

    criterion_ptr = nn.CrossEntropyLoss(ignore_index=PAD_TOKEN)
    criterion_gate = nn.CrossEntropyLoss()
    optimizer = torch.optim.Adam(model.parameters(), lr=args['learning_rate'])
    scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer,
                                                           mode='max',
                                                           factor=0.5,
                                                           patience=1,
                                                           min_lr=0.0001,
                                                           verbose=True)

    train_model(model=model,
                device=device,