DBTV
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © atchart

//@version=5

// @description TODO: add library description here
library("DBTV", overlay=true)

is_stock() =>
    var stocks = array.from("KRX", "NASDAQ", "ARCA", "AMEX", "NYSE")
    array.includes(stocks, syminfo.prefix)

is_korea_stock() =>
    syminfo.prefix == "KRX"

is_us_stock() =>
    var stocks = array.from("NASDAQ", "ARCA", "AMEX", "NYSE")
    array.includes(stocks, syminfo.prefix)

is_crypto() =>
    (syminfo.type == "crypto") 
 
is_futures() => 
    code = switch syminfo.prefix
        "BINANCE"   => ".P"
        "BYBIT"     => ".P"
        "BITGET"    => ".P"
        "UPBIT"     => "PERP"
        "OKX"       => ".P"
        =>".P"
    is_crypto() and str.endswith(syminfo.ticker, code)

is_spot() =>
    is_crypto() and (not is_futures())

get_exchange_and_code() =>
    is_stock = is_stock()    
    code = is_stock ? syminfo.currency : str.replace(syminfo.ticker, syminfo.basecurrency, "", 0)
    [syminfo.prefix, code]

get_ordertype_and_orderqty_and_orderprice_and_ordername() =>
    ["{{strategy.order.action}}", "{{strategy.order.contracts}}", "{{strategy.order.price}}", "{{strategy.order.comment}}"]


// @function            Create a buy order message for ATCT
// @param accnt_no      (string) [Optional] The number of account.
// @param password      (string) [Optional] The password of account.
// @param orderqty      (float)  [Optional] The orderqty for sell based on your wallet balance.
// @param orderkind     (string) [Optional] The orderkind for order price.

// @returns             (string) A string containing the formatted webhook message.
buy_order(string accnt_no = na, string password=na, int orderqty=na, string orderkind = "limit") =>
    [exchange, code] = get_exchange_and_code()
    [ordertype, strqty, orderprice, ordername] = get_ordertype_and_orderqty_and_orderprice_and_ordername()
    //order_qty = str.tonumber(strqty)
    if not na(orderqty)
        strqty := str.tostring(orderqty)

    json =  '{'
             + str.format(         
			 '
				 "accnt_no": "{0}",
				 "password":"{1}", 
			     "ordername":"{2}",                 
                 "exchange":"{3}",                 
                 "code":"{4}",
                 "ordertype":"{5}",
				 "orderkind":"{6}",
                 "orderqty":"{7}",
                 "orderprice":"{8}"   
             ', accnt_no, password, ordername, exchange, code, ordertype, orderkind, orderqty, orderprice) 
             +'}'
    json


// @function            Create a sell order message for ATCT
// @param accnt_no      (string) [Optional] The number of account.
// @param password      (string) [Optional] The password of account.
// @param orderqty      (float)  [Optional] The orderqty for sell based on your wallet balance.
// @param orderkind     (string) [Optional] The orderkind for order price.

// @returns             (string) A string containing the formatted webhook message.
sell_order(string accnt_no = na, string password=na, int orderqty=na, string orderkind = "limit") =>
    [exchange, code] = get_exchange_and_code()
    [ordertype, strqty, orderprice, ordername] = get_ordertype_and_orderqty_and_orderprice_and_ordername()
    //order_qty = str.tonumber(strqty)
    if not na(orderqty)
        strqty := str.tostring(orderqty)

    json =  '{'
             + str.format(         
			 '
				 "accnt_no": "{0}",
				 "password":"{1}", 
			     "ordername":"{2}",                 
                 "exchange":"{3}",                 
                 "code":"{4}",
                 "ordertype":"{5}",
				 "orderkind":"{6}",
                 "orderqty":"{7}",
                 "orderprice":"{8}"   
             ', accnt_no, password, ordername, exchange, code, ordertype, orderkind, orderqty, orderprice) 
             +'}'
    json

// @function            Create a entry order message for ATCT
// @param accnt_no      (string) [Optional] The number of account.
// @param password      (string) [Optional] The password of account.
// @param orderqty      (float)  [Optional] The orderqty for sell based on your wallet balance.
// @param orderkind     (string) [Optional] The orderkind for order price.

// @returns             (string) A string containing the formatted webhook message.
entry_order(string accnt_no = na, string password=na, int orderqty=na, string orderkind = "limit") =>
    [exchange, code] = get_exchange_and_code()
    [ordertype, strqty, orderprice, ordername] = get_ordertype_and_orderqty_and_orderprice_and_ordername()
    //order_qty = str.tonumber(strqty)
    if not na(orderqty)
        strqty := str.tostring(orderqty)

	username = '트레이딩뷰봇'
	content  = 'entry_order'
    embedColor = "red"
    timestamp  = str.format_time(time, "yyyy-MM-dd HH:mm")

    json =  str.format('{{"username": "{0}", "content": "{1}", "embeds": [{{"title": "{2}", "color": "{3}", "timestamp": "{4}"" }}] }}', username, content, ordername, embedColor, timestamp)

    


///////////////////////// EXPORT //////////////////////////////////////

// @function            Create a entry message for ATCHART
// @param password      (string) [Optional] The password of your bot.
// @param percent       (float)  [Optional] The percent for entry based on your wallet balance.
// @param leverage      (int)    [Optional] The leverage of entry. If not set, your levereage doesn't change.
// @param margin_mode   (string) [Optional] The margin mode for trade(only for OKX). "cross" or "isolated"
// @param accnt_no      (string) [Optional] The number of security account. Default 1
// @returns             (string) A json formatted string for webhook message.

export entry_msg(string accnt_no=na, string password=na, int orderqty = na, string orderkind = "limit") => 
    is_buy = is_stock() or is_spot()
    is_buy  ? buy_order(accnt_no, password, orderqty, orderkind) : entry_order(accnt_no, password, orderqty, orderkind)
