Need help converting TradingView Pine script from Version 2 to Version 4 - variables

I am new to TradingView Pine scripting. I am working on some study/strategy but currently seeking for help with a pine script which is on version 2 right now but I am trying convert it into Version 4 and is having so many compilation errors.
Below is the complete script I am trying to convert from V2 to V2 and error I am facing.
Script
//#version=4
//Trend Trading Study by MSM *Sanjay.r* Trend Trading Indicator
study("MystockMoney Trend Trading Tool 1.0", overlay=true)
res = input(title="Main MSM Time Frame", type=resolution, defval="120")
Factor=input(1, minval=1,maxval = 100)
Pd=input(1, minval=1,maxval = 100)
tp = input(500,title="Take Profit")
sl = input(200,title="Stop Loss")
//Plots VWAP and MVWAP for intraday trading. Useful to avoid whipsaws
//study("VWAP MVWAP with pivot points", overlay = true)
avlen = input(50)
color1 = blue
color2 = black
mvwap = ema(vwap,avlen)
plot(vwap,linewidth = 2,style = circles, color = color2)
plot(mvwap,color= color1)
Up=hl2-(Factor*atr(Pd))
Dn=hl2+(Factor*atr(Pd))
MUp=security(tickerid,res,hl2-(Factor*atr(Pd)))
MDn=security(tickerid,res,hl2+(Factor*atr(Pd)))
Mclose=security(tickerid,res,close)
TrendUp=close[1]>TrendUp[1]? max(Up,TrendUp[1]) : Up
TrendDown=close[1]<TrendDown[1]? min(Dn,TrendDown[1]) : Dn
MTrendUp=Mclose[1]>MTrendUp[1]? max(MUp,MTrendUp[1]) : MUp
MTrendDown=Mclose[1]<MTrendDown[1]? min(MDn,MTrendDown[1]) : MDn
Trend = close > TrendDown[1] ? 1: close< TrendUp[1]? -1: nz(Trend[1],1)
Tsl = Trend==1? TrendUp: TrendDown
MTrend = Mclose > MTrendDown[1] ? 1: Mclose< MTrendUp[1]? -1: nz(MTrend[1],1)
MTsl = MTrend==1? MTrendUp: MTrendDown
linecolor = Trend == 1 ? green : red
plot(Tsl, color = linecolor , style = line , linewidth = 2,title = "MSM")
Mlinecolor = MTrend == 1 ? blue : orange
plot(MTsl, color = Mlinecolor , style = line , linewidth = 2,title = "Main MSM")
plotshape(cross(close,Tsl) and close>Tsl , "Up Arrow", shape.triangleup,location.belowbar,green,0,0)
plotshape(cross(Tsl,close) and close<Tsl , "Down Arrow", shape.triangledown , location.abovebar, red,0,0)
up = Trend == 1 and Trend[1] == -1 and MTrend == 1
down = Trend == -1 and Trend[1] == 1 and MTrend == -1
plotarrow(up ? Trend : na, title="Up Entry Arrow", colorup=lime, maxheight=60, minheight=50, transp=0)
plotarrow(down ? Trend : na, title="Down Entry Arrow", colordown=red, maxheight=60, minheight=50, transp=0)
golong = Trend == 1 and Trend[1] == -1 and MTrend == 1
goshort = Trend == -1 and Trend[1] == 1 and MTrend == -1
length=input(21, "length", minval=1)
avrg=sma(volume,length)
vold1 = volume > avrg*1.5 and close<open
vold2 = volume >= avrg*0.5 and volume<=avrg*1.5 and close<open
vold3 = volume < avrg *0.5 and close<open
volu1 = volume > avrg*1.5 and close>open
volu2 = volume >= avrg*0.5 and volume<=avrg*1.5 and close>open
volu3 = volume< avrg*0.5 and close>open
cold1=#800000
cold2=#FF0000
cold3=orange
colu1=#006400
colu2=lime
colu3=#7FFFD4
color = vold1 ? cold1 : vold2 ? cold2 : vold3 ? cold3 : volu1 ? colu1 : volu2 ? colu2 : volu3 ? colu3 : na
barcolor(color)
//Code merged for another indicator
sd = input(true, title="Show Daily Pivots?")
//Pivot Range Calculations - Mark Fisher
pivot = (high + low + close ) / 3.0
bc = (high + low ) / 2.0
tc = (pivot - bc) + pivot
r1 = (pivot * 2) - low
s1 = (pivot * 2) - high
r2 = pivot + (high - low)
s2 = pivot - (high - low)
r3 = r1 + (high - low)
s3 = s1 - (high - low)
r4 = r3 + (r2 - r1)
s4 = s3 - (s1 - s2)
//Daily Pivot Range
dtime_pivot = security(tickerid, 'D', pivot[1])
dtime_bc = security(tickerid, 'D', bc[1])
dtime_tc = security(tickerid, 'D', tc[1])
dtime_r1 = security(tickerid, 'D', r1[1])
dtime_r2 = security(tickerid, 'D', r2[1])
dtime_r3 = security(tickerid, 'D', r3[1])
dtime_r4 = security(tickerid, 'D', r4[1])
dtime_s1 = security(tickerid, 'D', s1[1])
dtime_s2 = security(tickerid, 'D', s2[1])
dtime_s3 = security(tickerid, 'D', s3[1])
dtime_s4 = security(tickerid, 'D', s4[1])
offs_daily = 0
plot(sd and dtime_pivot ? dtime_pivot : na, title="Daily Pivot",style=circles, color=blue,linewidth=3)
plot(sd and dtime_bc ? dtime_bc : na, title="Daily BC",style=circles, color=blue,linewidth=3)
plot(sd and dtime_tc ? dtime_tc : na, title="Daily TC",style=circles, color=blue,linewidth=3)
plot(sd and dtime_r1 ? dtime_r1 : na, title="Daily r1",style=circles, color=green,linewidth=3)
plot(sd and dtime_s1 ? dtime_s1 : na, title="Daily s1",style=circles, color=red,linewidth=3)
Errors after compiling above script
Processing script...
line 5: Undeclared identifier 'resolution';
line 18: Undeclared identifier 'blue';
line 19: Undeclared identifier 'black';
line 21: Undeclared identifier 'circles';
line 21: Undeclared identifier 'color2';
line 22: Undeclared identifier 'color1';
line 26: Undeclared identifier 'res';
line 27: Undeclared identifier 'res';
line 29: Undeclared identifier 'res';
line 31: Undeclared identifier 'TrendUp';
line 32: Undeclared identifier 'TrendDown';
line 34: Undeclared identifier 'Mclose';
line 34: Undeclared identifier 'MTrendUp';
line 34: Undeclared identifier 'MUp';
line 35: Undeclared identifier 'Mclose';
line 35: Undeclared identifier 'MTrendDown';
line 35: Undeclared identifier 'MDn';
line 37: Undeclared identifier 'TrendDown';
line 37: Undeclared identifier 'TrendUp';
line 37: Undeclared identifier 'Trend';
line 38: Undeclared identifier 'Trend';
line 38: Undeclared identifier 'TrendUp';
line 38: Undeclared identifier 'TrendDown';
line 40: Undeclared identifier 'Mclose';
line 40: Undeclared identifier 'MTrendDown';
line 40: Undeclared identifier 'MTrendUp';
line 40: Undeclared identifier 'MTrend';
line 41: Undeclared identifier 'MTrend';
line 41: Undeclared identifier 'MTrendUp';
line 41: Undeclared identifier 'MTrendDown';
line 43: Undeclared identifier 'Trend';
line 43: Undeclared identifier 'green';
line 43: Undeclared identifier 'red';
line 44: Undeclared identifier 'Tsl';
line 44: Undeclared identifier 'linecolor';
line 44: Undeclared identifier 'line';
line 46: Undeclared identifier 'MTrend';
line 46: Undeclared identifier 'blue';
line 46: Undeclared identifier 'orange';
line 47: Undeclared identifier 'MTsl';
line 47: Undeclared identifier 'Mlinecolor';
line 47: Undeclared identifier 'line';
line 49: Undeclared identifier 'Tsl';
line 49: Undeclared identifier 'green';
line 50: Undeclared identifier 'Tsl';
line 50: Undeclared identifier 'red';
line 52: Undeclared identifier 'Trend';
line 52: Undeclared identifier 'MTrend';
line 53: Undeclared identifier 'Trend';
line 53: Undeclared identifier 'MTrend';
line 54: Undeclared identifier 'up';
line 54: Undeclared identifier 'Trend';
line 54: Undeclared identifier 'lime';
line 55: Undeclared identifier 'down';
line 55: Undeclared identifier 'Trend';
line 55: Undeclared identifier 'red';
line 58: Undeclared identifier 'Trend';
line 58: Undeclared identifier 'MTrend';
line 59: Undeclared identifier 'Trend';
line 59: Undeclared identifier 'MTrend';
line 76: Undeclared identifier 'orange';
line 80: Undeclared identifier 'lime';
line 84: Undeclared identifier 'cold3';
line 84: Undeclared identifier 'colu2';
line 86: Undeclared identifier 'color';
line 105: Cannot call 'security' with arguments (const integer, literal string, series[float]); available overloads: security(string, string, series[float], const bool, const bool, string) => series[float]; security(string, string, series[integer], const bool, const bool, string) => series[integer]; security(string, string, series[bool], const bool, const bool, string) => series[bool]; security(string, string, series[color], const bool, const bool, string) => series[color]; security(string, string, <arg_expr_type>, const bool, const bool, string) => <arg_expr_type>;
line 106: Cannot call 'security' with arguments (const integer, literal string, series[float]); available overloads: security(string, string, series[float], const bool, const bool, string) => series[float]; security(string, string, series[integer], const bool, const bool, string) => series[integer]; security(string, string, series[bool], const bool, const bool, string) => series[bool]; security(string, string, series[color], const bool, const bool, string) => series[color]; security(string, string, <arg_expr_type>, const bool, const bool, string) => <arg_expr_type>;
line 107: Cannot call 'security' with arguments (const integer, literal string, series[float]); available overloads: security(string, string, series[float], const bool, const bool, string) => series[float]; security(string, string, series[integer], const bool, const bool, string) => series[integer]; security(string, string, series[bool], const bool, const bool, string) => series[bool]; security(string, string, series[color], const bool, const bool, string) => series[color]; security(string, string, <arg_expr_type>, const bool, const bool, string) => <arg_expr_type>;
line 108: Cannot call 'security' with arguments (const integer, literal string, series[float]); available overloads: security(string, string, series[float], const bool, const bool, string) => series[float]; security(string, string, series[integer], const bool, const bool, string) => series[integer]; security(string, string, series[bool], const bool, const bool, string) => series[bool]; security(string, string, series[color], const bool, const bool, string) => series[color]; security(string, string, <arg_expr_type>, const bool, const bool, string) => <arg_expr_type>;
line 109: Cannot call 'security' with arguments (const integer, literal string, series[float]); available overloads: security(string, string, series[float], const bool, const bool, string) => series[float]; security(string, string, series[integer], const bool, const bool, string) => series[integer]; security(string, string, series[bool], const bool, const bool, string) => series[bool]; security(string, string, series[color], const bool, const bool, string) => series[color]; security(string, string, <arg_expr_type>, const bool, const bool, string) => <arg_expr_type>;
line 110: Cannot call 'security' with arguments (const integer, literal string, series[float]); available overloads: security(string, string, series[float], const bool, const bool, string) => series[float]; security(string, string, series[integer], const bool, const bool, string) => series[integer]; security(string, string, series[bool], const bool, const bool, string) => series[bool]; security(string, string, series[color], const bool, const bool, string) => series[color]; security(string, string, <arg_expr_type>, const bool, const bool, string) => <arg_expr_type>;
line 111: Cannot call 'security' with arguments (const integer, literal string, series[float]); available overloads: security(string, string, series[float], const bool, const bool, string) => series[float]; security(string, string, series[integer], const bool, const bool, string) => series[integer]; security(string, string, series[bool], const bool, const bool, string) => series[bool]; security(string, string, series[color], const bool, const bool, string) => series[color]; security(string, string, <arg_expr_type>, const bool, const bool, string) => <arg_expr_type>;
line 112: Cannot call 'security' with arguments (const integer, literal string, series[float]); available overloads: security(string, string, series[float], const bool, const bool, string) => series[float]; security(string, string, series[integer], const bool, const bool, string) => series[integer]; security(string, string, series[bool], const bool, const bool, string) => series[bool]; security(string, string, series[color], const bool, const bool, string) => series[color]; security(string, string, <arg_expr_type>, const bool, const bool, string) => <arg_expr_type>;
line 113: Cannot call 'security' with arguments (const integer, literal string, series[float]); available overloads: security(string, string, series[float], const bool, const bool, string) => series[float]; security(string, string, series[integer], const bool, const bool, string) => series[integer]; security(string, string, series[bool], const bool, const bool, string) => series[bool]; security(string, string, series[color], const bool, const bool, string) => series[color]; security(string, string, <arg_expr_type>, const bool, const bool, string) => <arg_expr_type>;
line 114: Cannot call 'security' with arguments (const integer, literal string, series[float]); available overloads: security(string, string, series[float], const bool, const bool, string) => series[float]; security(string, string, series[integer], const bool, const bool, string) => series[integer]; security(string, string, series[bool], const bool, const bool, string) => series[bool]; security(string, string, series[color], const bool, const bool, string) => series[color]; security(string, string, <arg_expr_type>, const bool, const bool, string) => <arg_expr_type>;
line 115: Cannot call 'security' with arguments (const integer, literal string, series[float]); available overloads: security(string, string, series[float], const bool, const bool, string) => series[float]; security(string, string, series[integer], const bool, const bool, string) => series[integer]; security(string, string, series[bool], const bool, const bool, string) => series[bool]; security(string, string, series[color], const bool, const bool, string) => series[color]; security(string, string, <arg_expr_type>, const bool, const bool, string) => <arg_expr_type>;
line 119: Undeclared identifier 'dtime_pivot';
line 119: Undeclared identifier 'circles';
line 119: Undeclared identifier 'blue';
line 120: Undeclared identifier 'dtime_bc';
line 120: Undeclared identifier 'circles';
line 120: Undeclared identifier 'blue';
line 121: Undeclared identifier 'dtime_tc';
line 121: Undeclared identifier 'circles';
line 121: Undeclared identifier 'blue';
line 122: Undeclared identifier 'dtime_r1';
line 122: Undeclared identifier 'circles';
line 122: Undeclared identifier 'green';
line 123: Undeclared identifier 'dtime_s1';
line 123: Undeclared identifier 'circles';
line 123: Undeclared identifier 'red'
Script 'MystockMoney Trend Trading Tool 1.0' has been saved

