Can't close position with ccxt bybit create_order - ccxt

Can't close my position. Exemple here with an actual 'side': 'long' on bybit.
ccxt version: 2.4.70
PAIR use 'ETH/USDT:USDT'
def place_market_order(self, symbol, side, amount, reduce=False):
try:
return self._session.create_order(
symbol,
'market',
side,
self.convert_amount_to_precision(symbol, amount),
None,
params={'reduceOnly': reduce},
)
except BaseException as err:
raise Exception(err)
bybit.place_market_order(pair, "sell", close_long_quantity, reduce=True)
TypeError: PerpBybit.authentication_required.<locals>.wrapped() got an unexpected keyword argument 'reduce'
I am not sure i am using the good function on ccxt.bybit. But i am confused of which one use so.
In the ccxt/bybit.py create_order has not 'reduceOnly' param. But other has it like
.create_contract_v3_order()
.create_unified_margin_order()
.create_usdc_order()
.create_spot_order()

Related

Having error "got an unexpected keyword argument" and can't fix it

Good day to everyone, I have been writing a simple bot to delete messages from one group and to forward them to another, so while executing I am facing this error, it says "TeleBot.forward_message() got an unexpected keyword argument 'chatid'"
I am new to bot making so any help would be appreciated
Here is my code
import telebot
from telebot import types
bot = telebot.TeleBot('tocken')
#bot.message_handler(commands=['start'])
def start(message):
bot.send_message(message.chat.id, 'Hi, ready to delete')
if ':' not in message.text:
bot.forward_message(chatid='group chat id',
fromchatid=message.chat.id, messageid=message.message_id)
bot.delete_message(chatid=message.chat.id, messageid=message.message_id)
bot.polling(none_stop=True)
It seems like you may be missmatching the variable's nomenclature.
Based on PyTelegramBot documentation, forward_message() expects this params:
forward_message(chat_id: Union[int, str], from_chat_id: Union[int,
str], message_id: int, disable_notification: Optional[bool] = None,
protect_content: Optional[bool] = None, timeout: Optional[int] = None,
message_thread_id: Optional[int] = None)
So your chatid should go like chat_id and the same goes with every other param.
Your snippet would go something like this:
bot.forward_message(chat_id='group chat id', from_chat_id=message.chat.id, message_id=message.message_id)
bot.delete_message(chat_id=message.chat.id, message_id=message.message_id)
Note: This nomenclature may be version dependant and was described as current latest (4.9.0).

Telegram Global Search using the raw API function via Telethon

I am trying to use the SearchGlobalRequest API method for global, full-text search on Telegram, but I am not sure what to use for some of the arguments, especially the offset_peer parameter. When I do this:
try:
result = client(SearchGlobalRequest(
q=search_term,
filter=None,
min_date=datetime.datetime.strptime(min_date, '%Y-%m-%d'),
max_date=datetime.datetime.strptime(max_date, '%Y-%m-%d'),
offset_rate=-1,
# offset_peer=None,
offset_id=-1,
limit=10
))
except Exception as e:
print(e)
I get __init__() missing 1 required positional argument: 'offset_peer'.
When I try to pass None as offset_peer, I get Cannot cast NoneType to any kind of Peer. I am not trying to search in any specific channel, I just want to specify the start and end date and find all (or rather as many as possible) matching results.
I am using Telethon version 1.24.0.
Next code works for me:
from telethon.tl.functions.messages import SearchGlobalRequest
from telethon.tl.types import InputMessagesFilterEmpty, InputPeerEmpty
results = client(SearchGlobalRequest(
q='your_query_here',
filter=InputMessagesFilterEmpty(),
min_date=None,
max_date=None,
offset_rate=0,
offset_peer=InputPeerEmpty(),
offset_id=0,
limit=100,
folder_id=None
))
print(results.stringify())

Is there a way I can access the attribute in an Attribute Error without parsing the string?

