double PAX_yahoo(char *metal) { // http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json // http://finance.yahoo.com/webservice/v1/symbols/XAU=X/quote?format=json // http://finance.yahoo.com/webservice/v1/symbols/XAG=X/quote?format=json // http://finance.yahoo.com/webservice/v1/symbols/XPT=X/quote?format=json // http://finance.yahoo.com/webservice/v1/symbols/XPD=X/quote?format=json char url[1024],*jsonstr; cJSON *json,*obj,*robj,*item,*field; double price = 0.; sprintf(url,"http://finance.yahoo.com/webservice/v1/symbols/%s=X/quote?format=json",metal); if ( (jsonstr= issue_curl(url)) != 0 ) { //printf("(%s)\n",jsonstr); if ( (json= cJSON_Parse(jsonstr)) != 0 ) { if ( (obj= jobj(json,"list")) != 0 && (robj= jobj(obj,"resources")) != 0 && (item= jitem(robj,0)) != 0 ) { if ( (robj= jobj(item,"resource")) != 0 && (field= jobj(robj,"fields")) != 0 && (price= jdouble(field,"price")) != 0 ) price = 1. / price; } free_json(json); } free(jsonstr); } if ( Debuglevel > 2 ) printf("(%s %f) ",metal,price); return(price); }
void marketmaker_pendingupdate(char *exchange,char *base,char *rel) { char *retstr; cJSON *retjson,*obj; int32_t i; struct mmpending_order *ptr; for (i=0; i<Num_Pending; i++) { ptr = &Pending_orders[i]; if ( strcmp(exchange,ptr->exchange) != 0 || strcmp(base,ptr->base) != 0 || strcmp(rel,ptr->rel) != 0 ) continue; if ( ptr->completed == 0 && (retstr= DEX_orderstatus(exchange,ptr->orderid)) != 0 ) { //printf("%s status.(%s)\n",ptr->orderid,retstr); if ( (retjson= cJSON_Parse(retstr)) != 0 ) { obj = jobj(retjson,"result"); if ( is_cJSON_Array(obj) != 0 ) obj = jitem(retjson,0); if ( jdouble(obj,"QuantityRemaining") == 0. || is_cJSON_True(jobj(obj,"IsOpen")) == 0 ) { //{"Uuid":null,"OrderUuid":"e7b0789c-0c4e-413b-a768-3d5734d9cbe5","Exchange":"BTC-KMD","OrderType":"LIMIT_SELL","Quantity":877.77700000,"QuantityRemaining":462.50512234,"Limit":0.00011770,"CommissionPaid":0.00012219,"Price":0.04887750,"PricePerUnit":0.00011769,"Opened":"2017-02-20T13:16:22.29","Closed":null,"CancelInitiated":false,"ImmediateOrCancel":false,"IsConditional":false,"Condition":"NONE","ConditionTarget":null} printf("uuid.(%s) finished.(%s)\n",ptr->orderid,jprint(retjson,0)); ptr->completed = (uint32_t)time(NULL); ptr->pending = 0; } free_json(retjson); } free(retstr); } } }
void marketmaker_pendinginit(char *exchange,char *base,char *rel) { char *retstr,*orderid; cJSON *retjson,*array,*item; int32_t i,j,n,dir; struct mmpending_order *ptr; if ( (retstr= DEX_openorders(exchange)) != 0 ) { if ( (retjson= cJSON_Parse(retstr)) != 0 ) { //printf("%s\n",jprint(retjson,0)); if ( is_cJSON_True(jobj(retjson,"success")) != 0 && (array= jarray(&n,retjson,"result")) != 0 ) { for (i=0; i<n; i++) { item = jitem(array,i); //printf("(%s)\n",jprint(item,0)); //{"success":true,"message":"","result":[{"Uuid":null,"OrderUuid":"81ad3e37-65d4-4fee-9c29-03b050f5192b","Exchange":"BTC-KMD","OrderType":"LIMIT_BUY","Quantity":885.19934578,"QuantityRemaining":885.19934578,"Limit":0.00011184,"CommissionPaid":0,"Price":0,"PricePerUnit":null,"Opened":"2017-02-19T19:14:02.94","Closed":null,"CancelInitiated":false,"ImmediateOrCancel":false,"IsConditional":false,"Condition":"NONE","ConditionTarget":null}],"tag":"10056789044100011414"} if ( (orderid= jstr(item,"OrderUuid")) != 0 && is_cJSON_Null(jobj(item,"Closed")) != 0 && is_cJSON_False(jobj(item,"CancelInitiated")) != 0 ) { for (j=0; j<Num_Pending; j++) { ptr = &Pending_orders[j]; if ( strcmp(exchange,ptr->exchange) != 0 || strcmp(base,ptr->base) != 0 || strcmp(rel,ptr->rel) != 0 ) continue; if ( strcmp(ptr->orderid,orderid) == 0 ) { ptr->pending = (uint32_t)time(NULL); ptr->completed = 0; printf("%s pending\n",orderid); break; } } if ( j == Num_Pending ) { if ( jstr(item,"OrderType") != 0 ) { if ( strcmp(jstr(item,"OrderType"),"LIMIT_BUY") == 0 ) dir = 1; else if ( strcmp(jstr(item,"OrderType"),"LIMIT_SELL") == 0 ) dir = -1; else dir = 0; if ( dir != 0 ) marketmaker_queue(exchange,base,rel,dir,jdouble(item,"Limit"),jdouble(item,"QuantityRemaining"),item); else printf("no dir (%s) (%s)\n",jprint(item,0),jstr(item,"OrderType")); } } } } } free_json(retjson); } free(retstr); } }
int32_t PAX_ecbparse(char *date,double *prices,char *url,int32_t basenum) { char *jsonstr,*relstr,*basestr; int32_t count=0,i,relnum; cJSON *json,*ratesobj,*item; struct destbuf tmp; if ( (jsonstr= issue_curl(url)) != 0 ) { if ( Debuglevel > 2 ) printf("(%s)\n",jsonstr); if ( (json= cJSON_Parse(jsonstr)) != 0 ) { copy_cJSON(&tmp,jobj(json,"date")), safecopy(date,tmp.buf,64); if ( (basestr= jstr(json,"base")) != 0 && strcmp(basestr,CURRENCIES[basenum]) == 0 && (ratesobj= jobj(json,"rates")) != 0 && (item= ratesobj->child) != 0 ) { while ( item != 0 ) { if ( (relstr= get_cJSON_fieldname(item)) != 0 && (relnum= PAX_basenum(relstr)) >= 0 ) { i = basenum*MAX_CURRENCIES + relnum; prices[i] = item->valuedouble; //if ( basenum == JPYNUM ) // prices[i] *= 100.; // else if ( relnum == JPYNUM ) // prices[i] /= 100.; count++; if ( Debuglevel > 2 ) printf("(%02d:%02d %f) ",basenum,relnum,prices[i]); } else printf("cant find.(%s)\n",relstr);//, getchar(); item = item->next; } } free_json(json); } free(jsonstr); } return(count); }
double blend_price(double *volp,double wtA,cJSON *jsonA,double wtB,cJSON *jsonB) { //A.{"ticker":{"base":"BTS","target":"CNY","price":"0.02958291","volume":"3128008.39295500","change":"0.00019513","markets":[{"market":"BTC38","price":"0.02960000","volume":3051650.682955},{"market":"Bter","price":"0.02890000","volume":76357.71}]},"timestamp":1438490881,"success":true,"error":""} // B.{"id":"bts\/cny","price":"0.02940000","price_before_24h":"0.02990000","volume_first":"3048457.6857147217","volume_second":"90629.45859575272","volume_btc":"52.74","best_market":"btc38","latest_trade":"2015-08-02 03:57:38","coin1":"BitShares","coin2":"CNY","markets":[{"market":"btc38","price":"0.02940000","volume":"3048457.6857147217","volume_btc":"52.738317962865"},{"market":"bter","price":"0.04350000","volume":"0","volume_btc":"0"}]} double priceA,priceB,priceB24,price,volA,volB; cJSON *obj; priceA = priceB = priceB24= price = volA = volB = 0.; if ( jsonA != 0 && (obj= jobj(jsonA,"ticker")) != 0 ) { priceA = jdouble(obj,"price"); volA = jdouble(obj,"volume"); } if ( jsonB != 0 ) { priceB = jdouble(jsonB,"price"); priceB24 = jdouble(jsonB,"price_before_24h"); volB = jdouble(jsonB,"volume_first"); } //printf("priceA %f volA %f, priceB %f %f volB %f\n",priceA,volA,priceB,priceB24,volB); if ( priceB > SMALLVAL && priceB24 > SMALLVAL ) priceB = (priceB * .1) + (priceB24 * .9); else if ( priceB < SMALLVAL ) priceB = priceB24; if ( priceA*volA < SMALLVAL ) price = priceB; else if ( priceB*volB < SMALLVAL ) price = priceA; else price = (wtA * priceA) + (wtB * priceB); *volp = (volA + volB); return(price); }
char *SuperNET_parsemainargs(struct supernet_info *myinfo,bits256 *wallethashp,bits256 *wallet2privp,char *argjsonstr) { cJSON *exchanges=0,*json = 0; char *wallet2fname,*coinargs=0,*secret,*filestr; long allocsize; bits256 wallethash,wallet2priv; int32_t n,len; uint8_t secretbuf[8192]; wallethash = wallet2priv = GENESIS_PRIVKEY; if ( argjsonstr != 0 ) { if ( (filestr= OS_filestr(&allocsize,argjsonstr)) != 0 ) { json = cJSON_Parse(filestr); free(filestr); } if ( json != 0 || (json= cJSON_Parse(argjsonstr)) != 0 ) { printf("ARGSTR.(%s)\n",argjsonstr); if ( jobj(json,"numhelpers") != 0 ) IGUANA_NUMHELPERS = juint(json,"numhelpers"); if ( (secret= jstr(json,"passphrase")) != 0 ) { len = (int32_t)strlen(secret); if ( is_hexstr(secret,0) != 0 && len == 128 ) { len >>= 1; decode_hex(secretbuf,len,secret); } else vcalc_sha256(0,secretbuf,(void *)secret,len), len = sizeof(bits256);
static int __cb(struct um_user *user, char *action, int (*cb)(jobj_t obj)) { static char json[1+OS_FILE_LEN]; int err = 0; jobj_t juser = um_juser(user); if (NULL==juser) { return -ENOEXIST; } os_arrayzero(json); os_v_spgetf(json, OS_FILE_LEN, UM_SCRIPT_EVENT " %s '%s'", action, jobj_string(juser)); jobj_put(juser); if (cb) { jobj_t obj = jobj(json); if (NULL==obj) { return -EBADJSON; } err = (*cb)(obj); jobj_put(obj); } return err; }
void prices777_instaforex(uint32_t timestamps[NUM_INSTAFOREX],double bids[NUM_INSTAFOREX],double asks[NUM_INSTAFOREX]) { //{"NZDUSD":{"symbol":"NZDUSD","lasttime":1437580206,"digits":4,"change":"-0.0001","bid":"0.6590","ask":"0.6593"}, char contract[32],*jsonstr; cJSON *json,*item; int32_t i; memset(timestamps,0,sizeof(*timestamps) * NUM_INSTAFOREX); memset(bids,0,sizeof(*bids) * NUM_INSTAFOREX); memset(asks,0,sizeof(*asks) * NUM_INSTAFOREX); jsonstr = issue_curl("https://quotes.instaforex.com/get_quotes.php?q=NZDUSD,NZDCHF,NZDCAD,NZDJPY,GBPNZD,EURNZD,AUDNZD,CADJPY,CADCHF,USDCAD,EURCAD,GBPCAD,AUDCAD,USDCHF,CHFJPY,EURCHF,GBPCHF,AUDCHF,EURUSD,EURAUD,EURJPY,EURGBP,GBPUSD,GBPJPY,GBPAUD,USDJPY,AUDJPY,AUDUSD,XAUUSD&m=json"); if ( jsonstr != 0 ) { printf("(%s)\n",jsonstr); if ( (json= cJSON_Parse(jsonstr)) != 0 ) { for (i=0; i<NUM_INSTAFOREX; i++) { sprintf(contract,"%s%s",BASERELS[i][0],BASERELS[i][1]); if ( (item= jobj(json,contract)) != 0 ) { timestamps[i] = juint(item,"lasttime"); bids[i] = jdouble(item,"bid"); asks[i] = jdouble(item,"ask"); } } free_json(json); } free(jsonstr); } }
uint32_t marketmaker_fiatupdate(cJSON *fiatjson) { int32_t i,n,baseid; cJSON *item,*array; double price; char *name; uint64_t mask = 0; fiatjson = jobj(fiatjson,"list"); if ( fiatjson != 0 && (array= jarray(&n,fiatjson,"resources")) > 0 ) { for (i=0; i<n; i++) { /* "resource" : { "classname" : "Quote", "fields" : { "name" : "USD/BRX", "price" : "3.063200", "symbol" : "BRX=X", "ts" : "1487866204", "type" : "currency", "utctime" : "2017-02-23T16:10:04+0000", "volume" : "0" } */ item = jitem(array,i); if ( (item= jobj(item,"resource")) != 0 ) item = jobj(item,"fields"); if ( item != 0 ) { price = jdouble(item,"price"); if ( price > SMALLVAL && (name= jstr(item,"name")) != 0 && strncmp(name,"USD/",4) == 0 ) { if ( (baseid= komodo_baseid(name+4)) >= 0 && baseid < 32 ) { if ( ((1LL << baseid) & mask) == 0 ) { _marketmaker_fiatupdate(baseid,price); mask |= (1LL << baseid); } else if ( fabs(price*PAXPRICES[0] - PAXPRICES[baseid]) > SMALLVAL ) printf("DUPLICATE PRICE? %s %.8f vs %.8f\n",name+4,price*PAXPRICES[0],PAXPRICES[baseid]); } } } } } printf("pax mask.%x\n",(uint32_t)mask); return((uint32_t)mask); }
char *PARSEBALANCE(struct exchange_info *exchange,double *balancep,char *coinstr,cJSON *argjson) { char field[128],*itemstr = 0; cJSON *obj,*item; *balancep = 0.; strcpy(field,coinstr); tolowercase(field); if ( argjson != 0 && (obj= jobj(argjson,"return")) != 0 && (item= jobj(obj,"funds")) != 0 ) { *balancep = jdouble(item,field); obj = cJSON_CreateObject(); touppercase(field); jaddstr(obj,"base",field); jaddnum(obj,"balance",*balancep); itemstr = jprint(obj,1); } if ( itemstr == 0 ) return(clonestr("{\"error\":\"cant find coin balance\"}")); return(itemstr); }
void marketmaker_queue(char *exchange,char *base,char *rel,int32_t dir,double price,double volume,cJSON *retjson) { struct mmpending_order *ptr; char *orderid; //DEX_trade.({"success":true,"message":"","result":{"uuid":"d5faa9e4-660d-436f-a257-2c6a40442d8c"},"tag":"11271578410079391025"} if ( is_cJSON_True(jobj(retjson,"success")) != 0 && jobj(retjson,"result") != 0 ) retjson = jobj(retjson,"result"); printf("QUEUE.%s %s/%s dir.%d %.8f %.6f (%s)\n",exchange,base,rel,dir,price,volume,jprint(retjson,0)); Pending_orders = realloc(Pending_orders,(1 + Num_Pending) * sizeof(*Pending_orders)); ptr = &Pending_orders[Num_Pending++]; memset(ptr,0,sizeof(*ptr)); ptr->price = price; ptr->volume = volume; ptr->dir = dir; ptr->pending = (uint32_t)time(NULL); strcpy(ptr->exchange,exchange); strcpy(ptr->base,base); strcpy(ptr->rel,rel); if ( (orderid= jstr(retjson,"OrderUuid")) != 0 || (orderid= jstr(retjson,"uuid")) != 0 ) strcpy(ptr->orderid,orderid); else strcpy(ptr->orderid,"0"); }
jobject Java_com_aldebaran_qimessaging_DynamicObjectBuilder_object(JNIEnv* env, jobject QI_UNUSED(jobj), jlong pObjectBuilder) { qi::DynamicObjectBuilder *ob = reinterpret_cast<qi::DynamicObjectBuilder *>(pObjectBuilder); qi::AnyObject *obj = new qi::AnyObject(); qi::AnyObject &o = *(reinterpret_cast<qi::AnyObject *>(obj)); JVM(env); o = ob->object(); JNIObject jobj(obj); return jobj.object(); }
VJSArray::VJSArray( const VJSValue& inArrayValue, bool inCheckInstanceOfArray) : fContext( inArrayValue.GetContextRef()) { if (inCheckInstanceOfArray && !inArrayValue.IsInstanceOf( CVSTR( "Array")) ) fObject = NULL; else { VJSObject jobj(inArrayValue.GetObject()); inArrayValue.GetObject(jobj); fObject = jobj.GetObjectRef(); } }
char *bidask_func(int32_t localaccess,int32_t valid,char *sender,cJSON *json,char *origargstr) { struct destbuf gui,exchangestr,name,base,rel,offerNXT; struct InstantDEX_quote iQ; copy_cJSON(&offerNXT,jobj(json,"offerNXT")); //printf("got (%s)\n",origargstr); if ( strcmp(SUPERNET.NXTADDR,offerNXT.buf) != 0 ) { if ( bidask_parse(&exchangestr,&name,&base,&rel,&gui,&iQ,json) == 0 ) return(InstantDEX_placebidask(sender,j64bits(json,"orderid"),exchangestr.buf,name.buf,base.buf,rel.buf,&iQ,jstr(json,"extra"),jstr(json,"secret"),jstr(json,"activenxt"),json)); else printf("error with incoming bidask\n"); } else fprintf(stderr,"got my bidask from network (%s)\n",origargstr); return(clonestr("{\"result\":\"got loopback bidask\"}")); }
char *iguana_inputaddress(struct iguana_info *coin,char *coinaddr,int16_t *spent_hdrsip,uint32_t *unspentindp,cJSON *vinobj) { bits256 txid; int32_t vout,checkind,height; *unspentindp = 0; *spent_hdrsip = -1; if ( jobj(vinobj,"txid") != 0 && jobj(vinobj,"vout") != 0 ) { txid = jbits256(vinobj,"txid"); vout = jint(vinobj,"vout"); if ( (checkind= iguana_unspentindfind(coin,coinaddr,0,0,0,&height,txid,vout,coin->bundlescount-1)) > 0 ) { *spent_hdrsip = (height / coin->chain->bundlesize); *unspentindp = checkind; return(coinaddr); } else { char str[65]; printf("error finding (%s/%d)\n",bits256_str(str,txid),vout); } } return(0); }
int32_t basilisk_message_returned(uint8_t *data,int32_t maxlen,cJSON *item) { char *hexstr=0; cJSON *msgobj; int32_t datalen=0,retval = -1; if ( (msgobj= jobj(item,"message")) != 0 ) { if ( (hexstr= jstr(msgobj,"data")) != 0 && (datalen= is_hexstr(hexstr,0)) > 0 ) { datalen >>= 1; if ( datalen < maxlen ) { decode_hex(data,datalen,hexstr); printf("decoded hexstr.[%d]\n",datalen); retval = datalen; } else printf("datalen.%d < maxlen.%d\n",datalen,maxlen); } else printf("no hexstr.%p or datalen.%d\n",hexstr,datalen);
char *PARSEBALANCE(struct exchange_info *exchange,double *balancep,char *coinstr) { //okcoin.({"info":{"funds":{"asset":{"net":"0","total":"0"},"free":{"btc":"0","ltc":"0","usd":"0"},"freezed":{"btc":"0","ltc":"0","usd":"0"}}},"result":true}) char field[128],*itemstr = 0; cJSON *obj,*item,*avail,*locked; double lockval = 0; *balancep = 0.; strcpy(field,coinstr); tolowercase(field); if ( exchange->balancejson != 0 && (obj= jobj(exchange->balancejson,"info")) != 0 && (item= jobj(obj,"funds")) != 0 ) { if ( (avail= jobj(item,"free")) != 0 ) *balancep = jdouble(avail,field); if ( (locked= jobj(item,"freezed")) != 0 ) lockval = jdouble(locked,field); obj = cJSON_CreateObject(); touppercase(field); jaddstr(obj,"base",field); jaddnum(obj,"balance",*balancep); jaddnum(obj,"locked",lockval); itemstr = jprint(obj,1); } if ( itemstr == 0 ) return(clonestr("{\"error\":\"cant find coin balance\"}")); return(itemstr); }
int32_t jnum(cJSON *obj,char *field) { char *str; int32_t polarity = 1; if ( field != 0 ) obj = jobj(obj,field); if ( obj != 0 ) { if ( is_cJSON_Number(obj) != 0 ) return(obj->valuedouble); else if ( is_cJSON_String(obj) != 0 && (str= jstr(obj,0)) != 0 ) { if ( str[0] == '-' ) polarity = -1, str++; return(polarity * (int32_t)calc_nxt64bits(str)); } } return(0); }
uint64_t TRADE(void **cHandlep,int32_t dotrade,char **retstrp,struct exchange_info *exchange,char *base,char *rel,int32_t dir,double price,double volume) { char payload[1024],market[16],coinname[16],fmtstr[512],*pricefmt,*extra,*volfmt = "%.3f"; cJSON *json,*resultobj; uint64_t txid = 0; if ( (extra= *retstrp) != 0 ) *retstrp = 0; if ( (dir= cny_flip(market,coinname,base,rel,dir,&price,&volume)) == 0 ) { fprintf(stderr,"btc38_trade illegal base.(%s) or rel.(%s)\n",base,rel); return(0); } if ( strcmp(market,"cny") == 0 ) pricefmt = "%.5f"; else pricefmt = "%.6f"; //sprintf(fmtstr,"key=%%s&time=%%llu&md5=%%s&type=%%s&mk_type=%%s&coinname=%%s&price=%s&amount=%s",pricefmt,volfmt); //sprintf(payload,fmtstr,exchange->apikey,(long long)nonce,digest,dir>0?"1":"2",market,coinname,price,volume); sprintf(fmtstr,"&type=%%s&mk_type=%%s&coinname=%%s&price=%s&amount=%s",pricefmt,volfmt); sprintf(payload,fmtstr,dir>0?"1":"2",market,coinname,price,volume); if ( CHECKBALANCE(retstrp,dotrade,exchange,dir,base,rel,price,volume) == 0 && (json= SIGNPOST(cHandlep,dotrade,retstrp,exchange,payload,"submitOrder.php")) != 0 ) { if ( juint(json,"success") > 0 && (resultobj= jobj(json,"return")) != 0 ) { if ( (txid= j64bits(resultobj,"order_id")) == 0 ) { if ( j64bits(resultobj,"remains") == 0 ) txid = _crc32(0,payload,strlen(payload)); } } free_json(json); if ( retstrp != 0 && *retstrp != 0 ) { if ( (json= cJSON_Parse(*retstrp)) == 0 ) { json = cJSON_CreateObject(); jaddstr(json,"result",*retstrp); free(*retstrp); *retstrp = jprint(json,1); } else free_json(json); } } return(txid); }
int32_t main(int32_t argc,char **argv) { cJSON *argjson,*array,*filejson,*obj,*fobj; char *fname,*filestr,*fstr,*str,*field; int32_t i,n; long filesize; printf("argv[2]: %s\n",argv[2]); if ( argc > 2 && (argjson= cJSON_Parse(argv[2])) != 0 ) { fname = argv[1]; printf("got file: %s\n",fname); if ( (filestr= OS_filestr(&filesize,fname)) != 0 ) { if ( (filejson= cJSON_Parse(filestr)) != 0 ) { if ( (array= jarray(&n,argjson,"fields")) != 0 ) { for (i=0; i<n; i++) { obj = jitem(array,i); if ( (field= jfieldname(obj)) != 0 && (obj= obj->child) != 0 ) { if ( (fobj= jobj(filejson,field)) != 0 ) { fstr = jprint(fobj,0); str = jprint(obj,0); if ( strcmp(fstr,str) != 0 ) { printf("{\"error\":\"field.(%s) in (%s) i.%d of n.%d mismatch (%s) != (%s)\"}\n",field,fname,i,n,fstr,str); fprintf(stderr,"{\"error\":\"field.(%s) in (%s) i.%d of n.%d mismatch (%s) != (%s)\"}\n",field,fname,i,n,fstr,str); } else printf("{\"result\":\"MATCHED.[%s] (%s).(%s)\"}\n",fname,field,fstr); free(str); free(fstr); } else fprintf(stderr,"cant find field.(%s) in (%s)\n",field,fname); } else fprintf(stderr,"no fieldname array[%d]\n",i); } } else fprintf(stderr,"no fields array\n"); free_json(filejson); } else fprintf(stderr,"cant parse.(%s)\n",filestr); free(filestr); } else fprintf(stderr,"cant load (%s)\n",fname); } else fprintf(stderr,"argc.%d fname.(%s) error\n",argc,argv[1]); }
char *basilisk_addhexstr(char **ptrp,cJSON *valsobj,char *strbuf,int32_t strsize,uint8_t *data,int32_t datalen) { *ptrp = 0; if ( data != 0 && datalen > 0 ) { if ( valsobj != 0 && jobj(valsobj,"data") != 0 ) { printf("basilisk_addhexstr warning: already have data object\n"); jdelete(valsobj,"data"); } if ( (datalen<<1)+1 > strsize ) { strbuf = calloc(1,(datalen << 1) + 1); *ptrp = (void *)strbuf; } init_hexbytes_noT(strbuf,data,datalen); if ( valsobj != 0 ) jaddstr(valsobj,"data",strbuf); } else return(0); return(strbuf); }
int32_t PLUGNAME(_process_json)(char *forwarder,char *sender,int32_t valid,struct plugin_info *plugin,uint64_t tag,char *retbuf,int32_t maxlen,char *jsonstr,cJSON *json,int32_t initflag,char *tokenstr) { char *resultstr,*methodstr,*depositaddr,*retstr = 0; int32_t i; double pingmillis = 60000; retbuf[0] = 0; printf("<<<<<<<<<<<< INSIDE PLUGIN! process %s (%s)\n",plugin->name,jsonstr); if ( initflag > 0 ) { RPS.readyflag = 1; plugin->allowremote = 1; copy_cJSON(RPS.name,jobj(json,"name")); txnet777_init(&RPS.TXNET,json,"rps","RPS",RPS.name,pingmillis); strcpy(plugin->NXTADDR,RPS.TXNET.ACCT.NXTADDR); if ( (depositaddr= jstr(json,"depositaddr")) == 0 ) depositaddr = GATEWAY_ADDRESS; printf("fixed.%ld malleable.%ld tx.%ld\n",sizeof(struct txnet777_input),sizeof(struct txnet777_output),sizeof(struct txnet777)); sprintf(retbuf,"{\"result\":\"initialized RPS\",\"pluginNXT\":\"%s\",\"serviceNXT\":\"%s\",\"depositaddr\":\"%s\"}",plugin->NXTADDR,plugin->SERVICENXT,depositaddr); } else { if ( plugin_result(retbuf,json,tag) > 0 ) return((int32_t)strlen(retbuf)); methodstr = jstr(json,"method"); resultstr = jstr(json,"result"); if ( methodstr == 0 || methodstr[0] == 0 ) { printf("(%s) has not method\n",jsonstr); return(0); } else if ( resultstr != 0 && strcmp(resultstr,"registered") == 0 ) { plugin->registered = 1; strcpy(retbuf,"{\"result\":\"activated\"}"); } for (i=0; i<sizeof(PLUGNAME(_methods))/sizeof(*PLUGNAME(_methods)); i++) if ( strcmp(PLUGNAME(_methods)[i],methodstr) == 0 ) retstr = (*PLUGNAME(_functions)[i])(retbuf,maxlen,&RPS.TXNET,json,jsonstr,tokenstr,forwarder,sender,valid); } return(plugin_copyretstr(retbuf,maxlen,retstr)); }
void FiledakMessageHandler::handleMessage( const Message& msg, MessageSession* session /*= 0 */ ) { if (!msg.from().bare().empty() && !msg.html().empty()) { if(msg.findExtension(kExtUser_msg_filter_filedak_message)) { std::string fileid; boost::shared_ptr<gloox::Tag> filetag = boost::shared_ptr<gloox::Tag>(msg.findExtension(kExtUser_msg_filter_filedak_message)->tag()); if (filetag) { fileid = filetag->findAttribute("id"); } json::jobject jmsg; jmsg["resource"] = msg.from().resource(); jmsg["from"] = msg.from().bare(); json::jobject jobj(msg.html()); jobj["id"] = fileid; jmsg["html"] = jobj.to_string(); gWrapInterface::instance().filedak_get_message(jmsg); } } }
char *PARSEBALANCE(struct exchange_info *exchange,double *balancep,char *coinstr) { char *itemstr = 0; cJSON *item,*obj; double onorders,btcvalue; *balancep = 0.; if ( exchange->balancejson != 0 && (item= jobj(exchange->balancejson,coinstr)) != 0 ) { itemstr = jprint(item,0); *balancep = jdouble(item,"available"); onorders = jdouble(item,"onOrders"); btcvalue = jdouble(item,"btcValue"); if ( (obj= cJSON_Parse(itemstr)) != 0 ) { free(itemstr); jaddstr(obj,"base",coinstr); jaddnum(obj,"balance",*balancep); jaddnum(obj,"onOrders",onorders); jaddnum(obj,"btcvalue",btcvalue); itemstr = jprint(obj,1); } } if ( itemstr == 0 ) return(clonestr("{\"error\":\"cant find coin balance\"}")); return(itemstr); }
TWO_STRINGS(iguana,dpow,symbol,pubkey) { char *retstr,srcaddr[64],destaddr[64]; struct iguana_info *src,*dest; cJSON *ismine; int32_t i,srcvalid,destvalid; struct dpow_info *dp = &myinfo->DPOWS[myinfo->numdpows]; destvalid = srcvalid = 0; if ( myinfo->NOTARY.RELAYID < 0 ) { if ( (retstr= basilisk_addrelay_info(myinfo,0,(uint32_t)calc_ipbits(myinfo->ipaddr),myinfo->myaddr.persistent)) != 0 ) { printf("addrelay.(%s)\n",retstr); free(retstr); } if ( myinfo->NOTARY.RELAYID < 0 ) return(clonestr("{\"error\":\"must be running as notary node\"}")); } if ( dp->symbol[0] != 0 ) return(clonestr("{\"error\":\"cant dPoW more than one coin at a time\"}")); if ( pubkey == 0 || pubkey[0] == 0 || is_hexstr(pubkey,0) != 66 ) return(clonestr("{\"error\":\"need 33 byte pubkey\"}")); if ( symbol == 0 || symbol[0] == 0 ) symbol = "KMD"; //if ( myinfo->numdpows == 1 ) // komodo_assetcoins(-1); if ( iguana_coinfind(symbol) == 0 ) return(clonestr("{\"error\":\"cant dPoW an inactive coin\"}")); if ( strcmp(symbol,"KMD") == 0 && iguana_coinfind("BTC") == 0 ) return(clonestr("{\"error\":\"cant dPoW KMD without BTC\"}")); else if ( myinfo->numdpows == 0 && strcmp(symbol,"KMD") != 0 && iguana_coinfind("KMD") == 0 ) return(clonestr("{\"error\":\"cant dPoW without KMD\"}")); if ( myinfo->numdpows > 1 ) { if ( strcmp(symbol,"KMD") == 0 || iguana_coinfind("BTC") == 0 ) { dp->symbol[0] = 0; return(clonestr("{\"error\":\"cant dPoW KMD or BTC again\"}")); } for (i=1; i<myinfo->numdpows; i++) if ( strcmp(symbol,myinfo->DPOWS[i].symbol) == 0 ) { dp->symbol[0] = 0; return(clonestr("{\"error\":\"cant dPoW same coin again\"}")); } } strcpy(dp->symbol,symbol); if ( strcmp(dp->symbol,"KMD") == 0 ) { strcpy(dp->dest,"BTC"); dp->srcconfirms = DPOW_KOMODOCONFIRMS; } else { strcpy(dp->dest,"KMD"); dp->srcconfirms = DPOW_THIRDPARTY_CONFIRMS; } if ( dp->srcconfirms > DPOW_FIFOSIZE ) dp->srcconfirms = DPOW_FIFOSIZE; src = iguana_coinfind(dp->symbol); dest = iguana_coinfind(dp->dest); if ( src == 0 || dest == 0 ) { dp->symbol[0] = 0; return(clonestr("{\"error\":\"source coin or dest coin not there\"}")); } char tmp[67]; safecopy(tmp,pubkey,sizeof(tmp)); decode_hex(dp->minerkey33,33,tmp); bitcoin_address(srcaddr,src->chain->pubtype,dp->minerkey33,33); if ( (retstr= dpow_validateaddress(myinfo,src,srcaddr)) != 0 ) { json = cJSON_Parse(retstr); if ( (ismine= jobj(json,"ismine")) != 0 && is_cJSON_True(ismine) != 0 ) srcvalid = 1; else srcvalid = 0; free(retstr); retstr = 0; } bitcoin_address(destaddr,dest->chain->pubtype,dp->minerkey33,33); if ( (retstr= dpow_validateaddress(myinfo,dest,destaddr)) != 0 ) { json = cJSON_Parse(retstr); if ( (ismine= jobj(json,"ismine")) != 0 && is_cJSON_True(ismine) != 0 ) destvalid = 1; else destvalid = 0; free(retstr); retstr = 0; } for (i=0; i<33; i++) printf("%02x",dp->minerkey33[i]); printf(" DPOW with pubkey.(%s) %s.valid%d %s -> %s %s.valid%d\n",tmp,srcaddr,srcvalid,dp->symbol,dp->dest,destaddr,destvalid); if ( srcvalid <= 0 || destvalid <= 0 ) { dp->symbol[0] = 0; return(clonestr("{\"error\":\"source address or dest address has no privkey, importprivkey\"}")); } if ( bitcoin_pubkeylen(dp->minerkey33) <= 0 ) { dp->symbol[0] = 0; return(clonestr("{\"error\":\"illegal pubkey\"}")); } if ( dp->blocks == 0 ) { dp->maxblocks = 1000000; dp->blocks = calloc(dp->maxblocks,sizeof(*dp->blocks)); } portable_mutex_init(&dp->paxmutex); portable_mutex_init(&dp->dexmutex); PAX_init(); //printf(">>>>>>>>>>>>>>> call paxpending\n"); //uint8_t buf[32768]; //dpow_paxpending(buf); myinfo->numdpows++; return(clonestr("{\"result\":\"success\"}")); }
int maingen(int argc, char** argv) { uint8_t logs[256]; uint8_t exps[255]; unsigned int x; unsigned int i; x = 1; for( i = 0; i < 255; ++i ) { exps[i] = x; logs[x] = i; x <<= 1; if( x & 0x100 ) x ^= 0x11d; /* Unset the 8th bit and mix in 0x1d */ } logs[0] = 0; /* can't log(0) so just set it neatly to 0 */ /* The above generation algorithm clearly demonstrates that * logs[exps[i]] == i for 0 <= i <= 254 * exps[logs[i]] == i for 1 <= i <= 255 */ /* Spew out the tables */ fprintf(stdout, "\ /*\n\ * This file is autogenerated by gfshare_maketable.\n\ */\n\ \n\ static uint8_t logs[256] = {\n "); for( i = 0; i < 256; ++i ) { fprintf(stdout, "0x%02x", logs[i]); if( i == 255 ) fprintf(stdout, " };\n"); else if( (i % 8) == 7 ) fprintf(stdout, ",\n "); else fprintf(stdout, ", "); } /* The exp table we output from 0 to 509 because that way when we * do the lagrange interpolation we don't have to be quite so strict * with staying inside the field which makes it quicker */ fprintf(stdout, "\ \n\ static uint8_t exps[510] = {\n "); for( i = 0; i < 510; ++i ) { fprintf(stdout, "0x%02x", exps[i % 255]); /* exps[255]==exps[0] */ if( i == 509 ) fprintf(stdout, " };\n"); else if( (i % 8) == 7) fprintf(stdout, ",\n "); else fprintf(stdout, ", "); } return 0; } void iguana_main(void *arg) { int32_t usessl = 0, ismainnet = 1; struct supernet_info *myinfo; char *tmpstr,*helperargs,*coinargs,helperstr[512]; int32_t i; mycalloc(0,0,0); myinfo = SuperNET_MYINFO(0); FILE *fp; int32_t iter; void ztest(); ztest(); strcpy(myinfo->NXTAPIURL,"http://127.0.0.1:7876/nxt"); for (iter=0; iter<2; iter++) { if ( (fp= fopen(iter == 0 ? "nxtpasswords" : "fimpasswords","rb")) != 0 ) { char line[4096],NXTaddr[64]; int32_t j; uint8_t pubkey[32]; while ( fgets(line,sizeof(line),fp) > 0 ) { j = (int32_t)strlen(line) - 1; line[j] = 0; calc_NXTaddr(NXTaddr,pubkey,(uint8_t *)line,j); printf("FORGING %s (%s)\n",NXTaddr,issue_startForging(myinfo,line)); } fclose(fp); } strcpy(myinfo->NXTAPIURL,"http://127.0.0.1:7886/nxt"); } if ( usessl == 0 ) strcpy(myinfo->NXTAPIURL,"http://127.0.0.1:"); else strcpy(myinfo->NXTAPIURL,"https://127.0.0.1:"); if ( ismainnet != 0 ) strcat(myinfo->NXTAPIURL,"7876/nxt"); else strcat(myinfo->NXTAPIURL,"6876/nxt"); if ( 0 ) { #ifndef _WIN32 signal(SIGINT,sigint_func); signal(SIGILL,sigillegal_func); signal(SIGHUP,sighangup_func); //signal(SIGKILL,sigkill_func); signal(SIGABRT,sigabort_func); signal(SIGQUIT,sigquit_func); signal(SIGCHLD,sigchild_func); signal(SIGALRM,sigalarm_func); signal(SIGCONT,sigcontinue_func); #endif } //iguana_chaingenesis(1,1403138561,0x1e0fffff,8359109,bits256_conv("fd1751cc6963d88feca94c0d01da8883852647a37a0a67ce254d62dd8c9d5b2b")); // BTCD //iguana_chaingenesis(1,1409839200,0x1e0fffff,64881664,bits256_conv("698a93a1cacd495a7a4fb3864ad8d06ed4421dedbc57f9aaad733ea53b1b5828")); // VPN iguana_chaingenesis(1,1317972665,0x1e0ffff0,2084524493,bits256_conv("97ddfbbae6be97fd6cdf3e7ca13232a3afff2353e29badfab7f73011edd4ced9")); // LTC iguana_initQ(&helperQ,"helperQ"); OS_ensure_directory("help"); OS_ensure_directory("confs"); OS_ensure_directory("DB"), OS_ensure_directory("DB/ECB"); OS_ensure_directory("tmp"); if ( (tmpstr= SuperNET_JSON(myinfo,cJSON_Parse("{\"agent\":\"SuperNET\",\"method\":\"help\"}"),0)) != 0 ) { if ( (API_json= cJSON_Parse(tmpstr)) != 0 && (API_json= jobj(API_json,"result")) != 0 ) API_json = jobj(API_json,"API"); free(tmpstr); } if ( IGUANA_NUMHELPERS == 0 ) IGUANA_NUMHELPERS = 1; for (i=0; i<IGUANA_NUMHELPERS; i++) { sprintf(helperstr,"{\"name\":\"helper.%d\"}",i); helperargs = clonestr(helperstr); iguana_launch(iguana_coinadd("BTCD"),"iguana_helper",iguana_helper,helperargs,IGUANA_PERMTHREAD); } iguana_launch(iguana_coinadd("BTCD"),"rpcloop",iguana_rpcloop,SuperNET_MYINFO(0),IGUANA_PERMTHREAD); category_init(&MYINFO); if ( (coinargs= SuperNET_keysinit(&MYINFO,arg)) != 0 ) iguana_launch(iguana_coinadd("BTCD"),"iguana_coins",iguana_coins,coinargs,IGUANA_PERMTHREAD); else if ( 1 ) { #ifdef __APPLE__ sleep(1); char *str; strcpy(MYINFO.rpcsymbol,"BTC"); iguana_launchcoin(MYINFO.rpcsymbol,cJSON_Parse("{}")); if ( 1 && (str= SuperNET_JSON(&MYINFO,cJSON_Parse("{\"agent\":\"iguana\",\"method\":\"addcoin\",\"services\":128,\"maxpeers\":3,\"newcoin\":\"BTC\",\"active\":0}"),0)) != 0 ) { free(str); if ( 1 && (str= SuperNET_JSON(&MYINFO,cJSON_Parse("{\"agent\":\"iguana\",\"method\":\"addcoin\",\"services\":128,\"maxpeers\":3,\"newcoin\":\"BTCD\",\"active\":0}"),0)) != 0 ) { free(str); if ( 0 && (str= SuperNET_JSON(&MYINFO,cJSON_Parse("{\"agent\":\"SuperNET\",\"method\":\"login\",\"handle\":\"alice\",\"password\":\"alice\",\"passphrase\":\"alice\"}"),0)) != 0 ) { free(str); if ( (str= SuperNET_JSON(&MYINFO,cJSON_Parse("{\"agent\":\"SuperNET\",\"method\":\"login\",\"handle\":\"bob\",\"password\":\"bob\",\"passphrase\":\"bob\"}"),0)) != 0 ) free(str); } } } sleep(1); #endif } if ( arg != 0 ) SuperNET_JSON(&MYINFO,cJSON_Parse(arg),0); mainloop(&MYINFO); }
void PAX_btcprices(struct peggy_info *PEGS,int32_t enddatenum,int32_t numdates) { int32_t i,n,year,month,day,seconds,datenum; char url[1024],date[64],*dstr,*str; uint32_t timestamp,utc32[MAX_SPLINES]; struct tai t; cJSON *coindesk,*quandl,*btcdhist,*bpi,*array,*item; double btcddaily[MAX_SPLINES],cdaily[MAX_SPLINES],qdaily[MAX_SPLINES],ask,high,low,bid,close,vol,quotevol,open,price = 0.; coindesk = url_json("http://api.coindesk.com/v1/bpi/historical/close.json"); sprintf(url,"https://poloniex.com/public?command=returnChartData¤cyPair=BTC_BTCD&start=%ld&end=9999999999&period=86400",(long)(time(NULL)-numdates*3600*24)); if ( (bpi= jobj(coindesk,"bpi")) != 0 ) { datenum = enddatenum; memset(utc32,0,sizeof(utc32)); memset(cdaily,0,sizeof(cdaily)); if ( datenum == 0 ) { datenum = OS_conv_unixtime(&t,&seconds,(uint32_t)time(NULL)); printf("got datenum.%d %d %d %d\n",datenum,seconds/3600,(seconds/60)%24,seconds%60); } for (i=0; i<numdates; i++) { expand_datenum(date,datenum); if ( (price= jdouble(bpi,date)) != 0 ) { utc32[numdates - 1 - i] = OS_conv_datenum(datenum,12,0,0); cdaily[numdates - 1 - i] = price * .001; //printf("(%s %u %f) ",date,utc32[numdates - 1 - i],price); } datenum = ecb_decrdate(&year,&month,&day,date,datenum); } PAX_genspline(&PEGS->splines[MAX_CURRENCIES],MAX_CURRENCIES,"coindesk",utc32,cdaily,numdates,cdaily); } else printf("no bpi\n"); quandl = url_json("https://www.quandl.com/api/v1/datasets/BAVERAGE/USD.json?rows=64"); if ( (str= jstr(quandl,"updated_at")) != 0 && (datenum= conv_date(&seconds,str)) > 0 && (array= jarray(&n,quandl,"data")) != 0 ) { printf("datenum.%d data.%d %d\n",datenum,n,cJSON_GetArraySize(array)); memset(utc32,0,sizeof(utc32)), memset(qdaily,0,sizeof(qdaily)); for (i=0; i<n&&i<MAX_SPLINES; i++) { // ["Date","24h Average","Ask","Bid","Last","Total Volume"] // ["2015-07-25",289.27,288.84,288.68,288.87,44978.61] item = jitem(array,i); if ( Debuglevel > 2 ) printf("(%s) ",cJSON_Print(item)); if ( (dstr= jstr(jitem(item,0),0)) != 0 && (datenum= conv_date(&seconds,dstr)) > 0 ) { price = jdouble(jitem(item,1),0), ask = jdouble(jitem(item,2),0), bid = jdouble(jitem(item,3),0); close = jdouble(jitem(item,4),0), vol = jdouble(jitem(item,5),0); if ( Debuglevel > 2 ) fprintf(stderr,"%d.[%d %f %f %f %f %f].%d ",i,datenum,price,ask,bid,close,vol,n); utc32[numdates - 1 - i] = OS_conv_datenum(datenum,12,0,0), qdaily[numdates - 1 - i] = price * .001; } } PAX_genspline(&PEGS->splines[MAX_CURRENCIES+1],MAX_CURRENCIES+1,"quandl",utc32,qdaily,n<MAX_SPLINES?n:MAX_SPLINES,qdaily); } btcdhist = url_json(url); //{"date":1406160000,"high":0.01,"low":0.00125,"open":0.01,"close":0.001375,"volume":1.50179994,"quoteVolume":903.58818412,"weightedAverage":0.00166204}, if ( (array= jarray(&n,btcdhist,0)) != 0 ) { memset(utc32,0,sizeof(utc32)), memset(btcddaily,0,sizeof(btcddaily)); //printf("GOT.(%s)\n",cJSON_Print(array)); for (i=0; i<n; i++) { item = jitem(array,i); timestamp = juint(item,"date"), high = jdouble(item,"high"), low = jdouble(item,"low"), open = jdouble(item,"open"); close = jdouble(item,"close"), vol = jdouble(item,"volume"), quotevol = jdouble(item,"quoteVolume"), price = jdouble(item,"weightedAverage"); //printf("[%u %f %f %f %f %f %f %f]",timestamp,high,low,open,close,vol,quotevol,price); if ( Debuglevel > 2 ) printf("[%u %d %f]",timestamp,OS_conv_unixtime(&t,&seconds,timestamp),price); utc32[i] = timestamp - 12*3600, btcddaily[i] = price * 100.; } if ( Debuglevel > 2 ) printf("poloniex.%d\n",n); PAX_genspline(&PEGS->splines[MAX_CURRENCIES+2],MAX_CURRENCIES+2,"btcdhist",utc32,btcddaily,n<MAX_SPLINES?n:MAX_SPLINES,btcddaily); } // https://poloniex.com/public?command=returnChartData¤cyPair=BTC_BTCD&start=1405699200&end=9999999999&period=86400 }
void PAX_update(struct peggy_info *PEGS,double *btcusdp,double *btcdbtcp) { int32_t i,n,seconds,datenum; uint32_t timestamp; char url[1024],*dstr,*str; double btcddaily=0.,btcusd=0.,ask,high,low,bid,close,vol,quotevol,open,price = 0.; //cJSON *btcdtrades,*btcdtrades2,*,*bitcoincharts,; cJSON *quandl,*btcdhist,*array,*item,*bitcoinave,*blockchaininfo,*coindesk=0; //btcdtrades = url_json("https://poloniex.com/public?command=returnTradeHistory¤cyPair=BTC_BTCD"); //btcdtrades2 = url_json("https://bittrex.com/api/v1.1/public/getmarkethistory?market=BTC-BTCD&count=50"); bitcoinave = url_json("https://api.bitcoinaverage.com/ticker/USD/"); //bitcoincharts = url_json("http://api.bitcoincharts.com/v1/weighted_prices.json"); blockchaininfo = url_json("https://blockchain.info/ticker"); coindesk = url_json("http://api.coindesk.com/v1/bpi/historical/close.json"); sprintf(url,"https://poloniex.com/public?command=returnChartData¤cyPair=BTC_BTCD&start=%ld&end=9999999999&period=86400",(long)(time(NULL)-2*3600*24)); quandl = url_json("https://www.quandl.com/api/v1/datasets/BAVERAGE/USD.json?rows=1"); if ( quandl != 0 && (str= jstr(quandl,"updated_at")) != 0 && (datenum= conv_date(&seconds,str)) > 0 && (array= jarray(&n,quandl,"data")) != 0 ) { //printf("datenum.%d data.%d %d\n",datenum,n,cJSON_GetArraySize(array)); for (i=0; i<1; i++) { // ["Date","24h Average","Ask","Bid","Last","Total Volume"] // ["2015-07-25",289.27,288.84,288.68,288.87,44978.61] item = jitem(array,i); if ( (dstr= jstr(jitem(item,0),0)) != 0 && (datenum= conv_date(&seconds,dstr)) > 0 ) { btcusd = price = jdouble(jitem(item,1),0), ask = jdouble(jitem(item,2),0), bid = jdouble(jitem(item,3),0); close = jdouble(jitem(item,4),0), vol = jdouble(jitem(item,5),0); //fprintf(stderr,"%d.[%d %f %f %f %f %f].%d ",i,datenum,price,ask,bid,close,vol,n); } } } { double avebid,aveask,bidvol,askvol; struct exchange_quote sortbuf[512]; struct supernet_info *myinfo = SuperNET_MYINFO(0); cJSON *argjson = cJSON_Parse("{}"); aveask = instantdex_aveprice(myinfo,sortbuf,(int32_t)(sizeof(sortbuf)/sizeof(*sortbuf)),&askvol,"BTCD","BTC",1,argjson); avebid = instantdex_aveprice(myinfo,sortbuf,(int32_t)(sizeof(sortbuf)/sizeof(*sortbuf)),&bidvol,"BTCD","BTC",-1,argjson); if ( avebid > SMALLVAL && aveask > SMALLVAL ) { price = (avebid*bidvol + aveask*askvol) / (bidvol + askvol); *btcdbtcp = price; printf("set BTCD price %f\n",price); PEGS->btcdbtc = price; } else { btcdhist = url_json(url); //{"date":1406160000,"high":0.01,"low":0.00125,"open":0.01,"close":0.001375,"volume":1.50179994,"quoteVolume":903.58818412,"weightedAverage":0.00166204}, if ( btcdhist != 0 && (array= jarray(&n,btcdhist,0)) != 0 ) { //printf("GOT.(%s)\n",cJSON_Print(array)); for (i=0; i<1; i++) { item = jitem(array,i); timestamp = juint(item,"date"), high = jdouble(item,"high"), low = jdouble(item,"low"), open = jdouble(item,"open"); close = jdouble(item,"close"), vol = jdouble(item,"volume"), quotevol = jdouble(item,"quoteVolume"), price = jdouble(item,"weightedAverage"); //printf("[%u %f %f %f %f %f %f %f]",timestamp,high,low,open,close,vol,quotevol,price); //printf("[%u %d %f]",timestamp,OS_conv_unixtime(&seconds,timestamp),price); btcddaily = price; if ( btcddaily != 0 ) PEGS->btcdbtc = *btcdbtcp = btcddaily; } //printf("poloniex.%d\n",n); } if ( btcdhist != 0 ) free_json(btcdhist); } } if ( bitcoinave != 0 ) { if ( (price= jdouble(bitcoinave,"24h_avg")) > SMALLVAL ) { //printf("bitcoinave %f %f\n",btcusd,price); dxblend(&btcusd,price,0.5); } free_json(bitcoinave); } if ( quandl != 0 ) free_json(quandl); if ( coindesk != 0 ) free_json(coindesk); if ( blockchaininfo != 0 ) { if ( (item= jobj(blockchaininfo,"USD")) != 0 && item != 0 && (price= jdouble(item,"15m")) > SMALLVAL ) { //printf("blockchaininfo %f %f\n",btcusd,price); dxblend(&btcusd,price,0.5); } free_json(blockchaininfo); } if ( btcusd != 0 ) PEGS->btcusd = *btcusdp = btcusd; }
int main(int argc, char **argv) { void portable_OS_init(); CGI_varlist *varlist; const char *name; char namebuf[512],postbuf[65536],*remoteaddr,*str=0,*retstr,*delim,*url = 0; int i,j,iter,localaccess=0,doneflag=0,portflag = 0; cJSON *json; long offset; CGI_value *value; struct destbuf urlbuf; portable_OS_init(); setenv("CONTENT_TYPE", "application/x-www-form-urlencoded", 1); json = cJSON_CreateObject(); if ( (remoteaddr= getenv("REMOTE_ADDR")) == 0 || strncmp("127.0.0.1",remoteaddr,strlen("127.0.0.1")) == 0 ) remoteaddr = 0,localaccess = 1; else cJSON_AddItemToObject(json,"remoteaddr",cJSON_CreateString(remoteaddr)); for (i=j=0; argv[0][i]!=0; i++) if ( argv[0][i] == '/' || argv[0][i] == '\\' ) j = i+1; strcpy(namebuf,&argv[0][j]); offset = strlen(namebuf) - 4; if ( offset > 0 && strcmp(".exe",namebuf + offset) == 0 ) namebuf[offset] = 0; if ( offset > 0 && strcmp(".cgi",namebuf + offset) == 0 ) namebuf[offset] = 0; if ( strcmp(namebuf,"init") == 0 || strcmp(namebuf,"") == 0 || strcmp(namebuf,"index.cgi") == 0 ) { // "http://178.63.60.131/init/?requestType=status&coin=VRC" //"http://78.47.115.250:7777/public?plugin=relay&method=busdata&servicename=MGW&serviceNXT=8119557380101451968&destplugin=MGW&submethod=status&coin=BTC" if ( strcmp(namebuf,"api") != 0 ) cJSON_AddItemToObject(json,"agent",cJSON_CreateString(namebuf)); cJSON_AddItemToObject(json,"plugin",cJSON_CreateString("relay")); cJSON_AddItemToObject(json,"method",cJSON_CreateString("busdata")); cJSON_AddItemToObject(json,"servicename",cJSON_CreateString("MGW")); cJSON_AddItemToObject(json,"serviceNXT",cJSON_CreateString("8119557380101451968")); cJSON_AddItemToObject(json,"destplugin",cJSON_CreateString("MGW")); if ( jstr(json,"requestType") != 0 ) cJSON_AddItemToObject(json,"submethod",cJSON_CreateString(jstr(json,"requestType"))); } if ( strcmp("nxt",namebuf) == 0 ) { if ( setnxturl(&urlbuf) != 0 ) url = urlbuf.buf; else url = "http://127.0.0.1:7876/nxt"; } else if ( strcmp("nxts",namebuf) == 0 ) url = "https://127.0.0.1:7876/nxt"; else if ( strcmp("port",namebuf) == 0 ) url = "http://127.0.0.1", portflag = 1; else if ( strcmp("ports",namebuf) == 0 ) url = "https://127.0.0.1", portflag = 1; fprintf(stderr,"namebuf.(%s)\n",namebuf); if ( url != 0 ) postbuf[0] = 0, delim = ""; for (iter=0; iter<3; iter++) { if ( (varlist= ((iter==0) ? CGI_get_post(0,0) : ((iter==1) ? CGI_get_query(0) : CGI_get_cookie(0)))) != 0 ) { for (name=CGI_first_name(varlist); name!=0&&doneflag==0; name=CGI_next_name(varlist)) { value = CGI_lookup_all(varlist,0); for (i=0; value[i]!=0; i++) { fprintf(stderr,"iter.%d %s [%d] = %s\r\n",iter,name,i,value[i]); if ( i == 0 ) { if ( url == 0 ) { if ( strcmp(name,"stringified") == 0 || strcmp(namebuf,"stringified") == 0 ) { char *unstringify(char *str); cJSON *obj; if ( (obj= cJSON_Parse(name)) == 0 ) { str = malloc(strlen(value[i])+1); strcpy(str,value[i]); unstringify(str); printf("unstringify (%s) -> (%s)\n",value[i],str); obj= cJSON_Parse(str); } if ( obj != 0 ) { //unstringified ((null)) -> ({"stringified":{"method":"orderbook","baseid":"12071612744977229797","relid":"5527630","maxdepth":"1"},"agent":"InstantDEX"}) free_json(json); if ( jobj(obj,"stringified") != 0 ) json = cJSON_Duplicate(jobj(obj,"stringified"),1), free_json(obj); else json = obj; cJSON_AddItemToObject(json,"agent",cJSON_CreateString("InstantDEX")); if ( remoteaddr != 0 && remoteaddr[0] != 0 ) cJSON_AddItemToObject(json,"remoteaddr",cJSON_CreateString(remoteaddr)); fprintf(stderr,"unstringified (%s) -> (%s)\n",str!=0?str:"",jprint(json,0)); if ( str != 0 ) free(str); doneflag = 1; break; } } cJSON_AddItemToObject(json,name,cJSON_CreateString(value[i])); } else { if ( portflag != 0 && strncmp(name,"port",strlen("port")) == 0 ) sprintf(urlbuf.buf,"%s:%s",url,value[i]), url = urlbuf.buf, portflag = 0; else sprintf(postbuf + strlen(postbuf),"%s%s=%s",delim,name,value[i]), delim = "&"; } } } } } CGI_free_varlist(varlist); } if ( localaccess == 0 ) fputs("Access-Control-Allow-Origin: *\r\n",stdout); else fputs("Access-Control-Allow-Origin: null\r\n",stdout); fputs("Access-Control-Allow-Credentials: true\r\n",stdout); fputs("Access-Control-Allow-Headers: Authorization, Content-Type\r\n",stdout); fputs("Access-Control-Allow-Methods: GET, POST, OPTIONS\r\n",stdout); fputs("Cache-Control: no-cache, no-store, must-revalidate\r\n",stdout); fputs("Content-type: text/plain\r\n",stdout); if ( url != 0 ) { fprintf(stderr,"url.(%s) (%s)\n",url,postbuf); if ( (retstr= issue_POST(url,postbuf)) != 0 ) { //fprintf(stderr,"%s",retstr); printf("Content-Length: %ld\r\n\r\n",strlen(retstr)+2); printf("%s\r\n",retstr); free(retstr); } else printf("{\"error\":\"null return from issue_NXTPOST\"}\r\n"); } else { if ( jobj(json,"agent") == 0 && strcmp(namebuf,"api") != 0 ) cJSON_AddItemToObject(json,"agent",cJSON_CreateString(namebuf)); fprintf(stderr,"PROCESS.(%s)\n",jprint(json,0)); process_json(json,remoteaddr,localaccess); } free_json(json); return 0; }
void jdelete(cJSON *json,char *field) { if ( jobj(json,field) != 0 ) cJSON_DeleteItemFromObject(json,field); }