Converted to Pine v4
//#version=4
//Trend Trading Study by MSM *Sanjay.r* Trend Trading Indicator
study("MystockMoney Trend Trading Tool 1.0", overlay=true)
res = input(title="Main MSM Time Frame", type=input.resolution, defval="120")
Factor = input(1, minval = 1, maxval = 100)
Pd = input(1, minval = 1, maxval = 100)
tp = input(500, title="Take Profit")
sl = input(200, title="Stop Loss")
avlen = input(50)
var float TrendUp = na
var float TrendDown = na
var float MTrendUp = na
var float MTrendDown = na
var float Trend = na
var float Tsl = na
var float MTrend = na
var float MTsl = na
var color linecolor = na
//Plots VWAP and MVWAP for intraday trading. Useful to avoid whipsaws
//study("VWAP MVWAP with pivot points", overlay = true)
color1 = color.blue
color2 = color.black
mvwap = ema(vwap,avlen)
plot(vwap, linewidth = 2, style = plot.style_circles, color = color2)
plot(mvwap, color= color1)
delta = (Factor*atr(Pd))
Up = hl2 - delta
Dn = hl2 + delta
MUp = security(syminfo.tickerid, res, Up)
MDn = security(syminfo.tickerid, res, Dn)
Mclose = security(syminfo.tickerid, res, close)
TrendUp := close[1]>TrendUp[1]? max(Up,TrendUp[1]) : Up
TrendDown := close[1]<TrendDown[1]? min(Dn,TrendDown[1]) : Dn
MTrendUp := Mclose[1]>MTrendUp[1]? max(MUp,MTrendUp[1]) : MUp
MTrendDown := Mclose[1]<MTrendDown[1]? min(MDn,MTrendDown[1]) : MDn
Trend := close > TrendDown[1] ? 1: close< TrendUp[1]? -1: nz(Trend[1],1)
Tsl := Trend==1? TrendUp: TrendDown
MTrend := Mclose > MTrendDown[1] ? 1: Mclose< MTrendUp[1]? -1: nz(MTrend[1],1)
MTsl := MTrend==1? MTrendUp: MTrendDown
linecolor := Trend == 1 ? color.green : color.red
plot(Tsl, color = linecolor , style = plot.style_line , linewidth = 2, title = "MSM")
Mlinecolor = MTrend == 1 ? color.blue : color.orange
plot(MTsl, color = Mlinecolor , style = plot.style_line , linewidth = 2,title = "Main MSM")
plotshape(cross(close,Tsl) and close>Tsl , "Up Arrow", shape.triangleup,location.belowbar, color.green, 0, 0)
plotshape(cross(Tsl,close) and close<Tsl , "Down Arrow", shape.triangledown , location.abovebar, color.red, 0, 0)
up = Trend == 1 and Trend[1] == -1 and MTrend == 1
down = Trend == -1 and Trend[1] == 1 and MTrend == -1
plotarrow(up ? Trend : na, title="Up Entry Arrow", colorup=color.lime, maxheight=60, minheight=50, transp=0)
plotarrow(down ? Trend : na, title="Down Entry Arrow", colordown=color.red, maxheight=60, minheight=50, transp=0)
golong = up
goshort = down
length = input(21, "length", minval=1)
avrg = sma(volume, length)
vold1 = volume > avrg*1.5 and close < open
vold2 = volume >= avrg*0.5 and volume <= avrg*1.5 and close < open
vold3 = volume < avrg*0.5 and close < open
volu1 = volume > avrg*1.5 and close > open
volu2 = volume >= avrg*0.5 and volume <= avrg*1.5 and close > open
volu3 = volume < avrg*0.5 and close > open
cold1 = #800000
cold2 = #FF0000
cold3 = color.orange
colu1 = #006400
colu2 = color.lime
colu3 = #7FFFD4
bcolor = vold1 ? cold1 : vold2 ? cold2 : vold3 ? cold3 : volu1 ? colu1 : volu2 ? colu2 : volu3 ? colu3 : na
barcolor(bcolor)
//Code merged for another indicator
sd = input(true, title="Show Daily Pivots?")
//Pivot Range Calculations - Mark Fisher
pivot = hlc3
bc = hl2
tc = (pivot - bc) + pivot
r1 = (pivot * 2) - low
s1 = (pivot * 2) - high
r2 = pivot + (high - low)
s2 = pivot - (high - low)
r3 = r1 + (high - low)
s3 = s1 - (high - low)
r4 = r3 + (r2 - r1)
s4 = s3 - (s1 - s2)
//Daily Pivot Range
dtime_pivot = security(syminfo.tickerid, 'D', pivot[1])
dtime_bc = security(syminfo.tickerid, 'D', bc[1])
dtime_tc = security(syminfo.tickerid, 'D', tc[1])
dtime_r1 = security(syminfo.tickerid, 'D', r1[1])
dtime_r2 = security(syminfo.tickerid, 'D', r2[1])
dtime_r3 = security(syminfo.tickerid, 'D', r3[1])
dtime_r4 = security(syminfo.tickerid, 'D', r4[1])
dtime_s1 = security(syminfo.tickerid, 'D', s1[1])
dtime_s2 = security(syminfo.tickerid, 'D', s2[1])
dtime_s3 = security(syminfo.tickerid, 'D', s3[1])
dtime_s4 = security(syminfo.tickerid, 'D', s4[1])
offs_daily = 0
plot(sd and dtime_pivot ? dtime_pivot : na, title="Daily Pivot", style=plot.style_circles, color=color.blue, linewidth=3)
plot(sd and dtime_bc ? dtime_bc : na, title="Daily BC", style=plot.style_circles, color=color.blue, linewidth=3)
plot(sd and dtime_tc ? dtime_tc : na, title="Daily TC", style=plot.style_circles, color=color.blue, linewidth=3)
plot(sd and dtime_r1 ? dtime_r1 : na, title="Daily r1", style=plot.style_circles, color=color.green, linewidth=3)
plot(sd and dtime_s1 ? dtime_s1 : na, title="Daily s1", style=plot.style_circles, color=color.red, linewidth=3)