My python version is 3.6
I am trying to give a more helpful message on attribute errors in a CLI framework that I am building. I have the following code
print(cli_config.test_exension_config.input_menu)
Which produces the error AttributeError: 'CLIConfig' object has no attribute 'test_exension_config'
Perfect, however now I want to give a recommendation on the closest attribute match as the attributes are dynamically created from a yaml file.
test_extension:
input_menu: # "InputMenuConfig_instantiation_test"
var:
So the closest attribute match would be test_extension_config.
Below is me catching the error and about to give a recommendation.
def __getattribute__(self, name) -> Any:
try:
return super().__getattribute__(name)
except AttributeError as ae:
# chance to handle the attribute differently
attr = get_erroring_attr(ae)
closest_match = next(get_close_matches(attr, list(vars(self).keys())))
if closest_match: # probably will have some threshold based on 'edit distance'
return closest_match
# if not, re-raise the exception
raise ae
I am wanting to just receive the attribute
I can parse the args of AttributeError but I wanted to know if there was another way to access the actual attribute name that is erroring without parsing the message.
In other words, in the last code block I have a method get_erroring_attr(ae) that takes in the AttributeError.
What would be the cleanest definition of def get_erroring_attr(ae) that will return the erroring attribute?
UPDATE:
So I did this and it works. I would just like to remove parsing as much as possible.
def __getattribute__(self, name) -> Any:
try:
return super().__getattribute__(name)
except AttributeError as ae:
# chance to handle the attribute differently
attr = self.get_erroring_attr(ae)
closest_match = next(match for match in get_close_matches(attr, list(vars(self).keys())))
if closest_match: # probably will have some threshold based on 'edit distance'
traceback.print_exc()
print(CLIColors.build_error_string(f"ERROR: Did you mean {CLIColors.build_value_string(closest_match)}?"))
sys.exit()
# if not, re-raise the exception
raise ae
def get_erroring_attr(self, attr_error: AttributeError):
message = attr_error.args[0]
_, error_attr_name = self.parse_attr_error_message(message)
return error_attr_name
def parse_attr_error_message(self, attr_err_msg: str):
parsed_msg = re.findall("'([^']*)'", attr_err_msg)
return parsed_msg
Which produces

Zerobrane: fractal-samples: zplane.lua is exiting with an error

I tried out some of the samples coming along with ZeroBraneStudio.
spirograph-samples are working fine. May be there should be also a wait() statement at the end of the livecoding-samples and the fractal-samples. Otherwise the graphic window disappears at the end of execution. For
fractal-samples: zplane.lua I get an error:
Zoom: {1}
Cent: {0,0}
Area: {-2,2,-2,2}
/Applications/ZeroBraneStudio.app/Contents/ZeroBraneStudio/bin/lua.app
/Contents/MacOS/lua: ./fractal.lua:123: attempt to index local 'C' (a nil value)
stack traceback:
./fractal.lua:123: in function 'Draw'
..ts/ZeroBraneStudio/myprograms/fractal-samples/zplane.lua:103: in main chunk
[C]: at 0x00001c80
In my version of fractal.lua there is no reference to C variable on line 123. I'd try a newer version, as I don't see any issue with the execution of zplane.lua with the current version of fractal.lua.

What is the standard code to check for valid/existing id in database-backed view in web2py?

In web2py, suppose I have the following url:
www.example.com/customer/view/1
Which is backed by a view() function in the customer controller and displays the customer with id of 1 from a database.
In the view function I want to handle the following error cases:
No argument is passed (/customer/view/) -> raise 404
A non-integer argument is passed (/customer/view/apple) -> raise 404
An integer argument is passed but does not exist in database (/customer/view/999999) -> raise 404
An application error occurs such as cannot connect to database -> raise 500 exception
What is the standard/canonical/correct way to handle these cases in the controller function in way that returns the proper HTTP error? It's such a common scenario that I'd like to do it in a correct and succinct way every time.
This almost works except it doesn't distinguish between id not valid/existing errors and any other errors:
def view():
try:
customer = db(db.customer.id==request.args(0, cast=int)).select()[0]
except:
raise HTTP(404, 'Cannot find that customer')
return dict(customer=customer)
def view():
id = request.args(0, cast=int, otherwise=lambda: None)
customer = db(db.customer.id == id).select().first()
if not customer:
raise HTTP(404, 'Cannot find that customer' if id
else 'Missing/invalid customer ID')
return dict(customer=customer)
If the cast fails in request.args(), by default it will raise its own HTTP(404), but you won't have control over the message. So, you can instead use the otherwise argument to return None in that case. The database query will then return None if the arg is missing or a non-integer, or if the customer is not found in the database.