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)
def close_trade(self, trade: Trade, reason: str, ohlcv: OHLCV) -> None: """ :param trade: Trade model, trade to close :type trade: Trade :param reason: Reason for the trade to be closed (SL, ROI, Sell Signal) :type reason: string :param ohlcv: Last candle :type ohlcv: OHLCV model :return: None :rtype: None """ trade.status = 'closed' trade.sell_reason = reason trade.close = trade.current date = datetime.fromtimestamp(ohlcv.time / 1000) trade.closed_at = date self.budget += (trade.close * trade.amount) self.open_trades.remove(trade) self.closed_trades.append(trade) self.update_drawdowns_closed_trade(trade)
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)
def check_stoploss_open_trade(self, trade: Trade, ohlcv: OHLCV) -> bool: """ :param trade: Trade model to check :type trade: Trade model :param ohlcv: last candle :type ohlcv: OHLCV model :return: return whether to close the trade based on Stop Loss :rtype: boolean """ if trade.profit_percentage < 0: if trade.max_drawdown is None or trade.max_drawdown > trade.profit_percentage: trade.max_drawdown = trade.profit_percentage if trade.profit_percentage < float(self.config['stoploss']): self.close_trade(trade, reason="Stoploss", ohlcv=ohlcv) return True return False
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)
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,
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,
def replace_trades(self, trades): if len(trades): Trade.replace_many(UserTradeTaskMinix.trade_cols, trades)
def save_trades(self, trades): if len(trades): Trade.save_many(UserTradeTaskMinix.trade_cols, trades)
def trade_product(code, num, price): Trade.trade(code, num, price)