Related

How can I generate a WM_SEC.AUTH_SIGNATURE in Elixir?

I'm trying to generate Walmart's API WM_SEC.AUTH_SIGNATURE header.
I found a lot of examples in Ruby and Python, but no examples in Elixir. I've been trying to create one and try it out.
Here's what I attempted.
# mix.exs
{:ex_crypto, git: "https://github.com/ntrepid8/ex_crypto.git", branch: "master"}
def scrape_store_item(store_item) do
consumer_id = "my-consumer-id"
private_key_version = "1"
private_key_password = "my-private-key-password"
private_key =
Application.app_dir(:my_app, "priv/keys/walmart/WM_IO_private_key.pem")
|> ExPublicKey.load!(private_key_password)
timestamp = DateTime.utc_now() |> DateTime.to_unix()
url = "https://developer.api.walmart.com/api-proxy/service/affil/product/v2/taxonomy"
message = "#{consumer_id}\n#{timestamp}\n#{private_key_version}\n"
encoded_message = Base.encode64(message)
{:ok, auth_signature} = ExPublicKey.sign(encoded_message, private_key)
auth_signature = Base.encode64(auth_signature)
middleware = [
{Tesla.Middleware.BaseUrl,
"https://developer.api.walmart.com/api-proxy/service/affil/product/v2"},
{Tesla.Middleware.Headers,
[
{"WM_CONSUMER.ID", consumer_id},
{"WM_CONSUMER.INTIMESTAMP", timestamp},
{"WM_SEC.KEY_VERSION", private_key_version},
{"WM_SEC.AUTH_SIGNATURE", auth_signature},
{"WM_SHOW_REASON_CODES", "ALL"},
{"Content-Type", "application/json"}
]}
]
client = Tesla.client(middleware)
{:ok, response} = Tesla.get(client, "/taxonomy") |> IO.inspect()
IO.inspect(response.body)
end
I get a 401 response with this code:
{:ok,
%Tesla.Env{
__client__: %Tesla.Client{
adapter: nil,
fun: nil,
post: [],
pre: [
{Tesla.Middleware.BaseUrl, :call,
["https://developer.api.walmart.com/api-proxy/service/affil/product/v2"]},
{Tesla.Middleware.Headers, :call,
[
[
{"WM_CONSUMER.ID", "my-consumer-id"},
{"WM_CONSUMER.INTIMESTAMP", 1654443660},
{"WM_SEC.KEY_VERSION", "1"},
{"WM_SEC.AUTH_SIGNATURE",
"kdXG+e6R/n+8pH1ha1WKnzLrAHbUqmJsZfN9nOIyOzp6gsHAH7/VrX0K477cdzAq/v7YLpNJXZug3Yt6WTZoP17sZhz6Dig1BK1gg+EZqVqRaF3VJdRwBKlVgBO31s634xL7M8kPhXK11CsMxG8/9xjTGn2cDKEZ9aLeq15ECIfYa5tVtCdTcjNS4u6a7npByU9PIFp9a7n3h1KbW9C/9EA05kTuC1N0oS8nBlnKbA2+C0UW9EAvN4MaIkG0SqOqf/uEHn9BteAv8hI0Ayyny9RpJQmfZEpZ0G3htA7t1pWTzwxUsIJrF/5D1gV+IIYR7OiwHUg2RsIrnPohbznPQw=="}
]
]}
]
},
__module__: Tesla,
body: <<31, 139, 8, 0, 0, 9, 110, 136, 0, 255, 68, 204, 65, 138, 131, 64, 16,
70, 225, 171, 20, 255, 122, 70, 156, 25, 199, 69, 175, 115, 132, 236, 67,
97, 151, 177, 192, 110, 155, 174, 210, 4, 196, 187, 135, ...>>,
headers: [
{"content-encoding", "gzip"},
{"content-type", "application/json;charset=utf-8"},
{"last-modified", "Sun, 05 Jun 2022 15:41:00 GMT"},
{"strict-transport-security", "max-age=86400"},
{"wm_svc.env", "prod"},
{"wm_svc.name", "affil-product"},
{"wm_svc.version", "2.0.0"},
{"x-lua-strict-transport-security", "max-age=86400"},
{"x-tb", "1"},
{"x-tb-optimization-total-bytes-saved", "0"},
{"date", "Sun, 05 Jun 2022 15:41:00 GMT"},
{"connection", "close"},
{"set-cookie",
"TS01a35e2a=01c5a4e2f95f0b472a3a7606aa7c7c33653874c13d636655443ecbca84d23369b19bc1de1973ac24c93ff1f24512e7af49264d46c6; Path=/; Secure"}
],
method: :get,
opts: [],
query: [],
status: 401,
url: "https://developer.api.walmart.com/api-proxy/service/affil/product/v2/taxonomy"
}}
Here's the example code someone shared for a working Ruby version.
version = 'YOUR VERSION'
consumer_id = "YOUR CONSUMER ID"
time_stamp = (Time.now.to_i * 1000).to_s
p_key = "YOUR PRIVATE KEY"
digest = OpenSSL::Digest.new('sha256')
data = consumer_id + "\n" + time_stamp + "\n" + version + "\n"
k = OpenSSL::PKey::RSA.new(p_key.to_s)
digest = OpenSSL::Digest::SHA256.new
signature = k.sign(digest,data)
signature = Base64.strict_encode64(signature)
headers = {
"WM_SEC.KEY_VERSION": version,
"WM_CONSUMER.ID": consumer_id,
"WM_CONSUMER.INTIMESTAMP": time_stamp,
"WM_SEC.AUTH_SIGNATURE": signature
}
puts HTTParty.get("https://developer.api.walmart.com/api-proxy/service/affil/product/v2/taxonomy", headers: headers).parsed_response
Here's a script that does it without ex_crypto. Nice challenge, those Wallmart docs are terrible.
Mix.install([:tesla])
key_version = System.fetch_env!("WALLMART_KEY_VERSION")
consumer_id = System.fetch_env!("WALLMART_CONSUMER_ID")
private_key_pem = File.read!("WM_IO_private_key.pem")
[pem_entry] = :public_key.pem_decode(private_key_pem)
private_key = :public_key.pem_entry_decode(pem_entry)
timestamp = System.os_time(:millisecond)
auth_signature =
"#{consumer_id}\n#{timestamp}\n#{key_version}\n"
|> :public_key.sign(:sha256, private_key)
|> Base.encode64()
url = "https://developer.api.walmart.com/api-proxy/service/affil/product/v2/taxonomy"
headers = [
{"WM_CONSUMER.ID", consumer_id},
{"WM_CONSUMER.INTIMESTAMP", timestamp},
{"WM_SEC.KEY_VERSION", key_version},
{"WM_SEC.AUTH_SIGNATURE", auth_signature}
]
{:ok, %{body: body}} = Tesla.get(url, headers: headers)
IO.puts(body)
Output:
{"categories":[{"id":"0","name":"Home Page","path":"Home Page",...
Here's how you generate WM_SEC.AUTH_SIGNATURE in Elixir:
Make sure you have ex_crypto package installed from master branch since the latest version has necessary changes but is not published.
{:ex_crypto, git: "https://github.com/ntrepid8/ex_crypto.git", branch: "master"}
Then here's the solution:
version = "1"
consumer_id = "my-consumer-id"
timestamp = DateTime.utc_now() |> DateTime.to_unix(:millisecond)
data = "#{consumer_id}\n#{timestamp}\n#{version}\n"
private_key =
Application.app_dir(:my_app, "priv/keys/walmart/WM_IO_private_key.pem")
|> ExPublicKey.load!()
{:ok, auth_signature} = ExPublicKey.sign(data, private_key)
auth_signature = Base.encode64(auth_signature)
middleware = [
{Tesla.Middleware.BaseUrl,
"https://developer.api.walmart.com/api-proxy/service/affil/product/v2"},
{Tesla.Middleware.Headers,
[
{"WM_CONSUMER.ID", consumer_id},
{"WM_CONSUMER.INTIMESTAMP", timestamp},
{"WM_SEC.KEY_VERSION", version},
{"WM_SEC.AUTH_SIGNATURE", auth_signature}
]}
]
client = Tesla.client(middleware)
Tesla.get(client, "/taxonomy")

Showing only none in output instead of changing numeric value to capitilized alphabets

def convert_digits(input_string, start_position, end_position):
# The ending index was required as it was not returning the whole sentence
new_string = input_string[:end_position]
newstring = " "
# return new_string
digit_mapping = {
'0': 'ZERO',
'1': 'ONE',
'2': 'TWO',
'3': 'THREE',
'4': 'FOUR',
'5': 'FIVE',
'6': 'SIX',
'7': 'SEVEN',
'8': 'EIGHT',
'9': 'NINE'
}
if start_position >= 1:
if end_position <= len(new_string):
if start_position < end_position:
for index in range(start_position - 1, end_position):
if input_string[index].isdigit():
mapped = digit_mapping[input_string[index]]
newstring += " " + mapped + " "
else:
newstring += input_string[index]
else:
return "INVALID"
else:
return "INVALID"
else:
return "INVALID"
return newstring
if name == 'main':
print(convert_digits("you are a 4king 5shole", 1, 21))
Use this code.
Your problem was in line 39, you add 2 tabs place 1.
def convert_digits(input_string, start_position, end_position):
# The ending index was required as it was not returning the whole sentence
new_string = input_string[:end_position]
newstring = " "
# return new_string
digit_mapping = {
'0': 'ZERO',
'1': 'ONE',
'2': 'TWO',
'3': 'THREE',
'4': 'FOUR',
'5': 'FIVE',
'6': 'SIX',
'7': 'SEVEN',
'8': 'EIGHT',
'9': 'NINE'
}
if start_position >= 1:
if end_position <= len(new_string):
if start_position < end_position:
for index in range(start_position - 1, end_position):
if input_string[index].isdigit():
mapped = digit_mapping[input_string[index]]
newstring += " " + mapped + " "
else:
newstring += input_string[index]
else:
return "INVALID"
else:
return "INVALID"
else:
return "INVALID"
return newstring
if __name__ == '__main__':
print(convert_digits("you are a 4king 5shole", 1, 21))

Python program Convert middle digits into its corresponding alphabets form in between start position and end position

take string and two integers from user and convert middle digits into its corresponding alphabetical form in between start and end position
def convert_digits( input_string, start_position, end_position ) :
new_string = input_string[:start_position]
digit_mapping = {
'0': 'ZERO',
'1': 'ONE',
'2': 'TWO',
'3': 'THREE',
'4': 'FOUR',
'5': 'FIVE',
'6': 'SIX',
'7': 'SEVEN',
'8': 'EIGHT',
'9': 'NINE'
}
for index in range(start_position, end_position):
if input_string[index].isdigit():
mapped = digit_mapping[input_string[index]]
new_string = mapped
new_string += input_string[end_position + 1:]
return new_string
def convert_digits(input_string, start_position, end_position):
len_str = len(input_string)
if end_position > len_str:
end_position = len_str
if start_position < 0:
start_position = 0
elif start_position >= end_position:
start_position = end_position - 1
input_string = input_string[start_position:end_position]
digit_mapping = {
'0': 'ZERO',
'1': 'ONE',
'2': 'TWO',
'3': 'THREE',
'4': 'FOUR',
'5': 'FIVE',
'6': 'SIX',
'7': 'SEVEN',
'8': 'EIGHT',
'9': 'NINE'
}
input_string = list(input_string)
for index, char in enumerate(input_string):
if char.isdigit():
input_string[index] = digit_mapping[char]
return "".join(input_string)
print(convert_digits("ajoegh12ioh12oih", 0, 14))

AES/GCM PBKDF2 Encryption for Kotlin and Dart

I am attempting to use GCM encryption with PBKDF2 that is interoperable across both kotlin and dart. Decrypters will come next. Currently I am using a "working" kotlin version (below) and I want to replicate it in dart (my attempt below that) if it is correct. See below Kotlin version (Notice log results provided below respective lines. Outputs are suspect.):
Also note: These examples now use the same text and masterpass inputs.
KOTLIN:
fun encrypt(input: String, password: String): String {
val masterpw = getKey(password).toString(Charset.forName("UTF-8"))
val mastertest = getKey(password)
val random = SecureRandom()
Log.d("RANDOM", "${random}") //D/RANDOM (25834): java.security.SecureRandom#dc72083
val salt = ByteArray(8)
Log.d("SALT", "${salt}") //D/SALT (25834): [B#202f200
random.nextBytes(salt)
Log.d("SALT2", "${salt}") //D/SALT2 (25834): [B#202f200
val factory: SecretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1")
Log.d("factory", "${factory}") //D/factory (25834): javax.crypto.SecretKeyFactory#cfd3a39
val spec: KeySpec = PBEKeySpec(masterpw.toString().toCharArray(), salt, 10000, 256)
Log.d("KeySpec", "${spec}") //D/KeySpec (25834): javax.crypto.spec.PBEKeySpec#a5587e
val tmp: SecretKey = factory.generateSecret(spec)
Log.d("SecretKey", "${tmp}") //D/SecretKey(25834): com.android.org.bouncycastle.jcajce.provider.symmetric.util.BCPBEKey#6d141df
val iv = ByteArray(12)
Log.d("IV", "${iv}") //D/IV (25834): [B#aa52e2c
random.nextBytes(iv)
Log.d("IV2", "${iv}") //D/IV2 (25834): [B#aa52e2c
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
Log.d("Cipher", "${cipher}") //D/Cipher (25834): javax.crypto.Cipher#e6e40f5
cipher.init(Cipher.ENCRYPT_MODE, tmp, IvParameterSpec(iv))
Log.d("Cipher2", "${cipher}") //D/Cipher2 (25834): javax.crypto.Cipher#e6e40f5
val cipherText: ByteArray = cipher.doFinal(input.toByteArray(Charset.forName("UTF-8")))
Log.d("cipherText", "${cipherText}") //D/cipherText(25834): [B#f3a7e8a
val ivstring: String = Base64.encodeToString(iv, Base64.NO_WRAP)
Log.d("ivstring", "${ivstring}") //D/ivstring(25834): D3tPtM6+WYnoSswE
val saltystring: String = Base64.encodeToString(salt, Base64.NO_WRAP)
Log.d("saltystring", "${saltystring}") //D/saltystring(25834): zbq9ZqJ9xiw=
val cipherstring: String = Base64.encodeToString(cipherText, Base64.NO_WRAP)
Log.d("cipherstring", "${cipherstring}") //D/cipherstring(25834): w/WqSqg++udXCLKE6ly765OWBHKt79Lw/g==
val returnstring: String = ivstring + "-" + saltystring + "-" + cipherstring
Log.d("returnstring", "${returnstring}") //D/returnstring(25834): D3tPtM6+WYnoSswE-zbq9ZqJ9xiw=-w/WqSqg++udXCLKE6ly765OWBHKt79Lw/g==
return returnstring
}
fun getKey(masterPass: String): ByteArray {
return masterPass.padEnd(32, '.').toByteArray(Charset.forName("UTF-8"))
}
DART:
The dart method utilizes the cryptography.dart package v1.4.1. Note: Due to constraints with other libraries in the app, I can't use a newer version of the cryptography package, which I believe rules the recently added 'AesGcm.with128bits' functions out.
The dart version crashes near the end when I attempt to decode the encrypted cipherTextBytes to a string, as shown in the provided log results.
encryptPassGCM(String text, String masterPass) async {
print("ENCRYPTPASSGCM STARTS WITH: " + "TEXT: " + text + " & " + "master: " + masterPass);
//trim key and convert
String keyString = masterPass;
if (keyString.length < 32) {
int count = 32 - keyString.length;
for (var i = 0; i < count; i++) {
keyString += ".";
}
}
Uint8List keyStringutf8 = utf8.encode(keyString);
print("keyStringutf8: " + keyStringutf8.toString());
//gen salt and iv
final salt = Nonce.randomBytes(8);
print("salt init: " + salt.bytes.toString());
//LOG salt init: [161, 50, 222, 98, 151, 225, 89, 65]
final iv = Nonce.randomBytes(12);
print("iv init: " + iv.bytes.toString());
//LOG iv init: [59, 188, 146, 172, 213, 13, 135, 35, 202, 220, 178, 190]
//create key
final pbkdf2 = Pbkdf2(
macAlgorithm: Hmac(sha1),
iterations: 10000,
bits: 256,
);
final keyBytes = await pbkdf2.deriveBits(
keyStringutf8,
nonce: salt,
);
print("keybytes: " + keyBytes.toString());
//LOG keybytes: [85, 204, 96, 108, 200, 21, 24, 115, 254, 104, 133, 81, 53, 126, 252, 161, 172, 193, 25, 177, 143, 69, 53, 35, 105, 144, 248, 6, 121, 106, 237, 142]
SecretKey secretKey = new SecretKey(keyBytes);
print("secretKey: " + secretKey.toString());
//LOG secretKey: SecretKey(...)
//create ciphertext and convert to string
List<int> textutf8 = utf8.encode(text);
Uint8List cipherTextBytes = await AesGcm().encrypt(textutf8, secretKey: secretKey, nonce: iv);
print("cipherTextBytes: " + cipherTextBytes.toString());
//LOG cipherTextBytes: [110, 3, 238, 169, 52, 125, 176, 200, 122, 142, 111, 75, 181, 248, 91, 57, 95, 131, 85, 223, 224, 73, 173, 39, 37]
var cipherText = utf8.decode(cipherTextBytes); //CRASHES HERE
print("cipherText: " + cipherText);
var cipherString = iv.toString() + "-" + salt.toString() + "-" + cipherText;
print("GCM CIPHER STRING COMPLETE: " + cipherString);
return cipherString;
}
Is the kotlin implementation correct? The data logs seem erroneous.
What is wrong with my dart implementation?
The exception is thrown when trying to Utf8 decode the ciphertext. Arbitrary binary data like ciphertexts or pseudo-random data like salts or IVs cannot be decoded with charset encodings like Utf8 because the data will be corrupted, see here. Instead, a binary-to-text encoding like Base64 must be applied.
The Kotlin code Base64 encodes salt, IV and ciphertext and concatenates the portions with a separator (-). The Dart counterpart would be e.g.:
var cipherString = base64.encode(iv.bytes) + "-" + base64.encode(salt.bytes) + "-" + base64.encode(cipherTextBytes);
and the UTF8 decoding of cipherTextBytes is to be removed.
A second problem was that by accident the originally posted code did not use the key derived using PBKDF2, but a randomly generated key (see also Rob Napier's comment).
When both bugs are fixed, both codes are functionally identical and produce the same ciphertext (assuming the same salt and IV).
Note that the GCM authentication tag (16 bytes by default) is automatically appended to the ciphertext in the Dart and Kotlin code (i.e. cipherTextBytes contains not only the ciphertext but also the authentication tag: ciphertext|tag). Not all libraries do it this way, so the separation of the tag (as the last 16 bytes) is required when decrypting with such a library.
Also, it is rather uncommon to Base64 encode salt, IV and ciphertext/tag separately and concatenate the parts with a separator. Instead, by convention, concatenation is done at byte level: salt|IV|ciphertext|tag. Since the salt, IV and tag lengths are known on both sides, no separator is needed. The result is Base64 encoded. But as mentioned, this is just a convention.
Regarding the parameters for PBKDF2: Although SHA1 is classified as insecure (see here), its use as HMAC/SHA1 is not critical. However, a move to SHA256 would support the banishment of SHA1 from the ecosystem. The iteration count should slow down an attacker and should therefore be chosen as high as possible while maintaining acceptable performance (typically larger than 10,000). The recommended salt length is 16 bytes, see PBKDF2.

The function must accept the result of another function as an argument Kotlin

The result of the gen function must be an argument of the res function.
The result of the res function is even numbers that came out of the first function.
fun gen():List<Int>{
val numbers=List(10){Random.nextInt(1,100)}
return numbers.filter{it>0}
}
fun res(){...}
From your question, seems like you're trying to create list of random numbers and then filtering out the even numbers from the generated list.
Most probably this should be the implementation:
fun gen(): List<Int> = List(10) { Random.nextInt(1, 100) }
fun res(list: List<Int>) = list.filter { it % 2 == 0 }
// somewhere else
val generated = gen()
println(generated)
println(res(generated))
Sample output:
[44, 57, 64, 96, 30, 93, 92 23, 58, 26]
[44, 64, 96, 30, 92, 58, 26]